babylon.no-module.max.js 5.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else if (otherMesh.subMeshes) {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /** @hidden */
  159. this._bonesComputationForcedToCPU = false;
  160. this._uniformBuffersNames = {};
  161. this._isReady = false;
  162. this._compilationError = "";
  163. this.name = baseName;
  164. if (attributesNamesOrOptions.attributes) {
  165. var options = attributesNamesOrOptions;
  166. this._engine = uniformsNamesOrEngine;
  167. this._attributesNames = options.attributes;
  168. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  169. this._samplers = options.samplers.slice();
  170. this.defines = options.defines;
  171. this.onError = options.onError;
  172. this.onCompiled = options.onCompiled;
  173. this._fallbacks = options.fallbacks;
  174. this._indexParameters = options.indexParameters;
  175. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  176. if (options.uniformBuffersNames) {
  177. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  178. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  179. }
  180. }
  181. }
  182. else {
  183. this._engine = engine;
  184. this.defines = defines;
  185. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  186. this._samplers = samplers ? samplers.slice() : [];
  187. this._attributesNames = attributesNamesOrOptions;
  188. this.onError = onError;
  189. this.onCompiled = onCompiled;
  190. this._indexParameters = indexParameters;
  191. this._fallbacks = fallbacks;
  192. }
  193. this.uniqueId = Effect._uniqueIdSeed++;
  194. var vertexSource;
  195. var fragmentSource;
  196. if (baseName.vertexElement) {
  197. vertexSource = document.getElementById(baseName.vertexElement);
  198. if (!vertexSource) {
  199. vertexSource = baseName.vertexElement;
  200. }
  201. }
  202. else {
  203. vertexSource = baseName.vertex || baseName;
  204. }
  205. if (baseName.fragmentElement) {
  206. fragmentSource = document.getElementById(baseName.fragmentElement);
  207. if (!fragmentSource) {
  208. fragmentSource = baseName.fragmentElement;
  209. }
  210. }
  211. else {
  212. fragmentSource = baseName.fragment || baseName;
  213. }
  214. this._loadVertexShader(vertexSource, function (vertexCode) {
  215. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  216. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  217. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  218. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  219. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  220. if (baseName) {
  221. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  222. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  223. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  224. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  225. }
  226. else {
  227. _this._vertexSourceCode = migratedVertexCode;
  228. _this._fragmentSourceCode = migratedFragmentCode;
  229. }
  230. _this._prepareEffect();
  231. });
  232. });
  233. });
  234. });
  235. });
  236. });
  237. }
  238. Object.defineProperty(Effect.prototype, "onBindObservable", {
  239. /**
  240. * Observable that will be called when effect is bound.
  241. */
  242. get: function () {
  243. if (!this._onBindObservable) {
  244. this._onBindObservable = new BABYLON.Observable();
  245. }
  246. return this._onBindObservable;
  247. },
  248. enumerable: true,
  249. configurable: true
  250. });
  251. Object.defineProperty(Effect.prototype, "key", {
  252. /**
  253. * Unique key for this effect
  254. */
  255. get: function () {
  256. return this._key;
  257. },
  258. enumerable: true,
  259. configurable: true
  260. });
  261. /**
  262. * If the effect has been compiled and prepared.
  263. * @returns if the effect is compiled and prepared.
  264. */
  265. Effect.prototype.isReady = function () {
  266. return this._isReady;
  267. };
  268. /**
  269. * The engine the effect was initialized with.
  270. * @returns the engine.
  271. */
  272. Effect.prototype.getEngine = function () {
  273. return this._engine;
  274. };
  275. /**
  276. * The compiled webGL program for the effect
  277. * @returns the webGL program.
  278. */
  279. Effect.prototype.getProgram = function () {
  280. return this._program;
  281. };
  282. /**
  283. * The set of names of attribute variables for the shader.
  284. * @returns An array of attribute names.
  285. */
  286. Effect.prototype.getAttributesNames = function () {
  287. return this._attributesNames;
  288. };
  289. /**
  290. * Returns the attribute at the given index.
  291. * @param index The index of the attribute.
  292. * @returns The location of the attribute.
  293. */
  294. Effect.prototype.getAttributeLocation = function (index) {
  295. return this._attributes[index];
  296. };
  297. /**
  298. * Returns the attribute based on the name of the variable.
  299. * @param name of the attribute to look up.
  300. * @returns the attribute location.
  301. */
  302. Effect.prototype.getAttributeLocationByName = function (name) {
  303. var index = this._attributesNames.indexOf(name);
  304. return this._attributes[index];
  305. };
  306. /**
  307. * The number of attributes.
  308. * @returns the numnber of attributes.
  309. */
  310. Effect.prototype.getAttributesCount = function () {
  311. return this._attributes.length;
  312. };
  313. /**
  314. * Gets the index of a uniform variable.
  315. * @param uniformName of the uniform to look up.
  316. * @returns the index.
  317. */
  318. Effect.prototype.getUniformIndex = function (uniformName) {
  319. return this._uniformsNames.indexOf(uniformName);
  320. };
  321. /**
  322. * Returns the attribute based on the name of the variable.
  323. * @param uniformName of the uniform to look up.
  324. * @returns the location of the uniform.
  325. */
  326. Effect.prototype.getUniform = function (uniformName) {
  327. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  328. };
  329. /**
  330. * Returns an array of sampler variable names
  331. * @returns The array of sampler variable neames.
  332. */
  333. Effect.prototype.getSamplers = function () {
  334. return this._samplers;
  335. };
  336. /**
  337. * The error from the last compilation.
  338. * @returns the error string.
  339. */
  340. Effect.prototype.getCompilationError = function () {
  341. return this._compilationError;
  342. };
  343. /**
  344. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  345. * @param func The callback to be used.
  346. */
  347. Effect.prototype.executeWhenCompiled = function (func) {
  348. if (this.isReady()) {
  349. func(this);
  350. return;
  351. }
  352. this.onCompileObservable.add(function (effect) {
  353. func(effect);
  354. });
  355. };
  356. /** @hidden */
  357. Effect.prototype._loadVertexShader = function (vertex, callback) {
  358. if (BABYLON.Tools.IsWindowObjectExist()) {
  359. // DOM element ?
  360. if (vertex instanceof HTMLElement) {
  361. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  362. callback(vertexCode);
  363. return;
  364. }
  365. }
  366. // Base64 encoded ?
  367. if (vertex.substr(0, 7) === "base64:") {
  368. var vertexBinary = window.atob(vertex.substr(7));
  369. callback(vertexBinary);
  370. return;
  371. }
  372. // Is in local store ?
  373. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  374. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  375. return;
  376. }
  377. var vertexShaderUrl;
  378. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  379. vertexShaderUrl = vertex;
  380. }
  381. else {
  382. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  383. }
  384. // Vertex shader
  385. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  386. };
  387. /** @hidden */
  388. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  389. if (BABYLON.Tools.IsWindowObjectExist()) {
  390. // DOM element ?
  391. if (fragment instanceof HTMLElement) {
  392. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  393. callback(fragmentCode);
  394. return;
  395. }
  396. }
  397. // Base64 encoded ?
  398. if (fragment.substr(0, 7) === "base64:") {
  399. var fragmentBinary = window.atob(fragment.substr(7));
  400. callback(fragmentBinary);
  401. return;
  402. }
  403. // Is in local store ?
  404. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  405. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  406. return;
  407. }
  408. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  409. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  410. return;
  411. }
  412. var fragmentShaderUrl;
  413. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  414. fragmentShaderUrl = fragment;
  415. }
  416. else {
  417. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  418. }
  419. // Fragment shader
  420. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  421. };
  422. /** @hidden */
  423. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  424. // Rebuild shaders source code
  425. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  426. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  427. vertexCode = prefix + vertexCode;
  428. fragmentCode = prefix + fragmentCode;
  429. // Number lines of shaders source code
  430. var i = 2;
  431. var regex = /\n/gm;
  432. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  433. i = 2;
  434. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  435. // Dump shaders name and formatted source code
  436. if (this.name.vertexElement) {
  437. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  438. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  439. }
  440. else if (this.name.vertex) {
  441. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  442. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  443. }
  444. else {
  445. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  446. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  447. }
  448. };
  449. ;
  450. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  451. var preparedSourceCode = this._processPrecision(sourceCode);
  452. if (this._engine.webGLVersion == 1) {
  453. callback(preparedSourceCode);
  454. return;
  455. }
  456. // Already converted
  457. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  458. callback(preparedSourceCode.replace("#version 300 es", ""));
  459. return;
  460. }
  461. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  462. // Remove extensions
  463. // #extension GL_OES_standard_derivatives : enable
  464. // #extension GL_EXT_shader_texture_lod : enable
  465. // #extension GL_EXT_frag_depth : enable
  466. // #extension GL_EXT_draw_buffers : require
  467. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  468. var result = preparedSourceCode.replace(regex, "");
  469. // Migrate to GLSL v300
  470. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  471. result = result.replace(/attribute[ \t]/g, "in ");
  472. result = result.replace(/[ \t]attribute/g, " in");
  473. if (isFragment) {
  474. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  475. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  476. result = result.replace(/texture2D\s*\(/g, "texture(");
  477. result = result.replace(/textureCube\s*\(/g, "texture(");
  478. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  479. result = result.replace(/gl_FragColor/g, "glFragColor");
  480. result = result.replace(/gl_FragData/g, "glFragData");
  481. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  482. }
  483. callback(result);
  484. };
  485. Effect.prototype._processIncludes = function (sourceCode, callback) {
  486. var _this = this;
  487. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  488. var match = regex.exec(sourceCode);
  489. var returnValue = new String(sourceCode);
  490. while (match != null) {
  491. var includeFile = match[1];
  492. // Uniform declaration
  493. if (includeFile.indexOf("__decl__") !== -1) {
  494. includeFile = includeFile.replace(/__decl__/, "");
  495. if (this._engine.supportsUniformBuffers) {
  496. includeFile = includeFile.replace(/Vertex/, "Ubo");
  497. includeFile = includeFile.replace(/Fragment/, "Ubo");
  498. }
  499. includeFile = includeFile + "Declaration";
  500. }
  501. if (Effect.IncludesShadersStore[includeFile]) {
  502. // Substitution
  503. var includeContent = Effect.IncludesShadersStore[includeFile];
  504. if (match[2]) {
  505. var splits = match[3].split(",");
  506. for (var index = 0; index < splits.length; index += 2) {
  507. var source = new RegExp(splits[index], "g");
  508. var dest = splits[index + 1];
  509. includeContent = includeContent.replace(source, dest);
  510. }
  511. }
  512. if (match[4]) {
  513. var indexString = match[5];
  514. if (indexString.indexOf("..") !== -1) {
  515. var indexSplits = indexString.split("..");
  516. var minIndex = parseInt(indexSplits[0]);
  517. var maxIndex = parseInt(indexSplits[1]);
  518. var sourceIncludeContent = includeContent.slice(0);
  519. includeContent = "";
  520. if (isNaN(maxIndex)) {
  521. maxIndex = this._indexParameters[indexSplits[1]];
  522. }
  523. for (var i = minIndex; i < maxIndex; i++) {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  531. }
  532. }
  533. else {
  534. if (!this._engine.supportsUniformBuffers) {
  535. // Ubo replacement
  536. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  537. return p1 + "{X}";
  538. });
  539. }
  540. includeContent = includeContent.replace(/\{X\}/g, indexString);
  541. }
  542. }
  543. // Replace
  544. returnValue = returnValue.replace(match[0], includeContent);
  545. }
  546. else {
  547. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  548. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  549. Effect.IncludesShadersStore[includeFile] = fileContent;
  550. _this._processIncludes(returnValue, callback);
  551. });
  552. return;
  553. }
  554. match = regex.exec(sourceCode);
  555. }
  556. callback(returnValue);
  557. };
  558. Effect.prototype._processPrecision = function (source) {
  559. if (source.indexOf("precision highp float") === -1) {
  560. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  561. source = "precision mediump float;\n" + source;
  562. }
  563. else {
  564. source = "precision highp float;\n" + source;
  565. }
  566. }
  567. else {
  568. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  569. source = source.replace("precision highp float", "precision mediump float");
  570. }
  571. }
  572. return source;
  573. };
  574. /**
  575. * Recompiles the webGL program
  576. * @param vertexSourceCode The source code for the vertex shader.
  577. * @param fragmentSourceCode The source code for the fragment shader.
  578. * @param onCompiled Callback called when completed.
  579. * @param onError Callback called on error.
  580. * @hidden
  581. */
  582. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  583. var _this = this;
  584. this._isReady = false;
  585. this._vertexSourceCodeOverride = vertexSourceCode;
  586. this._fragmentSourceCodeOverride = fragmentSourceCode;
  587. this.onError = function (effect, error) {
  588. if (onError) {
  589. onError(error);
  590. }
  591. };
  592. this.onCompiled = function () {
  593. var scenes = _this.getEngine().scenes;
  594. for (var i = 0; i < scenes.length; i++) {
  595. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  596. }
  597. if (onCompiled) {
  598. onCompiled(_this._program);
  599. }
  600. };
  601. this._fallbacks = null;
  602. this._prepareEffect();
  603. };
  604. /**
  605. * Gets the uniform locations of the the specified variable names
  606. * @param names THe names of the variables to lookup.
  607. * @returns Array of locations in the same order as variable names.
  608. */
  609. Effect.prototype.getSpecificUniformLocations = function (names) {
  610. var engine = this._engine;
  611. return engine.getUniforms(this._program, names);
  612. };
  613. /**
  614. * Prepares the effect
  615. * @hidden
  616. */
  617. Effect.prototype._prepareEffect = function () {
  618. var attributesNames = this._attributesNames;
  619. var defines = this.defines;
  620. var fallbacks = this._fallbacks;
  621. this._valueCache = {};
  622. var previousProgram = this._program;
  623. try {
  624. var engine = this._engine;
  625. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  626. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  627. }
  628. else {
  629. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  630. }
  631. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  632. if (engine.supportsUniformBuffers) {
  633. for (var name in this._uniformBuffersNames) {
  634. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  635. }
  636. }
  637. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  638. this._attributes = engine.getAttributes(this._program, attributesNames);
  639. var index;
  640. for (index = 0; index < this._samplers.length; index++) {
  641. var sampler = this.getUniform(this._samplers[index]);
  642. if (sampler == null) {
  643. this._samplers.splice(index, 1);
  644. index--;
  645. }
  646. }
  647. engine.bindSamplers(this);
  648. this._compilationError = "";
  649. this._isReady = true;
  650. if (this.onCompiled) {
  651. this.onCompiled(this);
  652. }
  653. this.onCompileObservable.notifyObservers(this);
  654. this.onCompileObservable.clear();
  655. // Unbind mesh reference in fallbacks
  656. if (this._fallbacks) {
  657. this._fallbacks.unBindMesh();
  658. }
  659. if (previousProgram) {
  660. this.getEngine()._deleteProgram(previousProgram);
  661. }
  662. }
  663. catch (e) {
  664. this._compilationError = e.message;
  665. // Let's go through fallbacks then
  666. BABYLON.Tools.Error("Unable to compile effect:");
  667. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  668. return " " + uniform;
  669. }));
  670. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  671. return " " + attribute;
  672. }));
  673. BABYLON.Tools.Error("Error: " + this._compilationError);
  674. if (previousProgram) {
  675. this._program = previousProgram;
  676. this._isReady = true;
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. }
  682. if (fallbacks && fallbacks.isMoreFallbacks) {
  683. BABYLON.Tools.Error("Trying next fallback.");
  684. this.defines = fallbacks.reduce(this.defines, this);
  685. this._prepareEffect();
  686. }
  687. else { // Sorry we did everything we can
  688. if (this.onError) {
  689. this.onError(this, this._compilationError);
  690. }
  691. this.onErrorObservable.notifyObservers(this);
  692. this.onErrorObservable.clear();
  693. // Unbind mesh reference in fallbacks
  694. if (this._fallbacks) {
  695. this._fallbacks.unBindMesh();
  696. }
  697. }
  698. }
  699. };
  700. Object.defineProperty(Effect.prototype, "isSupported", {
  701. /**
  702. * Checks if the effect is supported. (Must be called after compilation)
  703. */
  704. get: function () {
  705. return this._compilationError === "";
  706. },
  707. enumerable: true,
  708. configurable: true
  709. });
  710. /**
  711. * Binds a texture to the engine to be used as output of the shader.
  712. * @param channel Name of the output variable.
  713. * @param texture Texture to bind.
  714. * @hidden
  715. */
  716. Effect.prototype._bindTexture = function (channel, texture) {
  717. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  718. };
  719. /**
  720. * Sets a texture on the engine to be used in the shader.
  721. * @param channel Name of the sampler variable.
  722. * @param texture Texture to set.
  723. */
  724. Effect.prototype.setTexture = function (channel, texture) {
  725. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  726. };
  727. /**
  728. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  729. * @param channel Name of the sampler variable.
  730. * @param texture Texture to set.
  731. */
  732. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  733. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  734. };
  735. /**
  736. * Sets an array of textures on the engine to be used in the shader.
  737. * @param channel Name of the variable.
  738. * @param textures Textures to set.
  739. */
  740. Effect.prototype.setTextureArray = function (channel, textures) {
  741. if (this._samplers.indexOf(channel + "Ex") === -1) {
  742. var initialPos = this._samplers.indexOf(channel);
  743. for (var index = 1; index < textures.length; index++) {
  744. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  745. }
  746. }
  747. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  748. };
  749. /**
  750. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  751. * @param channel Name of the sampler variable.
  752. * @param postProcess Post process to get the input texture from.
  753. */
  754. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  755. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  756. };
  757. /**
  758. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  759. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  760. * @param channel Name of the sampler variable.
  761. * @param postProcess Post process to get the output texture from.
  762. */
  763. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  764. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  765. };
  766. /** @hidden */
  767. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  768. var cache = this._valueCache[uniformName];
  769. var flag = matrix.updateFlag;
  770. if (cache !== undefined && cache === flag) {
  771. return false;
  772. }
  773. this._valueCache[uniformName] = flag;
  774. return true;
  775. };
  776. /** @hidden */
  777. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  778. var cache = this._valueCache[uniformName];
  779. if (!cache) {
  780. cache = [x, y];
  781. this._valueCache[uniformName] = cache;
  782. return true;
  783. }
  784. var changed = false;
  785. if (cache[0] !== x) {
  786. cache[0] = x;
  787. changed = true;
  788. }
  789. if (cache[1] !== y) {
  790. cache[1] = y;
  791. changed = true;
  792. }
  793. return changed;
  794. };
  795. /** @hidden */
  796. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  797. var cache = this._valueCache[uniformName];
  798. if (!cache) {
  799. cache = [x, y, z];
  800. this._valueCache[uniformName] = cache;
  801. return true;
  802. }
  803. var changed = false;
  804. if (cache[0] !== x) {
  805. cache[0] = x;
  806. changed = true;
  807. }
  808. if (cache[1] !== y) {
  809. cache[1] = y;
  810. changed = true;
  811. }
  812. if (cache[2] !== z) {
  813. cache[2] = z;
  814. changed = true;
  815. }
  816. return changed;
  817. };
  818. /** @hidden */
  819. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  820. var cache = this._valueCache[uniformName];
  821. if (!cache) {
  822. cache = [x, y, z, w];
  823. this._valueCache[uniformName] = cache;
  824. return true;
  825. }
  826. var changed = false;
  827. if (cache[0] !== x) {
  828. cache[0] = x;
  829. changed = true;
  830. }
  831. if (cache[1] !== y) {
  832. cache[1] = y;
  833. changed = true;
  834. }
  835. if (cache[2] !== z) {
  836. cache[2] = z;
  837. changed = true;
  838. }
  839. if (cache[3] !== w) {
  840. cache[3] = w;
  841. changed = true;
  842. }
  843. return changed;
  844. };
  845. /**
  846. * Binds a buffer to a uniform.
  847. * @param buffer Buffer to bind.
  848. * @param name Name of the uniform variable to bind to.
  849. */
  850. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  851. var bufferName = this._uniformBuffersNames[name];
  852. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  853. return;
  854. }
  855. Effect._baseCache[bufferName] = buffer;
  856. this._engine.bindUniformBufferBase(buffer, bufferName);
  857. };
  858. /**
  859. * Binds block to a uniform.
  860. * @param blockName Name of the block to bind.
  861. * @param index Index to bind.
  862. */
  863. Effect.prototype.bindUniformBlock = function (blockName, index) {
  864. this._engine.bindUniformBlock(this._program, blockName, index);
  865. };
  866. /**
  867. * Sets an interger value on a uniform variable.
  868. * @param uniformName Name of the variable.
  869. * @param value Value to be set.
  870. * @returns this effect.
  871. */
  872. Effect.prototype.setInt = function (uniformName, value) {
  873. var cache = this._valueCache[uniformName];
  874. if (cache !== undefined && cache === value)
  875. return this;
  876. this._valueCache[uniformName] = value;
  877. this._engine.setInt(this.getUniform(uniformName), value);
  878. return this;
  879. };
  880. /**
  881. * Sets an int array on a uniform variable.
  882. * @param uniformName Name of the variable.
  883. * @param array array to be set.
  884. * @returns this effect.
  885. */
  886. Effect.prototype.setIntArray = function (uniformName, array) {
  887. this._valueCache[uniformName] = null;
  888. this._engine.setIntArray(this.getUniform(uniformName), array);
  889. return this;
  890. };
  891. /**
  892. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  893. * @param uniformName Name of the variable.
  894. * @param array array to be set.
  895. * @returns this effect.
  896. */
  897. Effect.prototype.setIntArray2 = function (uniformName, array) {
  898. this._valueCache[uniformName] = null;
  899. this._engine.setIntArray2(this.getUniform(uniformName), array);
  900. return this;
  901. };
  902. /**
  903. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  904. * @param uniformName Name of the variable.
  905. * @param array array to be set.
  906. * @returns this effect.
  907. */
  908. Effect.prototype.setIntArray3 = function (uniformName, array) {
  909. this._valueCache[uniformName] = null;
  910. this._engine.setIntArray3(this.getUniform(uniformName), array);
  911. return this;
  912. };
  913. /**
  914. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  915. * @param uniformName Name of the variable.
  916. * @param array array to be set.
  917. * @returns this effect.
  918. */
  919. Effect.prototype.setIntArray4 = function (uniformName, array) {
  920. this._valueCache[uniformName] = null;
  921. this._engine.setIntArray4(this.getUniform(uniformName), array);
  922. return this;
  923. };
  924. /**
  925. * Sets an float array on a uniform variable.
  926. * @param uniformName Name of the variable.
  927. * @param array array to be set.
  928. * @returns this effect.
  929. */
  930. Effect.prototype.setFloatArray = function (uniformName, array) {
  931. this._valueCache[uniformName] = null;
  932. this._engine.setFloatArray(this.getUniform(uniformName), array);
  933. return this;
  934. };
  935. /**
  936. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  937. * @param uniformName Name of the variable.
  938. * @param array array to be set.
  939. * @returns this effect.
  940. */
  941. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  942. this._valueCache[uniformName] = null;
  943. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  944. return this;
  945. };
  946. /**
  947. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  948. * @param uniformName Name of the variable.
  949. * @param array array to be set.
  950. * @returns this effect.
  951. */
  952. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  953. this._valueCache[uniformName] = null;
  954. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  955. return this;
  956. };
  957. /**
  958. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  959. * @param uniformName Name of the variable.
  960. * @param array array to be set.
  961. * @returns this effect.
  962. */
  963. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  964. this._valueCache[uniformName] = null;
  965. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  966. return this;
  967. };
  968. /**
  969. * Sets an array on a uniform variable.
  970. * @param uniformName Name of the variable.
  971. * @param array array to be set.
  972. * @returns this effect.
  973. */
  974. Effect.prototype.setArray = function (uniformName, array) {
  975. this._valueCache[uniformName] = null;
  976. this._engine.setArray(this.getUniform(uniformName), array);
  977. return this;
  978. };
  979. /**
  980. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  981. * @param uniformName Name of the variable.
  982. * @param array array to be set.
  983. * @returns this effect.
  984. */
  985. Effect.prototype.setArray2 = function (uniformName, array) {
  986. this._valueCache[uniformName] = null;
  987. this._engine.setArray2(this.getUniform(uniformName), array);
  988. return this;
  989. };
  990. /**
  991. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  992. * @param uniformName Name of the variable.
  993. * @param array array to be set.
  994. * @returns this effect.
  995. */
  996. Effect.prototype.setArray3 = function (uniformName, array) {
  997. this._valueCache[uniformName] = null;
  998. this._engine.setArray3(this.getUniform(uniformName), array);
  999. return this;
  1000. };
  1001. /**
  1002. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1003. * @param uniformName Name of the variable.
  1004. * @param array array to be set.
  1005. * @returns this effect.
  1006. */
  1007. Effect.prototype.setArray4 = function (uniformName, array) {
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setArray4(this.getUniform(uniformName), array);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets matrices on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param matrices matrices to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1019. if (!matrices) {
  1020. return this;
  1021. }
  1022. this._valueCache[uniformName] = null;
  1023. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets matrix on a uniform variable.
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1033. if (this._cacheMatrix(uniformName, matrix)) {
  1034. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1035. }
  1036. return this;
  1037. };
  1038. /**
  1039. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1040. * @param uniformName Name of the variable.
  1041. * @param matrix matrix to be set.
  1042. * @returns this effect.
  1043. */
  1044. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1045. this._valueCache[uniformName] = null;
  1046. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1047. return this;
  1048. };
  1049. /**
  1050. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1051. * @param uniformName Name of the variable.
  1052. * @param matrix matrix to be set.
  1053. * @returns this effect.
  1054. */
  1055. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1056. this._valueCache[uniformName] = null;
  1057. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1058. return this;
  1059. };
  1060. /**
  1061. * Sets a float on a uniform variable.
  1062. * @param uniformName Name of the variable.
  1063. * @param value value to be set.
  1064. * @returns this effect.
  1065. */
  1066. Effect.prototype.setFloat = function (uniformName, value) {
  1067. var cache = this._valueCache[uniformName];
  1068. if (cache !== undefined && cache === value)
  1069. return this;
  1070. this._valueCache[uniformName] = value;
  1071. this._engine.setFloat(this.getUniform(uniformName), value);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a boolean on a uniform variable.
  1076. * @param uniformName Name of the variable.
  1077. * @param bool value to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setBool = function (uniformName, bool) {
  1081. var cache = this._valueCache[uniformName];
  1082. if (cache !== undefined && cache === bool)
  1083. return this;
  1084. this._valueCache[uniformName] = bool;
  1085. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a Vector2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param vector2 vector2 to be set.
  1092. * @returns this effect.
  1093. */
  1094. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1095. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1096. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1097. }
  1098. return this;
  1099. };
  1100. /**
  1101. * Sets a float2 on a uniform variable.
  1102. * @param uniformName Name of the variable.
  1103. * @param x First float in float2.
  1104. * @param y Second float in float2.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1108. if (this._cacheFloat2(uniformName, x, y)) {
  1109. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a Vector3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param vector3 Value to be set.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1120. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1121. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a float3 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param x First float in float3.
  1129. * @param y Second float in float3.
  1130. * @param z Third float in float3.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1134. if (this._cacheFloat3(uniformName, x, y, z)) {
  1135. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a Vector4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param vector4 Value to be set.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1146. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1147. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a float4 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param x First float in float4.
  1155. * @param y Second float in float4.
  1156. * @param z Third float in float4.
  1157. * @param w Fourth float in float4.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1161. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color3 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setColor3 = function (uniformName, color3) {
  1173. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1174. this._engine.setColor3(this.getUniform(uniformName), color3);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a Color4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param color3 Value to be set.
  1182. * @param alpha Alpha value to be set.
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1186. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1187. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Sets a Color4 on a uniform variable
  1193. * @param uniformName defines the name of the variable
  1194. * @param color4 defines the value to be set
  1195. * @returns this effect.
  1196. */
  1197. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1198. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1199. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1200. }
  1201. return this;
  1202. };
  1203. /**
  1204. * This function will add a new shader to the shader store
  1205. * @param name the name of the shader
  1206. * @param pixelShader optional pixel shader content
  1207. * @param vertexShader optional vertex shader content
  1208. */
  1209. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1210. if (pixelShader) {
  1211. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1212. }
  1213. if (vertexShader) {
  1214. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1215. }
  1216. };
  1217. /**
  1218. * Resets the cache of effects.
  1219. */
  1220. Effect.ResetCache = function () {
  1221. Effect._baseCache = {};
  1222. };
  1223. Effect._uniqueIdSeed = 0;
  1224. Effect._baseCache = {};
  1225. /**
  1226. * Store of each shader (The can be looked up using effect.key)
  1227. */
  1228. Effect.ShadersStore = {};
  1229. /**
  1230. * Store of each included file for a shader (The can be looked up using effect.key)
  1231. */
  1232. Effect.IncludesShadersStore = {};
  1233. return Effect;
  1234. }());
  1235. BABYLON.Effect = Effect;
  1236. })(BABYLON || (BABYLON = {}));
  1237. //# sourceMappingURL=babylon.effect.js.map
  1238. //# sourceMappingURL=babylon.types.js.map
  1239. var BABYLON;
  1240. (function (BABYLON) {
  1241. /**
  1242. * Gather the list of keyboard event types as constants.
  1243. */
  1244. var KeyboardEventTypes = /** @class */ (function () {
  1245. function KeyboardEventTypes() {
  1246. }
  1247. /**
  1248. * The keydown event is fired when a key becomes active (pressed).
  1249. */
  1250. KeyboardEventTypes.KEYDOWN = 0x01;
  1251. /**
  1252. * The keyup event is fired when a key has been released.
  1253. */
  1254. KeyboardEventTypes.KEYUP = 0x02;
  1255. return KeyboardEventTypes;
  1256. }());
  1257. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1258. /**
  1259. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1260. */
  1261. var KeyboardInfo = /** @class */ (function () {
  1262. /**
  1263. * Instantiates a new keyboard info.
  1264. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1265. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1266. * @param event Defines the related dom event
  1267. */
  1268. function KeyboardInfo(
  1269. /**
  1270. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1271. */
  1272. type,
  1273. /**
  1274. * Defines the related dom event
  1275. */
  1276. event) {
  1277. this.type = type;
  1278. this.event = event;
  1279. }
  1280. return KeyboardInfo;
  1281. }());
  1282. BABYLON.KeyboardInfo = KeyboardInfo;
  1283. /**
  1284. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1285. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1286. */
  1287. var KeyboardInfoPre = /** @class */ (function (_super) {
  1288. __extends(KeyboardInfoPre, _super);
  1289. /**
  1290. * Instantiates a new keyboard pre info.
  1291. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1292. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1293. * @param event Defines the related dom event
  1294. */
  1295. function KeyboardInfoPre(
  1296. /**
  1297. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1298. */
  1299. type,
  1300. /**
  1301. * Defines the related dom event
  1302. */
  1303. event) {
  1304. var _this = _super.call(this, type, event) || this;
  1305. _this.type = type;
  1306. _this.event = event;
  1307. _this.skipOnPointerObservable = false;
  1308. return _this;
  1309. }
  1310. return KeyboardInfoPre;
  1311. }(KeyboardInfo));
  1312. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1313. })(BABYLON || (BABYLON = {}));
  1314. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1315. var BABYLON;
  1316. (function (BABYLON) {
  1317. /**
  1318. * Gather the list of pointer event types as constants.
  1319. */
  1320. var PointerEventTypes = /** @class */ (function () {
  1321. function PointerEventTypes() {
  1322. }
  1323. /**
  1324. * The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.
  1325. */
  1326. PointerEventTypes.POINTERDOWN = 0x01;
  1327. /**
  1328. * The pointerup event is fired when a pointer is no longer active.
  1329. */
  1330. PointerEventTypes.POINTERUP = 0x02;
  1331. /**
  1332. * The pointermove event is fired when a pointer changes coordinates.
  1333. */
  1334. PointerEventTypes.POINTERMOVE = 0x04;
  1335. /**
  1336. * The pointerwheel event is fired when a mouse wheel has been rotated.
  1337. */
  1338. PointerEventTypes.POINTERWHEEL = 0x08;
  1339. /**
  1340. * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
  1341. */
  1342. PointerEventTypes.POINTERPICK = 0x10;
  1343. /**
  1344. * The pointertap event is fired when a the object has been touched and released without drag.
  1345. */
  1346. PointerEventTypes.POINTERTAP = 0x20;
  1347. /**
  1348. * The pointertap event is fired when a the object has been touched and released twice without drag.
  1349. */
  1350. PointerEventTypes.POINTERDOUBLETAP = 0x40;
  1351. return PointerEventTypes;
  1352. }());
  1353. BABYLON.PointerEventTypes = PointerEventTypes;
  1354. /**
  1355. * Base class of pointer info types.
  1356. */
  1357. var PointerInfoBase = /** @class */ (function () {
  1358. /**
  1359. * Instantiates the base class of pointers info.
  1360. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1361. * @param event Defines the related dom event
  1362. */
  1363. function PointerInfoBase(
  1364. /**
  1365. * Defines the type of event (BABYLON.PointerEventTypes)
  1366. */
  1367. type,
  1368. /**
  1369. * Defines the related dom event
  1370. */
  1371. event) {
  1372. this.type = type;
  1373. this.event = event;
  1374. }
  1375. return PointerInfoBase;
  1376. }());
  1377. BABYLON.PointerInfoBase = PointerInfoBase;
  1378. /**
  1379. * This class is used to store pointer related info for the onPrePointerObservable event.
  1380. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1381. */
  1382. var PointerInfoPre = /** @class */ (function (_super) {
  1383. __extends(PointerInfoPre, _super);
  1384. /**
  1385. * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
  1386. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1387. * @param event Defines the related dom event
  1388. * @param localX Defines the local x coordinates of the pointer when the event occured
  1389. * @param localY Defines the local y coordinates of the pointer when the event occured
  1390. */
  1391. function PointerInfoPre(type, event, localX, localY) {
  1392. var _this = _super.call(this, type, event) || this;
  1393. /**
  1394. * Ray from a pointer if availible (eg. 6dof controller)
  1395. */
  1396. _this.ray = null;
  1397. _this.skipOnPointerObservable = false;
  1398. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1399. return _this;
  1400. }
  1401. return PointerInfoPre;
  1402. }(PointerInfoBase));
  1403. BABYLON.PointerInfoPre = PointerInfoPre;
  1404. /**
  1405. * This type contains all the data related to a pointer event in Babylon.js.
  1406. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1407. */
  1408. var PointerInfo = /** @class */ (function (_super) {
  1409. __extends(PointerInfo, _super);
  1410. /**
  1411. * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
  1412. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1413. * @param event Defines the related dom event
  1414. * @param pickInfo Defines the picking info associated to the info (if any)\
  1415. */
  1416. function PointerInfo(type, event,
  1417. /**
  1418. * Defines the picking info associated to the info (if any)\
  1419. */
  1420. pickInfo) {
  1421. var _this = _super.call(this, type, event) || this;
  1422. _this.pickInfo = pickInfo;
  1423. return _this;
  1424. }
  1425. return PointerInfo;
  1426. }(PointerInfoBase));
  1427. BABYLON.PointerInfo = PointerInfo;
  1428. })(BABYLON || (BABYLON = {}));
  1429. //# sourceMappingURL=babylon.pointerEvents.js.map
  1430. var BABYLON;
  1431. (function (BABYLON) {
  1432. /**
  1433. * Constant used to convert a value to gamma space
  1434. * @ignorenaming
  1435. */
  1436. BABYLON.ToGammaSpace = 1 / 2.2;
  1437. /**
  1438. * Constant used to convert a value to linear space
  1439. * @ignorenaming
  1440. */
  1441. BABYLON.ToLinearSpace = 2.2;
  1442. /**
  1443. * Constant used to define the minimal number value in Babylon.js
  1444. * @ignorenaming
  1445. */
  1446. BABYLON.Epsilon = 0.001;
  1447. /**
  1448. * Class used to hold a RBG color
  1449. */
  1450. var Color3 = /** @class */ (function () {
  1451. /**
  1452. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1453. * @param r defines the red component (between 0 and 1, default is 0)
  1454. * @param g defines the green component (between 0 and 1, default is 0)
  1455. * @param b defines the blue component (between 0 and 1, default is 0)
  1456. */
  1457. function Color3(
  1458. /**
  1459. * Defines the red component (between 0 and 1, default is 0)
  1460. */
  1461. r,
  1462. /**
  1463. * Defines the green component (between 0 and 1, default is 0)
  1464. */
  1465. g,
  1466. /**
  1467. * Defines the blue component (between 0 and 1, default is 0)
  1468. */
  1469. b) {
  1470. if (r === void 0) { r = 0; }
  1471. if (g === void 0) { g = 0; }
  1472. if (b === void 0) { b = 0; }
  1473. this.r = r;
  1474. this.g = g;
  1475. this.b = b;
  1476. }
  1477. /**
  1478. * Creates a string with the Color3 current values
  1479. * @returns the string representation of the Color3 object
  1480. */
  1481. Color3.prototype.toString = function () {
  1482. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1483. };
  1484. /**
  1485. * Returns the string "Color3"
  1486. * @returns "Color3"
  1487. */
  1488. Color3.prototype.getClassName = function () {
  1489. return "Color3";
  1490. };
  1491. /**
  1492. * Compute the Color3 hash code
  1493. * @returns an unique number that can be used to hash Color3 objects
  1494. */
  1495. Color3.prototype.getHashCode = function () {
  1496. var hash = this.r || 0;
  1497. hash = (hash * 397) ^ (this.g || 0);
  1498. hash = (hash * 397) ^ (this.b || 0);
  1499. return hash;
  1500. };
  1501. // Operators
  1502. /**
  1503. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1504. * @param array defines the array where to store the r,g,b components
  1505. * @param index defines an optional index in the target array to define where to start storing values
  1506. * @returns the current Color3 object
  1507. */
  1508. Color3.prototype.toArray = function (array, index) {
  1509. if (index === undefined) {
  1510. index = 0;
  1511. }
  1512. array[index] = this.r;
  1513. array[index + 1] = this.g;
  1514. array[index + 2] = this.b;
  1515. return this;
  1516. };
  1517. /**
  1518. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1519. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1520. * @returns a new {BABYLON.Color4} object
  1521. */
  1522. Color3.prototype.toColor4 = function (alpha) {
  1523. if (alpha === void 0) { alpha = 1; }
  1524. return new Color4(this.r, this.g, this.b, alpha);
  1525. };
  1526. /**
  1527. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1528. * @returns the new array
  1529. */
  1530. Color3.prototype.asArray = function () {
  1531. var result = new Array();
  1532. this.toArray(result, 0);
  1533. return result;
  1534. };
  1535. /**
  1536. * Returns the luminance value
  1537. * @returns a float value
  1538. */
  1539. Color3.prototype.toLuminance = function () {
  1540. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1541. };
  1542. /**
  1543. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1544. * @param otherColor defines the second operand
  1545. * @returns the new Color3 object
  1546. */
  1547. Color3.prototype.multiply = function (otherColor) {
  1548. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1549. };
  1550. /**
  1551. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1552. * @param otherColor defines the second operand
  1553. * @param result defines the Color3 object where to store the result
  1554. * @returns the current Color3
  1555. */
  1556. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1557. result.r = this.r * otherColor.r;
  1558. result.g = this.g * otherColor.g;
  1559. result.b = this.b * otherColor.b;
  1560. return this;
  1561. };
  1562. /**
  1563. * Determines equality between Color3 objects
  1564. * @param otherColor defines the second operand
  1565. * @returns true if the rgb values are equal to the given ones
  1566. */
  1567. Color3.prototype.equals = function (otherColor) {
  1568. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1569. };
  1570. /**
  1571. * Determines equality between the current Color3 object and a set of r,b,g values
  1572. * @param r defines the red component to check
  1573. * @param g defines the green component to check
  1574. * @param b defines the blue component to check
  1575. * @returns true if the rgb values are equal to the given ones
  1576. */
  1577. Color3.prototype.equalsFloats = function (r, g, b) {
  1578. return this.r === r && this.g === g && this.b === b;
  1579. };
  1580. /**
  1581. * Multiplies in place each rgb value by scale
  1582. * @param scale defines the scaling factor
  1583. * @returns the updated Color3
  1584. */
  1585. Color3.prototype.scale = function (scale) {
  1586. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1587. };
  1588. /**
  1589. * Multiplies the rgb values by scale and stores the result into "result"
  1590. * @param scale defines the scaling factor
  1591. * @param result defines the Color3 object where to store the result
  1592. * @returns the unmodified current Color3
  1593. */
  1594. Color3.prototype.scaleToRef = function (scale, result) {
  1595. result.r = this.r * scale;
  1596. result.g = this.g * scale;
  1597. result.b = this.b * scale;
  1598. return this;
  1599. };
  1600. /**
  1601. * Scale the current Color3 values by a factor and add the result to a given Color3
  1602. * @param scale defines the scale factor
  1603. * @param result defines color to store the result into
  1604. * @returns the unmodified current Color3
  1605. */
  1606. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1607. result.r += this.r * scale;
  1608. result.g += this.g * scale;
  1609. result.b += this.b * scale;
  1610. return this;
  1611. };
  1612. /**
  1613. * Clamps the rgb values by the min and max values and stores the result into "result"
  1614. * @param min defines minimum clamping value (default is 0)
  1615. * @param max defines maximum clamping value (default is 1)
  1616. * @param result defines color to store the result into
  1617. * @returns the original Color3
  1618. */
  1619. Color3.prototype.clampToRef = function (min, max, result) {
  1620. if (min === void 0) { min = 0; }
  1621. if (max === void 0) { max = 1; }
  1622. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1623. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1624. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1625. return this;
  1626. };
  1627. /**
  1628. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1629. * @param otherColor defines the second operand
  1630. * @returns the new Color3
  1631. */
  1632. Color3.prototype.add = function (otherColor) {
  1633. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1634. };
  1635. /**
  1636. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1637. * @param otherColor defines the second operand
  1638. * @param result defines Color3 object to store the result into
  1639. * @returns the unmodified current Color3
  1640. */
  1641. Color3.prototype.addToRef = function (otherColor, result) {
  1642. result.r = this.r + otherColor.r;
  1643. result.g = this.g + otherColor.g;
  1644. result.b = this.b + otherColor.b;
  1645. return this;
  1646. };
  1647. /**
  1648. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1649. * @param otherColor defines the second operand
  1650. * @returns the new Color3
  1651. */
  1652. Color3.prototype.subtract = function (otherColor) {
  1653. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1654. };
  1655. /**
  1656. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1657. * @param otherColor defines the second operand
  1658. * @param result defines Color3 object to store the result into
  1659. * @returns the unmodified current Color3
  1660. */
  1661. Color3.prototype.subtractToRef = function (otherColor, result) {
  1662. result.r = this.r - otherColor.r;
  1663. result.g = this.g - otherColor.g;
  1664. result.b = this.b - otherColor.b;
  1665. return this;
  1666. };
  1667. /**
  1668. * Copy the current object
  1669. * @returns a new Color3 copied the current one
  1670. */
  1671. Color3.prototype.clone = function () {
  1672. return new Color3(this.r, this.g, this.b);
  1673. };
  1674. /**
  1675. * Copies the rgb values from the source in the current Color3
  1676. * @param source defines the source Color3 object
  1677. * @returns the updated Color3 object
  1678. */
  1679. Color3.prototype.copyFrom = function (source) {
  1680. this.r = source.r;
  1681. this.g = source.g;
  1682. this.b = source.b;
  1683. return this;
  1684. };
  1685. /**
  1686. * Updates the Color3 rgb values from the given floats
  1687. * @param r defines the red component to read from
  1688. * @param g defines the green component to read from
  1689. * @param b defines the blue component to read from
  1690. * @returns the current Color3 object
  1691. */
  1692. Color3.prototype.copyFromFloats = function (r, g, b) {
  1693. this.r = r;
  1694. this.g = g;
  1695. this.b = b;
  1696. return this;
  1697. };
  1698. /**
  1699. * Updates the Color3 rgb values from the given floats
  1700. * @param r defines the red component to read from
  1701. * @param g defines the green component to read from
  1702. * @param b defines the blue component to read from
  1703. * @returns the current Color3 object
  1704. */
  1705. Color3.prototype.set = function (r, g, b) {
  1706. return this.copyFromFloats(r, g, b);
  1707. };
  1708. /**
  1709. * Compute the Color3 hexadecimal code as a string
  1710. * @returns a string containing the hexadecimal representation of the Color3 object
  1711. */
  1712. Color3.prototype.toHexString = function () {
  1713. var intR = (this.r * 255) | 0;
  1714. var intG = (this.g * 255) | 0;
  1715. var intB = (this.b * 255) | 0;
  1716. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1717. };
  1718. /**
  1719. * Computes a new Color3 converted from the current one to linear space
  1720. * @returns a new Color3 object
  1721. */
  1722. Color3.prototype.toLinearSpace = function () {
  1723. var convertedColor = new Color3();
  1724. this.toLinearSpaceToRef(convertedColor);
  1725. return convertedColor;
  1726. };
  1727. /**
  1728. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1729. * @param convertedColor defines the Color3 object where to store the linear space version
  1730. * @returns the unmodified Color3
  1731. */
  1732. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1733. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1734. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1735. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1736. return this;
  1737. };
  1738. /**
  1739. * Computes a new Color3 converted from the current one to gamma space
  1740. * @returns a new Color3 object
  1741. */
  1742. Color3.prototype.toGammaSpace = function () {
  1743. var convertedColor = new Color3();
  1744. this.toGammaSpaceToRef(convertedColor);
  1745. return convertedColor;
  1746. };
  1747. /**
  1748. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1749. * @param convertedColor defines the Color3 object where to store the gamma space version
  1750. * @returns the unmodified Color3
  1751. */
  1752. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1753. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1754. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1755. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1756. return this;
  1757. };
  1758. // Statics
  1759. /**
  1760. * Creates a new Color3 from the string containing valid hexadecimal values
  1761. * @param hex defines a string containing valid hexadecimal values
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.FromHexString = function (hex) {
  1765. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1766. return new Color3(0, 0, 0);
  1767. }
  1768. var r = parseInt(hex.substring(1, 3), 16);
  1769. var g = parseInt(hex.substring(3, 5), 16);
  1770. var b = parseInt(hex.substring(5, 7), 16);
  1771. return Color3.FromInts(r, g, b);
  1772. };
  1773. /**
  1774. * Creates a new Vector3 from the starting index of the given array
  1775. * @param array defines the source array
  1776. * @param offset defines an offset in the source array
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.FromArray = function (array, offset) {
  1780. if (offset === void 0) { offset = 0; }
  1781. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1782. };
  1783. /**
  1784. * Creates a new Color3 from integer values (< 256)
  1785. * @param r defines the red component to read from (value between 0 and 255)
  1786. * @param g defines the green component to read from (value between 0 and 255)
  1787. * @param b defines the blue component to read from (value between 0 and 255)
  1788. * @returns a new Color3 object
  1789. */
  1790. Color3.FromInts = function (r, g, b) {
  1791. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1792. };
  1793. /**
  1794. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1795. * @param start defines the start Color3 value
  1796. * @param end defines the end Color3 value
  1797. * @param amount defines the gradient value between start and end
  1798. * @returns a new Color3 object
  1799. */
  1800. Color3.Lerp = function (start, end, amount) {
  1801. var result = new Color3(0.0, 0.0, 0.0);
  1802. Color3.LerpToRef(start, end, amount, result);
  1803. return result;
  1804. };
  1805. /**
  1806. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1807. * @param left defines the start value
  1808. * @param right defines the end value
  1809. * @param amount defines the gradient factor
  1810. * @param result defines the Color3 object where to store the result
  1811. */
  1812. Color3.LerpToRef = function (left, right, amount, result) {
  1813. result.r = left.r + ((right.r - left.r) * amount);
  1814. result.g = left.g + ((right.g - left.g) * amount);
  1815. result.b = left.b + ((right.b - left.b) * amount);
  1816. };
  1817. /**
  1818. * Returns a Color3 value containing a red color
  1819. * @returns a new Color3 object
  1820. */
  1821. Color3.Red = function () { return new Color3(1, 0, 0); };
  1822. /**
  1823. * Returns a Color3 value containing a green color
  1824. * @returns a new Color3 object
  1825. */
  1826. Color3.Green = function () { return new Color3(0, 1, 0); };
  1827. /**
  1828. * Returns a Color3 value containing a blue color
  1829. * @returns a new Color3 object
  1830. */
  1831. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1832. /**
  1833. * Returns a Color3 value containing a black color
  1834. * @returns a new Color3 object
  1835. */
  1836. Color3.Black = function () { return new Color3(0, 0, 0); };
  1837. /**
  1838. * Returns a Color3 value containing a white color
  1839. * @returns a new Color3 object
  1840. */
  1841. Color3.White = function () { return new Color3(1, 1, 1); };
  1842. /**
  1843. * Returns a Color3 value containing a purple color
  1844. * @returns a new Color3 object
  1845. */
  1846. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1847. /**
  1848. * Returns a Color3 value containing a magenta color
  1849. * @returns a new Color3 object
  1850. */
  1851. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1852. /**
  1853. * Returns a Color3 value containing a yellow color
  1854. * @returns a new Color3 object
  1855. */
  1856. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1857. /**
  1858. * Returns a Color3 value containing a gray color
  1859. * @returns a new Color3 object
  1860. */
  1861. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1862. /**
  1863. * Returns a Color3 value containing a teal color
  1864. * @returns a new Color3 object
  1865. */
  1866. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1867. /**
  1868. * Returns a Color3 value containing a random color
  1869. * @returns a new Color3 object
  1870. */
  1871. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1872. return Color3;
  1873. }());
  1874. BABYLON.Color3 = Color3;
  1875. /**
  1876. * Class used to hold a RBGA color
  1877. */
  1878. var Color4 = /** @class */ (function () {
  1879. /**
  1880. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1881. * @param r defines the red component (between 0 and 1, default is 0)
  1882. * @param g defines the green component (between 0 and 1, default is 0)
  1883. * @param b defines the blue component (between 0 and 1, default is 0)
  1884. * @param a defines the alpha component (between 0 and 1, default is 1)
  1885. */
  1886. function Color4(
  1887. /**
  1888. * Defines the red component (between 0 and 1, default is 0)
  1889. */
  1890. r,
  1891. /**
  1892. * Defines the green component (between 0 and 1, default is 0)
  1893. */
  1894. g,
  1895. /**
  1896. * Defines the blue component (between 0 and 1, default is 0)
  1897. */
  1898. b,
  1899. /**
  1900. * Defines the alpha component (between 0 and 1, default is 1)
  1901. */
  1902. a) {
  1903. if (r === void 0) { r = 0; }
  1904. if (g === void 0) { g = 0; }
  1905. if (b === void 0) { b = 0; }
  1906. if (a === void 0) { a = 1; }
  1907. this.r = r;
  1908. this.g = g;
  1909. this.b = b;
  1910. this.a = a;
  1911. }
  1912. // Operators
  1913. /**
  1914. * Adds in place the given Color4 values to the current Color4 object
  1915. * @param right defines the second operand
  1916. * @returns the current updated Color4 object
  1917. */
  1918. Color4.prototype.addInPlace = function (right) {
  1919. this.r += right.r;
  1920. this.g += right.g;
  1921. this.b += right.b;
  1922. this.a += right.a;
  1923. return this;
  1924. };
  1925. /**
  1926. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1927. * @returns the new array
  1928. */
  1929. Color4.prototype.asArray = function () {
  1930. var result = new Array();
  1931. this.toArray(result, 0);
  1932. return result;
  1933. };
  1934. /**
  1935. * Stores from the starting index in the given array the Color4 successive values
  1936. * @param array defines the array where to store the r,g,b components
  1937. * @param index defines an optional index in the target array to define where to start storing values
  1938. * @returns the current Color4 object
  1939. */
  1940. Color4.prototype.toArray = function (array, index) {
  1941. if (index === undefined) {
  1942. index = 0;
  1943. }
  1944. array[index] = this.r;
  1945. array[index + 1] = this.g;
  1946. array[index + 2] = this.b;
  1947. array[index + 3] = this.a;
  1948. return this;
  1949. };
  1950. /**
  1951. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1952. * @param right defines the second operand
  1953. * @returns a new Color4 object
  1954. */
  1955. Color4.prototype.add = function (right) {
  1956. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1957. };
  1958. /**
  1959. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1960. * @param right defines the second operand
  1961. * @returns a new Color4 object
  1962. */
  1963. Color4.prototype.subtract = function (right) {
  1964. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1965. };
  1966. /**
  1967. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1968. * @param right defines the second operand
  1969. * @param result defines the Color4 object where to store the result
  1970. * @returns the current Color4 object
  1971. */
  1972. Color4.prototype.subtractToRef = function (right, result) {
  1973. result.r = this.r - right.r;
  1974. result.g = this.g - right.g;
  1975. result.b = this.b - right.b;
  1976. result.a = this.a - right.a;
  1977. return this;
  1978. };
  1979. /**
  1980. * Creates a new Color4 with the current Color4 values multiplied by scale
  1981. * @param scale defines the scaling factor to apply
  1982. * @returns a new Color4 object
  1983. */
  1984. Color4.prototype.scale = function (scale) {
  1985. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1986. };
  1987. /**
  1988. * Multiplies the current Color4 values by scale and stores the result in "result"
  1989. * @param scale defines the scaling factor to apply
  1990. * @param result defines the Color4 object where to store the result
  1991. * @returns the current unmodified Color4
  1992. */
  1993. Color4.prototype.scaleToRef = function (scale, result) {
  1994. result.r = this.r * scale;
  1995. result.g = this.g * scale;
  1996. result.b = this.b * scale;
  1997. result.a = this.a * scale;
  1998. return this;
  1999. };
  2000. /**
  2001. * Scale the current Color4 values by a factor and add the result to a given Color4
  2002. * @param scale defines the scale factor
  2003. * @param result defines the Color4 object where to store the result
  2004. * @returns the unmodified current Color4
  2005. */
  2006. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2007. result.r += this.r * scale;
  2008. result.g += this.g * scale;
  2009. result.b += this.b * scale;
  2010. result.a += this.a * scale;
  2011. return this;
  2012. };
  2013. /**
  2014. * Clamps the rgb values by the min and max values and stores the result into "result"
  2015. * @param min defines minimum clamping value (default is 0)
  2016. * @param max defines maximum clamping value (default is 1)
  2017. * @param result defines color to store the result into.
  2018. * @returns the cuurent Color4
  2019. */
  2020. Color4.prototype.clampToRef = function (min, max, result) {
  2021. if (min === void 0) { min = 0; }
  2022. if (max === void 0) { max = 1; }
  2023. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2024. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2025. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2026. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2027. return this;
  2028. };
  2029. /**
  2030. * Multipy an Color4 value by another and return a new Color4 object
  2031. * @param color defines the Color4 value to multiply by
  2032. * @returns a new Color4 object
  2033. */
  2034. Color4.prototype.multiply = function (color) {
  2035. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2036. };
  2037. /**
  2038. * Multipy a Color4 value by another and push the result in a reference value
  2039. * @param color defines the Color4 value to multiply by
  2040. * @param result defines the Color4 to fill the result in
  2041. * @returns the result Color4
  2042. */
  2043. Color4.prototype.multiplyToRef = function (color, result) {
  2044. result.r = this.r * color.r;
  2045. result.g = this.g * color.g;
  2046. result.b = this.b * color.b;
  2047. result.a = this.a * color.a;
  2048. return result;
  2049. };
  2050. /**
  2051. * Creates a string with the Color4 current values
  2052. * @returns the string representation of the Color4 object
  2053. */
  2054. Color4.prototype.toString = function () {
  2055. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2056. };
  2057. /**
  2058. * Returns the string "Color4"
  2059. * @returns "Color4"
  2060. */
  2061. Color4.prototype.getClassName = function () {
  2062. return "Color4";
  2063. };
  2064. /**
  2065. * Compute the Color4 hash code
  2066. * @returns an unique number that can be used to hash Color4 objects
  2067. */
  2068. Color4.prototype.getHashCode = function () {
  2069. var hash = this.r || 0;
  2070. hash = (hash * 397) ^ (this.g || 0);
  2071. hash = (hash * 397) ^ (this.b || 0);
  2072. hash = (hash * 397) ^ (this.a || 0);
  2073. return hash;
  2074. };
  2075. /**
  2076. * Creates a new Color4 copied from the current one
  2077. * @returns a new Color4 object
  2078. */
  2079. Color4.prototype.clone = function () {
  2080. return new Color4(this.r, this.g, this.b, this.a);
  2081. };
  2082. /**
  2083. * Copies the given Color4 values into the current one
  2084. * @param source defines the source Color4 object
  2085. * @returns the current updated Color4 object
  2086. */
  2087. Color4.prototype.copyFrom = function (source) {
  2088. this.r = source.r;
  2089. this.g = source.g;
  2090. this.b = source.b;
  2091. this.a = source.a;
  2092. return this;
  2093. };
  2094. /**
  2095. * Copies the given float values into the current one
  2096. * @param r defines the red component to read from
  2097. * @param g defines the green component to read from
  2098. * @param b defines the blue component to read from
  2099. * @param a defines the alpha component to read from
  2100. * @returns the current updated Color4 object
  2101. */
  2102. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2103. this.r = r;
  2104. this.g = g;
  2105. this.b = b;
  2106. this.a = a;
  2107. return this;
  2108. };
  2109. /**
  2110. * Copies the given float values into the current one
  2111. * @param r defines the red component to read from
  2112. * @param g defines the green component to read from
  2113. * @param b defines the blue component to read from
  2114. * @param a defines the alpha component to read from
  2115. * @returns the current updated Color4 object
  2116. */
  2117. Color4.prototype.set = function (r, g, b, a) {
  2118. return this.copyFromFloats(r, g, b, a);
  2119. };
  2120. /**
  2121. * Compute the Color4 hexadecimal code as a string
  2122. * @returns a string containing the hexadecimal representation of the Color4 object
  2123. */
  2124. Color4.prototype.toHexString = function () {
  2125. var intR = (this.r * 255) | 0;
  2126. var intG = (this.g * 255) | 0;
  2127. var intB = (this.b * 255) | 0;
  2128. var intA = (this.a * 255) | 0;
  2129. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2130. };
  2131. /**
  2132. * Computes a new Color4 converted from the current one to linear space
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.prototype.toLinearSpace = function () {
  2136. var convertedColor = new Color4();
  2137. this.toLinearSpaceToRef(convertedColor);
  2138. return convertedColor;
  2139. };
  2140. /**
  2141. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2142. * @param convertedColor defines the Color4 object where to store the linear space version
  2143. * @returns the unmodified Color4
  2144. */
  2145. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2146. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2147. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2148. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2149. convertedColor.a = this.a;
  2150. return this;
  2151. };
  2152. /**
  2153. * Computes a new Color4 converted from the current one to gamma space
  2154. * @returns a new Color4 object
  2155. */
  2156. Color4.prototype.toGammaSpace = function () {
  2157. var convertedColor = new Color4();
  2158. this.toGammaSpaceToRef(convertedColor);
  2159. return convertedColor;
  2160. };
  2161. /**
  2162. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2163. * @param convertedColor defines the Color4 object where to store the gamma space version
  2164. * @returns the unmodified Color4
  2165. */
  2166. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2167. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2168. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2169. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2170. convertedColor.a = this.a;
  2171. return this;
  2172. };
  2173. // Statics
  2174. /**
  2175. * Creates a new Color4 from the string containing valid hexadecimal values
  2176. * @param hex defines a string containing valid hexadecimal values
  2177. * @returns a new Color4 object
  2178. */
  2179. Color4.FromHexString = function (hex) {
  2180. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2181. return new Color4(0.0, 0.0, 0.0, 0.0);
  2182. }
  2183. var r = parseInt(hex.substring(1, 3), 16);
  2184. var g = parseInt(hex.substring(3, 5), 16);
  2185. var b = parseInt(hex.substring(5, 7), 16);
  2186. var a = parseInt(hex.substring(7, 9), 16);
  2187. return Color4.FromInts(r, g, b, a);
  2188. };
  2189. /**
  2190. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2191. * @param left defines the start value
  2192. * @param right defines the end value
  2193. * @param amount defines the gradient factor
  2194. * @returns a new Color4 object
  2195. */
  2196. Color4.Lerp = function (left, right, amount) {
  2197. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2198. Color4.LerpToRef(left, right, amount, result);
  2199. return result;
  2200. };
  2201. /**
  2202. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2203. * @param left defines the start value
  2204. * @param right defines the end value
  2205. * @param amount defines the gradient factor
  2206. * @param result defines the Color4 object where to store data
  2207. */
  2208. Color4.LerpToRef = function (left, right, amount, result) {
  2209. result.r = left.r + (right.r - left.r) * amount;
  2210. result.g = left.g + (right.g - left.g) * amount;
  2211. result.b = left.b + (right.b - left.b) * amount;
  2212. result.a = left.a + (right.a - left.a) * amount;
  2213. };
  2214. /**
  2215. * Creates a new Color4 from a Color3 and an alpha value
  2216. * @param color3 defines the source Color3 to read from
  2217. * @param alpha defines the alpha component (1.0 by default)
  2218. * @returns a new Color4 object
  2219. */
  2220. Color4.FromColor3 = function (color3, alpha) {
  2221. if (alpha === void 0) { alpha = 1.0; }
  2222. return new Color4(color3.r, color3.g, color3.b, alpha);
  2223. };
  2224. /**
  2225. * Creates a new Color4 from the starting index element of the given array
  2226. * @param array defines the source array to read from
  2227. * @param offset defines the offset in the source array
  2228. * @returns a new Color4 object
  2229. */
  2230. Color4.FromArray = function (array, offset) {
  2231. if (offset === void 0) { offset = 0; }
  2232. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2233. };
  2234. /**
  2235. * Creates a new Color3 from integer values (< 256)
  2236. * @param r defines the red component to read from (value between 0 and 255)
  2237. * @param g defines the green component to read from (value between 0 and 255)
  2238. * @param b defines the blue component to read from (value between 0 and 255)
  2239. * @param a defines the alpha component to read from (value between 0 and 255)
  2240. * @returns a new Color3 object
  2241. */
  2242. Color4.FromInts = function (r, g, b, a) {
  2243. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2244. };
  2245. /**
  2246. * Check the content of a given array and convert it to an array containing RGBA data
  2247. * If the original array was already containing count * 4 values then it is returned directly
  2248. * @param colors defines the array to check
  2249. * @param count defines the number of RGBA data to expect
  2250. * @returns an array containing count * 4 values (RGBA)
  2251. */
  2252. Color4.CheckColors4 = function (colors, count) {
  2253. // Check if color3 was used
  2254. if (colors.length === count * 3) {
  2255. var colors4 = [];
  2256. for (var index = 0; index < colors.length; index += 3) {
  2257. var newIndex = (index / 3) * 4;
  2258. colors4[newIndex] = colors[index];
  2259. colors4[newIndex + 1] = colors[index + 1];
  2260. colors4[newIndex + 2] = colors[index + 2];
  2261. colors4[newIndex + 3] = 1.0;
  2262. }
  2263. return colors4;
  2264. }
  2265. return colors;
  2266. };
  2267. return Color4;
  2268. }());
  2269. BABYLON.Color4 = Color4;
  2270. /**
  2271. * Class representing a vector containing 2 coordinates
  2272. */
  2273. var Vector2 = /** @class */ (function () {
  2274. /**
  2275. * Creates a new Vector2 from the given x and y coordinates
  2276. * @param x defines the first coordinate
  2277. * @param y defines the second coordinate
  2278. */
  2279. function Vector2(
  2280. /** defines the first coordinate */
  2281. x,
  2282. /** defines the second coordinate */
  2283. y) {
  2284. if (x === void 0) { x = 0; }
  2285. if (y === void 0) { y = 0; }
  2286. this.x = x;
  2287. this.y = y;
  2288. }
  2289. /**
  2290. * Gets a string with the Vector2 coordinates
  2291. * @returns a string with the Vector2 coordinates
  2292. */
  2293. Vector2.prototype.toString = function () {
  2294. return "{X: " + this.x + " Y:" + this.y + "}";
  2295. };
  2296. /**
  2297. * Gets class name
  2298. * @returns the string "Vector2"
  2299. */
  2300. Vector2.prototype.getClassName = function () {
  2301. return "Vector2";
  2302. };
  2303. /**
  2304. * Gets current vector hash code
  2305. * @returns the Vector2 hash code as a number
  2306. */
  2307. Vector2.prototype.getHashCode = function () {
  2308. var hash = this.x || 0;
  2309. hash = (hash * 397) ^ (this.y || 0);
  2310. return hash;
  2311. };
  2312. // Operators
  2313. /**
  2314. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2315. * @param array defines the source array
  2316. * @param index defines the offset in source array
  2317. * @returns the current Vector2
  2318. */
  2319. Vector2.prototype.toArray = function (array, index) {
  2320. if (index === void 0) { index = 0; }
  2321. array[index] = this.x;
  2322. array[index + 1] = this.y;
  2323. return this;
  2324. };
  2325. /**
  2326. * Copy the current vector to an array
  2327. * @returns a new array with 2 elements: the Vector2 coordinates.
  2328. */
  2329. Vector2.prototype.asArray = function () {
  2330. var result = new Array();
  2331. this.toArray(result, 0);
  2332. return result;
  2333. };
  2334. /**
  2335. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2336. * @param source defines the source Vector2
  2337. * @returns the current updated Vector2
  2338. */
  2339. Vector2.prototype.copyFrom = function (source) {
  2340. this.x = source.x;
  2341. this.y = source.y;
  2342. return this;
  2343. };
  2344. /**
  2345. * Sets the Vector2 coordinates with the given floats
  2346. * @param x defines the first coordinate
  2347. * @param y defines the second coordinate
  2348. * @returns the current updated Vector2
  2349. */
  2350. Vector2.prototype.copyFromFloats = function (x, y) {
  2351. this.x = x;
  2352. this.y = y;
  2353. return this;
  2354. };
  2355. /**
  2356. * Sets the Vector2 coordinates with the given floats
  2357. * @param x defines the first coordinate
  2358. * @param y defines the second coordinate
  2359. * @returns the current updated Vector2
  2360. */
  2361. Vector2.prototype.set = function (x, y) {
  2362. return this.copyFromFloats(x, y);
  2363. };
  2364. /**
  2365. * Add another vector with the current one
  2366. * @param otherVector defines the other vector
  2367. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2368. */
  2369. Vector2.prototype.add = function (otherVector) {
  2370. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2371. };
  2372. /**
  2373. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2374. * @param otherVector defines the other vector
  2375. * @param result defines the target vector
  2376. * @returns the unmodified current Vector2
  2377. */
  2378. Vector2.prototype.addToRef = function (otherVector, result) {
  2379. result.x = this.x + otherVector.x;
  2380. result.y = this.y + otherVector.y;
  2381. return this;
  2382. };
  2383. /**
  2384. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2385. * @param otherVector defines the other vector
  2386. * @returns the current updated Vector2
  2387. */
  2388. Vector2.prototype.addInPlace = function (otherVector) {
  2389. this.x += otherVector.x;
  2390. this.y += otherVector.y;
  2391. return this;
  2392. };
  2393. /**
  2394. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2395. * @param otherVector defines the other vector
  2396. * @returns a new Vector2
  2397. */
  2398. Vector2.prototype.addVector3 = function (otherVector) {
  2399. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2400. };
  2401. /**
  2402. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2403. * @param otherVector defines the other vector
  2404. * @returns a new Vector2
  2405. */
  2406. Vector2.prototype.subtract = function (otherVector) {
  2407. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2408. };
  2409. /**
  2410. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2411. * @param otherVector defines the other vector
  2412. * @param result defines the target vector
  2413. * @returns the unmodified current Vector2
  2414. */
  2415. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2416. result.x = this.x - otherVector.x;
  2417. result.y = this.y - otherVector.y;
  2418. return this;
  2419. };
  2420. /**
  2421. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2422. * @param otherVector defines the other vector
  2423. * @returns the current updated Vector2
  2424. */
  2425. Vector2.prototype.subtractInPlace = function (otherVector) {
  2426. this.x -= otherVector.x;
  2427. this.y -= otherVector.y;
  2428. return this;
  2429. };
  2430. /**
  2431. * Multiplies in place the current Vector2 coordinates by the given ones
  2432. * @param otherVector defines the other vector
  2433. * @returns the current updated Vector2
  2434. */
  2435. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2436. this.x *= otherVector.x;
  2437. this.y *= otherVector.y;
  2438. return this;
  2439. };
  2440. /**
  2441. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2442. * @param otherVector defines the other vector
  2443. * @returns a new Vector2
  2444. */
  2445. Vector2.prototype.multiply = function (otherVector) {
  2446. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2447. };
  2448. /**
  2449. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2450. * @param otherVector defines the other vector
  2451. * @param result defines the target vector
  2452. * @returns the unmodified current Vector2
  2453. */
  2454. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2455. result.x = this.x * otherVector.x;
  2456. result.y = this.y * otherVector.y;
  2457. return this;
  2458. };
  2459. /**
  2460. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2461. * @param x defines the first coordinate
  2462. * @param y defines the second coordinate
  2463. * @returns a new Vector2
  2464. */
  2465. Vector2.prototype.multiplyByFloats = function (x, y) {
  2466. return new Vector2(this.x * x, this.y * y);
  2467. };
  2468. /**
  2469. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2470. * @param otherVector defines the other vector
  2471. * @returns a new Vector2
  2472. */
  2473. Vector2.prototype.divide = function (otherVector) {
  2474. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2475. };
  2476. /**
  2477. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2478. * @param otherVector defines the other vector
  2479. * @param result defines the target vector
  2480. * @returns the unmodified current Vector2
  2481. */
  2482. Vector2.prototype.divideToRef = function (otherVector, result) {
  2483. result.x = this.x / otherVector.x;
  2484. result.y = this.y / otherVector.y;
  2485. return this;
  2486. };
  2487. /**
  2488. * Divides the current Vector2 coordinates by the given ones
  2489. * @param otherVector defines the other vector
  2490. * @returns the current updated Vector2
  2491. */
  2492. Vector2.prototype.divideInPlace = function (otherVector) {
  2493. return this.divideToRef(otherVector, this);
  2494. };
  2495. /**
  2496. * Gets a new Vector2 with current Vector2 negated coordinates
  2497. * @returns a new Vector2
  2498. */
  2499. Vector2.prototype.negate = function () {
  2500. return new Vector2(-this.x, -this.y);
  2501. };
  2502. /**
  2503. * Multiply the Vector2 coordinates by scale
  2504. * @param scale defines the scaling factor
  2505. * @returns the current updated Vector2
  2506. */
  2507. Vector2.prototype.scaleInPlace = function (scale) {
  2508. this.x *= scale;
  2509. this.y *= scale;
  2510. return this;
  2511. };
  2512. /**
  2513. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2514. * @param scale defines the scaling factor
  2515. * @returns a new Vector2
  2516. */
  2517. Vector2.prototype.scale = function (scale) {
  2518. var result = new Vector2(0, 0);
  2519. this.scaleToRef(scale, result);
  2520. return result;
  2521. };
  2522. /**
  2523. * Scale the current Vector2 values by a factor to a given Vector2
  2524. * @param scale defines the scale factor
  2525. * @param result defines the Vector2 object where to store the result
  2526. * @returns the unmodified current Vector2
  2527. */
  2528. Vector2.prototype.scaleToRef = function (scale, result) {
  2529. result.x = this.x * scale;
  2530. result.y = this.y * scale;
  2531. return this;
  2532. };
  2533. /**
  2534. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2535. * @param scale defines the scale factor
  2536. * @param result defines the Vector2 object where to store the result
  2537. * @returns the unmodified current Vector2
  2538. */
  2539. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2540. result.x += this.x * scale;
  2541. result.y += this.y * scale;
  2542. return this;
  2543. };
  2544. /**
  2545. * Gets a boolean if two vectors are equals
  2546. * @param otherVector defines the other vector
  2547. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2548. */
  2549. Vector2.prototype.equals = function (otherVector) {
  2550. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2551. };
  2552. /**
  2553. * Gets a boolean if two vectors are equals (using an epsilon value)
  2554. * @param otherVector defines the other vector
  2555. * @param epsilon defines the minimal distance to consider equality
  2556. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2557. */
  2558. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2559. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2560. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2561. };
  2562. /**
  2563. * Gets a new Vector2 from current Vector2 floored values
  2564. * @returns a new Vector2
  2565. */
  2566. Vector2.prototype.floor = function () {
  2567. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2568. };
  2569. /**
  2570. * Gets a new Vector2 from current Vector2 floored values
  2571. * @returns a new Vector2
  2572. */
  2573. Vector2.prototype.fract = function () {
  2574. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2575. };
  2576. // Properties
  2577. /**
  2578. * Gets the length of the vector
  2579. * @returns the vector length (float)
  2580. */
  2581. Vector2.prototype.length = function () {
  2582. return Math.sqrt(this.x * this.x + this.y * this.y);
  2583. };
  2584. /**
  2585. * Gets the vector squared length
  2586. * @returns the vector squared length (float)
  2587. */
  2588. Vector2.prototype.lengthSquared = function () {
  2589. return (this.x * this.x + this.y * this.y);
  2590. };
  2591. // Methods
  2592. /**
  2593. * Normalize the vector
  2594. * @returns the current updated Vector2
  2595. */
  2596. Vector2.prototype.normalize = function () {
  2597. var len = this.length();
  2598. if (len === 0)
  2599. return this;
  2600. var num = 1.0 / len;
  2601. this.x *= num;
  2602. this.y *= num;
  2603. return this;
  2604. };
  2605. /**
  2606. * Gets a new Vector2 copied from the Vector2
  2607. * @returns a new Vector2
  2608. */
  2609. Vector2.prototype.clone = function () {
  2610. return new Vector2(this.x, this.y);
  2611. };
  2612. // Statics
  2613. /**
  2614. * Gets a new Vector2(0, 0)
  2615. * @returns a new Vector2
  2616. */
  2617. Vector2.Zero = function () {
  2618. return new Vector2(0, 0);
  2619. };
  2620. /**
  2621. * Gets a new Vector2(1, 1)
  2622. * @returns a new Vector2
  2623. */
  2624. Vector2.One = function () {
  2625. return new Vector2(1, 1);
  2626. };
  2627. /**
  2628. * Gets a new Vector2 set from the given index element of the given array
  2629. * @param array defines the data source
  2630. * @param offset defines the offset in the data source
  2631. * @returns a new Vector2
  2632. */
  2633. Vector2.FromArray = function (array, offset) {
  2634. if (offset === void 0) { offset = 0; }
  2635. return new Vector2(array[offset], array[offset + 1]);
  2636. };
  2637. /**
  2638. * Sets "result" from the given index element of the given array
  2639. * @param array defines the data source
  2640. * @param offset defines the offset in the data source
  2641. * @param result defines the target vector
  2642. */
  2643. Vector2.FromArrayToRef = function (array, offset, result) {
  2644. result.x = array[offset];
  2645. result.y = array[offset + 1];
  2646. };
  2647. /**
  2648. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2649. * @param value1 defines 1st point of control
  2650. * @param value2 defines 2nd point of control
  2651. * @param value3 defines 3rd point of control
  2652. * @param value4 defines 4th point of control
  2653. * @param amount defines the interpolation factor
  2654. * @returns a new Vector2
  2655. */
  2656. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2657. var squared = amount * amount;
  2658. var cubed = amount * squared;
  2659. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2660. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2661. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2662. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2663. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2664. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2665. return new Vector2(x, y);
  2666. };
  2667. /**
  2668. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2669. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2670. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2671. * @param value defines the value to clamp
  2672. * @param min defines the lower limit
  2673. * @param max defines the upper limit
  2674. * @returns a new Vector2
  2675. */
  2676. Vector2.Clamp = function (value, min, max) {
  2677. var x = value.x;
  2678. x = (x > max.x) ? max.x : x;
  2679. x = (x < min.x) ? min.x : x;
  2680. var y = value.y;
  2681. y = (y > max.y) ? max.y : y;
  2682. y = (y < min.y) ? min.y : y;
  2683. return new Vector2(x, y);
  2684. };
  2685. /**
  2686. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2687. * @param value1 defines the 1st control point
  2688. * @param tangent1 defines the outgoing tangent
  2689. * @param value2 defines the 2nd control point
  2690. * @param tangent2 defines the incoming tangent
  2691. * @param amount defines the interpolation factor
  2692. * @returns a new Vector2
  2693. */
  2694. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2695. var squared = amount * amount;
  2696. var cubed = amount * squared;
  2697. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2698. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2699. var part3 = (cubed - (2.0 * squared)) + amount;
  2700. var part4 = cubed - squared;
  2701. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2702. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2703. return new Vector2(x, y);
  2704. };
  2705. /**
  2706. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2707. * @param start defines the start vector
  2708. * @param end defines the end vector
  2709. * @param amount defines the interpolation factor
  2710. * @returns a new Vector2
  2711. */
  2712. Vector2.Lerp = function (start, end, amount) {
  2713. var x = start.x + ((end.x - start.x) * amount);
  2714. var y = start.y + ((end.y - start.y) * amount);
  2715. return new Vector2(x, y);
  2716. };
  2717. /**
  2718. * Gets the dot product of the vector "left" and the vector "right"
  2719. * @param left defines first vector
  2720. * @param right defines second vector
  2721. * @returns the dot product (float)
  2722. */
  2723. Vector2.Dot = function (left, right) {
  2724. return left.x * right.x + left.y * right.y;
  2725. };
  2726. /**
  2727. * Returns a new Vector2 equal to the normalized given vector
  2728. * @param vector defines the vector to normalize
  2729. * @returns a new Vector2
  2730. */
  2731. Vector2.Normalize = function (vector) {
  2732. var newVector = vector.clone();
  2733. newVector.normalize();
  2734. return newVector;
  2735. };
  2736. /**
  2737. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2738. * @param left defines 1st vector
  2739. * @param right defines 2nd vector
  2740. * @returns a new Vector2
  2741. */
  2742. Vector2.Minimize = function (left, right) {
  2743. var x = (left.x < right.x) ? left.x : right.x;
  2744. var y = (left.y < right.y) ? left.y : right.y;
  2745. return new Vector2(x, y);
  2746. };
  2747. /**
  2748. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2749. * @param left defines 1st vector
  2750. * @param right defines 2nd vector
  2751. * @returns a new Vector2
  2752. */
  2753. Vector2.Maximize = function (left, right) {
  2754. var x = (left.x > right.x) ? left.x : right.x;
  2755. var y = (left.y > right.y) ? left.y : right.y;
  2756. return new Vector2(x, y);
  2757. };
  2758. /**
  2759. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2760. * @param vector defines the vector to transform
  2761. * @param transformation defines the matrix to apply
  2762. * @returns a new Vector2
  2763. */
  2764. Vector2.Transform = function (vector, transformation) {
  2765. var r = Vector2.Zero();
  2766. Vector2.TransformToRef(vector, transformation, r);
  2767. return r;
  2768. };
  2769. /**
  2770. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2771. * @param vector defines the vector to transform
  2772. * @param transformation defines the matrix to apply
  2773. * @param result defines the target vector
  2774. */
  2775. Vector2.TransformToRef = function (vector, transformation, result) {
  2776. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2777. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2778. result.x = x;
  2779. result.y = y;
  2780. };
  2781. /**
  2782. * Determines if a given vector is included in a triangle
  2783. * @param p defines the vector to test
  2784. * @param p0 defines 1st triangle point
  2785. * @param p1 defines 2nd triangle point
  2786. * @param p2 defines 3rd triangle point
  2787. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2788. */
  2789. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2790. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2791. var sign = a < 0 ? -1 : 1;
  2792. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2793. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2794. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2795. };
  2796. /**
  2797. * Gets the distance between the vectors "value1" and "value2"
  2798. * @param value1 defines first vector
  2799. * @param value2 defines second vector
  2800. * @returns the distance between vectors
  2801. */
  2802. Vector2.Distance = function (value1, value2) {
  2803. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2804. };
  2805. /**
  2806. * Returns the squared distance between the vectors "value1" and "value2"
  2807. * @param value1 defines first vector
  2808. * @param value2 defines second vector
  2809. * @returns the squared distance between vectors
  2810. */
  2811. Vector2.DistanceSquared = function (value1, value2) {
  2812. var x = value1.x - value2.x;
  2813. var y = value1.y - value2.y;
  2814. return (x * x) + (y * y);
  2815. };
  2816. /**
  2817. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2818. * @param value1 defines first vector
  2819. * @param value2 defines second vector
  2820. * @returns a new Vector2
  2821. */
  2822. Vector2.Center = function (value1, value2) {
  2823. var center = value1.add(value2);
  2824. center.scaleInPlace(0.5);
  2825. return center;
  2826. };
  2827. /**
  2828. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2829. * @param p defines the middle point
  2830. * @param segA defines one point of the segment
  2831. * @param segB defines the other point of the segment
  2832. * @returns the shortest distance
  2833. */
  2834. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2835. var l2 = Vector2.DistanceSquared(segA, segB);
  2836. if (l2 === 0.0) {
  2837. return Vector2.Distance(p, segA);
  2838. }
  2839. var v = segB.subtract(segA);
  2840. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2841. var proj = segA.add(v.multiplyByFloats(t, t));
  2842. return Vector2.Distance(p, proj);
  2843. };
  2844. return Vector2;
  2845. }());
  2846. BABYLON.Vector2 = Vector2;
  2847. /**
  2848. * Classed used to store (x,y,z) vector representation
  2849. * A Vector3 is the main object used in 3D geometry
  2850. * It can represent etiher the coordinates of a point the space, either a direction
  2851. * Reminder: Babylon.js uses a left handed forward facing system
  2852. */
  2853. var Vector3 = /** @class */ (function () {
  2854. /**
  2855. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2856. * @param x defines the first coordinates (on X axis)
  2857. * @param y defines the second coordinates (on Y axis)
  2858. * @param z defines the third coordinates (on Z axis)
  2859. */
  2860. function Vector3(
  2861. /**
  2862. * Defines the first coordinates (on X axis)
  2863. */
  2864. x,
  2865. /**
  2866. * Defines the second coordinates (on Y axis)
  2867. */
  2868. y,
  2869. /**
  2870. * Defines the third coordinates (on Z axis)
  2871. */
  2872. z) {
  2873. if (x === void 0) { x = 0; }
  2874. if (y === void 0) { y = 0; }
  2875. if (z === void 0) { z = 0; }
  2876. this.x = x;
  2877. this.y = y;
  2878. this.z = z;
  2879. }
  2880. /**
  2881. * Creates a string representation of the Vector3
  2882. * @returns a string with the Vector3 coordinates.
  2883. */
  2884. Vector3.prototype.toString = function () {
  2885. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2886. };
  2887. /**
  2888. * Gets the class name
  2889. * @returns the string "Vector3"
  2890. */
  2891. Vector3.prototype.getClassName = function () {
  2892. return "Vector3";
  2893. };
  2894. /**
  2895. * Creates the Vector3 hash code
  2896. * @returns a number which tends to be unique between Vector3 instances
  2897. */
  2898. Vector3.prototype.getHashCode = function () {
  2899. var hash = this.x || 0;
  2900. hash = (hash * 397) ^ (this.y || 0);
  2901. hash = (hash * 397) ^ (this.z || 0);
  2902. return hash;
  2903. };
  2904. // Operators
  2905. /**
  2906. * Creates an array containing three elements : the coordinates of the Vector3
  2907. * @returns a new array of numbers
  2908. */
  2909. Vector3.prototype.asArray = function () {
  2910. var result = [];
  2911. this.toArray(result, 0);
  2912. return result;
  2913. };
  2914. /**
  2915. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2916. * @param array defines the destination array
  2917. * @param index defines the offset in the destination array
  2918. * @returns the current Vector3
  2919. */
  2920. Vector3.prototype.toArray = function (array, index) {
  2921. if (index === void 0) { index = 0; }
  2922. array[index] = this.x;
  2923. array[index + 1] = this.y;
  2924. array[index + 2] = this.z;
  2925. return this;
  2926. };
  2927. /**
  2928. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2929. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2930. */
  2931. Vector3.prototype.toQuaternion = function () {
  2932. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2933. };
  2934. /**
  2935. * Adds the given vector to the current Vector3
  2936. * @param otherVector defines the second operand
  2937. * @returns the current updated Vector3
  2938. */
  2939. Vector3.prototype.addInPlace = function (otherVector) {
  2940. this.x += otherVector.x;
  2941. this.y += otherVector.y;
  2942. this.z += otherVector.z;
  2943. return this;
  2944. };
  2945. /**
  2946. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2947. * @param otherVector defines the second operand
  2948. * @returns the resulting Vector3
  2949. */
  2950. Vector3.prototype.add = function (otherVector) {
  2951. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2952. };
  2953. /**
  2954. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2955. * @param otherVector defines the second operand
  2956. * @param result defines the Vector3 object where to store the result
  2957. * @returns the current Vector3
  2958. */
  2959. Vector3.prototype.addToRef = function (otherVector, result) {
  2960. result.x = this.x + otherVector.x;
  2961. result.y = this.y + otherVector.y;
  2962. result.z = this.z + otherVector.z;
  2963. return this;
  2964. };
  2965. /**
  2966. * Subtract the given vector from the current Vector3
  2967. * @param otherVector defines the second operand
  2968. * @returns the current updated Vector3
  2969. */
  2970. Vector3.prototype.subtractInPlace = function (otherVector) {
  2971. this.x -= otherVector.x;
  2972. this.y -= otherVector.y;
  2973. this.z -= otherVector.z;
  2974. return this;
  2975. };
  2976. /**
  2977. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2978. * @param otherVector defines the second operand
  2979. * @returns the resulting Vector3
  2980. */
  2981. Vector3.prototype.subtract = function (otherVector) {
  2982. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2983. };
  2984. /**
  2985. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2986. * @param otherVector defines the second operand
  2987. * @param result defines the Vector3 object where to store the result
  2988. * @returns the current Vector3
  2989. */
  2990. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2991. result.x = this.x - otherVector.x;
  2992. result.y = this.y - otherVector.y;
  2993. result.z = this.z - otherVector.z;
  2994. return this;
  2995. };
  2996. /**
  2997. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2998. * @param x defines the x coordinate of the operand
  2999. * @param y defines the y coordinate of the operand
  3000. * @param z defines the z coordinate of the operand
  3001. * @returns the resulting Vector3
  3002. */
  3003. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  3004. return new Vector3(this.x - x, this.y - y, this.z - z);
  3005. };
  3006. /**
  3007. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3008. * @param x defines the x coordinate of the operand
  3009. * @param y defines the y coordinate of the operand
  3010. * @param z defines the z coordinate of the operand
  3011. * @param result defines the Vector3 object where to store the result
  3012. * @returns the current Vector3
  3013. */
  3014. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3015. result.x = this.x - x;
  3016. result.y = this.y - y;
  3017. result.z = this.z - z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3022. * @returns a new Vector3
  3023. */
  3024. Vector3.prototype.negate = function () {
  3025. return new Vector3(-this.x, -this.y, -this.z);
  3026. };
  3027. /**
  3028. * Multiplies the Vector3 coordinates by the float "scale"
  3029. * @param scale defines the multiplier factor
  3030. * @returns the current updated Vector3
  3031. */
  3032. Vector3.prototype.scaleInPlace = function (scale) {
  3033. this.x *= scale;
  3034. this.y *= scale;
  3035. this.z *= scale;
  3036. return this;
  3037. };
  3038. /**
  3039. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3040. * @param scale defines the multiplier factor
  3041. * @returns a new Vector3
  3042. */
  3043. Vector3.prototype.scale = function (scale) {
  3044. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3045. };
  3046. /**
  3047. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3048. * @param scale defines the multiplier factor
  3049. * @param result defines the Vector3 object where to store the result
  3050. * @returns the current Vector3
  3051. */
  3052. Vector3.prototype.scaleToRef = function (scale, result) {
  3053. result.x = this.x * scale;
  3054. result.y = this.y * scale;
  3055. result.z = this.z * scale;
  3056. return this;
  3057. };
  3058. /**
  3059. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3060. * @param scale defines the scale factor
  3061. * @param result defines the Vector3 object where to store the result
  3062. * @returns the unmodified current Vector3
  3063. */
  3064. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3065. result.x += this.x * scale;
  3066. result.y += this.y * scale;
  3067. result.z += this.z * scale;
  3068. return this;
  3069. };
  3070. /**
  3071. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3072. * @param otherVector defines the second operand
  3073. * @returns true if both vectors are equals
  3074. */
  3075. Vector3.prototype.equals = function (otherVector) {
  3076. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3077. };
  3078. /**
  3079. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3080. * @param otherVector defines the second operand
  3081. * @param epsilon defines the minimal distance to define values as equals
  3082. * @returns true if both vectors are distant less than epsilon
  3083. */
  3084. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3085. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3086. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  3087. };
  3088. /**
  3089. * Returns true if the current Vector3 coordinates equals the given floats
  3090. * @param x defines the x coordinate of the operand
  3091. * @param y defines the y coordinate of the operand
  3092. * @param z defines the z coordinate of the operand
  3093. * @returns true if both vectors are equals
  3094. */
  3095. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3096. return this.x === x && this.y === y && this.z === z;
  3097. };
  3098. /**
  3099. * Multiplies the current Vector3 coordinates by the given ones
  3100. * @param otherVector defines the second operand
  3101. * @returns the current updated Vector3
  3102. */
  3103. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3104. this.x *= otherVector.x;
  3105. this.y *= otherVector.y;
  3106. this.z *= otherVector.z;
  3107. return this;
  3108. };
  3109. /**
  3110. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3111. * @param otherVector defines the second operand
  3112. * @returns the new Vector3
  3113. */
  3114. Vector3.prototype.multiply = function (otherVector) {
  3115. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3116. };
  3117. /**
  3118. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3119. * @param otherVector defines the second operand
  3120. * @param result defines the Vector3 object where to store the result
  3121. * @returns the current Vector3
  3122. */
  3123. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3124. result.x = this.x * otherVector.x;
  3125. result.y = this.y * otherVector.y;
  3126. result.z = this.z * otherVector.z;
  3127. return this;
  3128. };
  3129. /**
  3130. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3131. * @param x defines the x coordinate of the operand
  3132. * @param y defines the y coordinate of the operand
  3133. * @param z defines the z coordinate of the operand
  3134. * @returns the new Vector3
  3135. */
  3136. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3137. return new Vector3(this.x * x, this.y * y, this.z * z);
  3138. };
  3139. /**
  3140. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3141. * @param otherVector defines the second operand
  3142. * @returns the new Vector3
  3143. */
  3144. Vector3.prototype.divide = function (otherVector) {
  3145. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3146. };
  3147. /**
  3148. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3149. * @param otherVector defines the second operand
  3150. * @param result defines the Vector3 object where to store the result
  3151. * @returns the current Vector3
  3152. */
  3153. Vector3.prototype.divideToRef = function (otherVector, result) {
  3154. result.x = this.x / otherVector.x;
  3155. result.y = this.y / otherVector.y;
  3156. result.z = this.z / otherVector.z;
  3157. return this;
  3158. };
  3159. /**
  3160. * Divides the current Vector3 coordinates by the given ones.
  3161. * @param otherVector defines the second operand
  3162. * @returns the current updated Vector3
  3163. */
  3164. Vector3.prototype.divideInPlace = function (otherVector) {
  3165. return this.divideToRef(otherVector, this);
  3166. };
  3167. /**
  3168. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3169. * @param other defines the second operand
  3170. * @returns the current updated Vector3
  3171. */
  3172. Vector3.prototype.minimizeInPlace = function (other) {
  3173. if (other.x < this.x)
  3174. this.x = other.x;
  3175. if (other.y < this.y)
  3176. this.y = other.y;
  3177. if (other.z < this.z)
  3178. this.z = other.z;
  3179. return this;
  3180. };
  3181. /**
  3182. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3183. * @param other defines the second operand
  3184. * @returns the current updated Vector3
  3185. */
  3186. Vector3.prototype.maximizeInPlace = function (other) {
  3187. if (other.x > this.x)
  3188. this.x = other.x;
  3189. if (other.y > this.y)
  3190. this.y = other.y;
  3191. if (other.z > this.z)
  3192. this.z = other.z;
  3193. return this;
  3194. };
  3195. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3196. /**
  3197. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3198. */
  3199. get: function () {
  3200. var absX = Math.abs(this.x);
  3201. var absY = Math.abs(this.y);
  3202. if (absX !== absY) {
  3203. return true;
  3204. }
  3205. var absZ = Math.abs(this.z);
  3206. if (absX !== absZ) {
  3207. return true;
  3208. }
  3209. if (absY !== absZ) {
  3210. return true;
  3211. }
  3212. return false;
  3213. },
  3214. enumerable: true,
  3215. configurable: true
  3216. });
  3217. /**
  3218. * Gets a new Vector3 from current Vector3 floored values
  3219. * @returns a new Vector3
  3220. */
  3221. Vector3.prototype.floor = function () {
  3222. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3223. };
  3224. /**
  3225. * Gets a new Vector3 from current Vector3 floored values
  3226. * @returns a new Vector3
  3227. */
  3228. Vector3.prototype.fract = function () {
  3229. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3230. };
  3231. // Properties
  3232. /**
  3233. * Gets the length of the Vector3
  3234. * @returns the length of the Vecto3
  3235. */
  3236. Vector3.prototype.length = function () {
  3237. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3238. };
  3239. /**
  3240. * Gets the squared length of the Vector3
  3241. * @returns squared length of the Vector3
  3242. */
  3243. Vector3.prototype.lengthSquared = function () {
  3244. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3245. };
  3246. /**
  3247. * Normalize the current Vector3.
  3248. * Please note that this is an in place operation.
  3249. * @returns the current updated Vector3
  3250. */
  3251. Vector3.prototype.normalize = function () {
  3252. var len = this.length();
  3253. if (len === 0 || len === 1.0)
  3254. return this;
  3255. var num = 1.0 / len;
  3256. this.x *= num;
  3257. this.y *= num;
  3258. this.z *= num;
  3259. return this;
  3260. };
  3261. /**
  3262. * Normalize the current Vector3 to a new vector
  3263. * @returns the new Vector3
  3264. */
  3265. Vector3.prototype.normalizeToNew = function () {
  3266. var normalized = new Vector3(0, 0, 0);
  3267. this.normalizeToRef(normalized);
  3268. return normalized;
  3269. };
  3270. /**
  3271. * Normalize the current Vector3 to the reference
  3272. * @param reference define the Vector3 to update
  3273. * @returns the updated Vector3
  3274. */
  3275. Vector3.prototype.normalizeToRef = function (reference) {
  3276. var len = this.length();
  3277. if (len === 0 || len === 1.0) {
  3278. reference.set(this.x, this.y, this.z);
  3279. return reference;
  3280. }
  3281. var scale = 1.0 / len;
  3282. this.scaleToRef(scale, reference);
  3283. return reference;
  3284. };
  3285. /**
  3286. * Creates a new Vector3 copied from the current Vector3
  3287. * @returns the new Vector3
  3288. */
  3289. Vector3.prototype.clone = function () {
  3290. return new Vector3(this.x, this.y, this.z);
  3291. };
  3292. /**
  3293. * Copies the given vector coordinates to the current Vector3 ones
  3294. * @param source defines the source Vector3
  3295. * @returns the current updated Vector3
  3296. */
  3297. Vector3.prototype.copyFrom = function (source) {
  3298. this.x = source.x;
  3299. this.y = source.y;
  3300. this.z = source.z;
  3301. return this;
  3302. };
  3303. /**
  3304. * Copies the given floats to the current Vector3 coordinates
  3305. * @param x defines the x coordinate of the operand
  3306. * @param y defines the y coordinate of the operand
  3307. * @param z defines the z coordinate of the operand
  3308. * @returns the current updated Vector3
  3309. */
  3310. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3311. this.x = x;
  3312. this.y = y;
  3313. this.z = z;
  3314. return this;
  3315. };
  3316. /**
  3317. * Copies the given floats to the current Vector3 coordinates
  3318. * @param x defines the x coordinate of the operand
  3319. * @param y defines the y coordinate of the operand
  3320. * @param z defines the z coordinate of the operand
  3321. * @returns the current updated Vector3
  3322. */
  3323. Vector3.prototype.set = function (x, y, z) {
  3324. return this.copyFromFloats(x, y, z);
  3325. };
  3326. // Statics
  3327. /**
  3328. * Get the clip factor between two vectors
  3329. * @param vector0 defines the first operand
  3330. * @param vector1 defines the second operand
  3331. * @param axis defines the axis to use
  3332. * @param size defines the size along the axis
  3333. * @returns the clip factor
  3334. */
  3335. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3336. var d0 = Vector3.Dot(vector0, axis) - size;
  3337. var d1 = Vector3.Dot(vector1, axis) - size;
  3338. var s = d0 / (d0 - d1);
  3339. return s;
  3340. };
  3341. /**
  3342. * Get angle between two vectors
  3343. * @param vector0 angle between vector0 and vector1
  3344. * @param vector1 angle between vector0 and vector1
  3345. * @param normal direction of the normal
  3346. * @return the angle between vector0 and vector1
  3347. */
  3348. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3349. var v0 = vector0.clone().normalize();
  3350. var v1 = vector1.clone().normalize();
  3351. var dot = Vector3.Dot(v0, v1);
  3352. var n = Vector3.Cross(v0, v1);
  3353. if (Vector3.Dot(n, normal) > 0) {
  3354. return Math.acos(dot);
  3355. }
  3356. return -Math.acos(dot);
  3357. };
  3358. /**
  3359. * Returns a new Vector3 set from the index "offset" of the given array
  3360. * @param array defines the source array
  3361. * @param offset defines the offset in the source array
  3362. * @returns the new Vector3
  3363. */
  3364. Vector3.FromArray = function (array, offset) {
  3365. if (!offset) {
  3366. offset = 0;
  3367. }
  3368. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3369. };
  3370. /**
  3371. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3372. * This function is deprecated. Use FromArray instead
  3373. * @param array defines the source array
  3374. * @param offset defines the offset in the source array
  3375. * @returns the new Vector3
  3376. */
  3377. Vector3.FromFloatArray = function (array, offset) {
  3378. return Vector3.FromArray(array, offset);
  3379. };
  3380. /**
  3381. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3382. * @param array defines the source array
  3383. * @param offset defines the offset in the source array
  3384. * @param result defines the Vector3 where to store the result
  3385. */
  3386. Vector3.FromArrayToRef = function (array, offset, result) {
  3387. result.x = array[offset];
  3388. result.y = array[offset + 1];
  3389. result.z = array[offset + 2];
  3390. };
  3391. /**
  3392. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3393. * This function is deprecated. Use FromArrayToRef instead.
  3394. * @param array defines the source array
  3395. * @param offset defines the offset in the source array
  3396. * @param result defines the Vector3 where to store the result
  3397. */
  3398. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3399. return Vector3.FromArrayToRef(array, offset, result);
  3400. };
  3401. /**
  3402. * Sets the given vector "result" with the given floats.
  3403. * @param x defines the x coordinate of the source
  3404. * @param y defines the y coordinate of the source
  3405. * @param z defines the z coordinate of the source
  3406. * @param result defines the Vector3 where to store the result
  3407. */
  3408. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3409. result.x = x;
  3410. result.y = y;
  3411. result.z = z;
  3412. };
  3413. /**
  3414. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3415. * @returns a new empty Vector3
  3416. */
  3417. Vector3.Zero = function () {
  3418. return new Vector3(0.0, 0.0, 0.0);
  3419. };
  3420. /**
  3421. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3422. * @returns a new unit Vector3
  3423. */
  3424. Vector3.One = function () {
  3425. return new Vector3(1.0, 1.0, 1.0);
  3426. };
  3427. /**
  3428. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3429. * @returns a new up Vector3
  3430. */
  3431. Vector3.Up = function () {
  3432. return new Vector3(0.0, 1.0, 0.0);
  3433. };
  3434. /**
  3435. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3436. * @returns a new down Vector3
  3437. */
  3438. Vector3.Down = function () {
  3439. return new Vector3(0.0, -1.0, 0.0);
  3440. };
  3441. /**
  3442. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3443. * @returns a new forward Vector3
  3444. */
  3445. Vector3.Forward = function () {
  3446. return new Vector3(0.0, 0.0, 1.0);
  3447. };
  3448. /**
  3449. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  3450. * @returns a new forward Vector3
  3451. */
  3452. Vector3.Backward = function () {
  3453. return new Vector3(0.0, 0.0, -1.0);
  3454. };
  3455. /**
  3456. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3457. * @returns a new right Vector3
  3458. */
  3459. Vector3.Right = function () {
  3460. return new Vector3(1.0, 0.0, 0.0);
  3461. };
  3462. /**
  3463. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3464. * @returns a new left Vector3
  3465. */
  3466. Vector3.Left = function () {
  3467. return new Vector3(-1.0, 0.0, 0.0);
  3468. };
  3469. /**
  3470. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3471. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3472. * @param vector defines the Vector3 to transform
  3473. * @param transformation defines the transformation matrix
  3474. * @returns the transformed Vector3
  3475. */
  3476. Vector3.TransformCoordinates = function (vector, transformation) {
  3477. var result = Vector3.Zero();
  3478. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3479. return result;
  3480. };
  3481. /**
  3482. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3483. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3484. * @param vector defines the Vector3 to transform
  3485. * @param transformation defines the transformation matrix
  3486. * @param result defines the Vector3 where to store the result
  3487. */
  3488. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3489. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3490. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3491. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3492. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3493. result.x = x / w;
  3494. result.y = y / w;
  3495. result.z = z / w;
  3496. };
  3497. /**
  3498. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3499. * This method computes tranformed coordinates only, not transformed direction vectors
  3500. * @param x define the x coordinate of the source vector
  3501. * @param y define the y coordinate of the source vector
  3502. * @param z define the z coordinate of the source vector
  3503. * @param transformation defines the transformation matrix
  3504. * @param result defines the Vector3 where to store the result
  3505. */
  3506. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3507. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3508. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3509. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3510. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3511. result.x = rx / rw;
  3512. result.y = ry / rw;
  3513. result.z = rz / rw;
  3514. };
  3515. /**
  3516. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3517. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3518. * @param vector defines the Vector3 to transform
  3519. * @param transformation defines the transformation matrix
  3520. * @returns the new Vector3
  3521. */
  3522. Vector3.TransformNormal = function (vector, transformation) {
  3523. var result = Vector3.Zero();
  3524. Vector3.TransformNormalToRef(vector, transformation, result);
  3525. return result;
  3526. };
  3527. /**
  3528. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3529. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3530. * @param vector defines the Vector3 to transform
  3531. * @param transformation defines the transformation matrix
  3532. * @param result defines the Vector3 where to store the result
  3533. */
  3534. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3535. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3536. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3537. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3538. result.x = x;
  3539. result.y = y;
  3540. result.z = z;
  3541. };
  3542. /**
  3543. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3544. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3545. * @param x define the x coordinate of the source vector
  3546. * @param y define the y coordinate of the source vector
  3547. * @param z define the z coordinate of the source vector
  3548. * @param transformation defines the transformation matrix
  3549. * @param result defines the Vector3 where to store the result
  3550. */
  3551. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3552. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3553. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3554. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3555. };
  3556. /**
  3557. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3558. * @param value1 defines the first control point
  3559. * @param value2 defines the second control point
  3560. * @param value3 defines the third control point
  3561. * @param value4 defines the fourth control point
  3562. * @param amount defines the amount on the spline to use
  3563. * @returns the new Vector3
  3564. */
  3565. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3566. var squared = amount * amount;
  3567. var cubed = amount * squared;
  3568. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3569. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3570. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3571. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3572. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3573. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3574. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3575. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3576. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3577. return new Vector3(x, y, z);
  3578. };
  3579. /**
  3580. * 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"
  3581. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3582. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3583. * @param value defines the current value
  3584. * @param min defines the lower range value
  3585. * @param max defines the upper range value
  3586. * @returns the new Vector3
  3587. */
  3588. Vector3.Clamp = function (value, min, max) {
  3589. var x = value.x;
  3590. x = (x > max.x) ? max.x : x;
  3591. x = (x < min.x) ? min.x : x;
  3592. var y = value.y;
  3593. y = (y > max.y) ? max.y : y;
  3594. y = (y < min.y) ? min.y : y;
  3595. var z = value.z;
  3596. z = (z > max.z) ? max.z : z;
  3597. z = (z < min.z) ? min.z : z;
  3598. return new Vector3(x, y, z);
  3599. };
  3600. /**
  3601. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3602. * @param value1 defines the first control point
  3603. * @param tangent1 defines the first tangent vector
  3604. * @param value2 defines the second control point
  3605. * @param tangent2 defines the second tangent vector
  3606. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3607. * @returns the new Vector3
  3608. */
  3609. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3610. var squared = amount * amount;
  3611. var cubed = amount * squared;
  3612. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3613. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3614. var part3 = (cubed - (2.0 * squared)) + amount;
  3615. var part4 = cubed - squared;
  3616. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3617. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3618. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3619. return new Vector3(x, y, z);
  3620. };
  3621. /**
  3622. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3623. * @param start defines the start value
  3624. * @param end defines the end value
  3625. * @param amount max defines amount between both (between 0 and 1)
  3626. * @returns the new Vector3
  3627. */
  3628. Vector3.Lerp = function (start, end, amount) {
  3629. var result = new Vector3(0, 0, 0);
  3630. Vector3.LerpToRef(start, end, amount, result);
  3631. return result;
  3632. };
  3633. /**
  3634. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3635. * @param start defines the start value
  3636. * @param end defines the end value
  3637. * @param amount max defines amount between both (between 0 and 1)
  3638. * @param result defines the Vector3 where to store the result
  3639. */
  3640. Vector3.LerpToRef = function (start, end, amount, result) {
  3641. result.x = start.x + ((end.x - start.x) * amount);
  3642. result.y = start.y + ((end.y - start.y) * amount);
  3643. result.z = start.z + ((end.z - start.z) * amount);
  3644. };
  3645. /**
  3646. * Returns the dot product (float) between the vectors "left" and "right"
  3647. * @param left defines the left operand
  3648. * @param right defines the right operand
  3649. * @returns the dot product
  3650. */
  3651. Vector3.Dot = function (left, right) {
  3652. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3653. };
  3654. /**
  3655. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3656. * The cross product is then orthogonal to both "left" and "right"
  3657. * @param left defines the left operand
  3658. * @param right defines the right operand
  3659. * @returns the cross product
  3660. */
  3661. Vector3.Cross = function (left, right) {
  3662. var result = Vector3.Zero();
  3663. Vector3.CrossToRef(left, right, result);
  3664. return result;
  3665. };
  3666. /**
  3667. * Sets the given vector "result" with the cross product of "left" and "right"
  3668. * The cross product is then orthogonal to both "left" and "right"
  3669. * @param left defines the left operand
  3670. * @param right defines the right operand
  3671. * @param result defines the Vector3 where to store the result
  3672. */
  3673. Vector3.CrossToRef = function (left, right, result) {
  3674. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3675. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3676. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3677. result.copyFrom(MathTmp.Vector3[0]);
  3678. };
  3679. /**
  3680. * Returns a new Vector3 as the normalization of the given vector
  3681. * @param vector defines the Vector3 to normalize
  3682. * @returns the new Vector3
  3683. */
  3684. Vector3.Normalize = function (vector) {
  3685. var result = Vector3.Zero();
  3686. Vector3.NormalizeToRef(vector, result);
  3687. return result;
  3688. };
  3689. /**
  3690. * Sets the given vector "result" with the normalization of the given first vector
  3691. * @param vector defines the Vector3 to normalize
  3692. * @param result defines the Vector3 where to store the result
  3693. */
  3694. Vector3.NormalizeToRef = function (vector, result) {
  3695. result.copyFrom(vector);
  3696. result.normalize();
  3697. };
  3698. /**
  3699. * Project a Vector3 onto screen space
  3700. * @param vector defines the Vector3 to project
  3701. * @param world defines the world matrix to use
  3702. * @param transform defines the transform (view x projection) matrix to use
  3703. * @param viewport defines the screen viewport to use
  3704. * @returns the new Vector3
  3705. */
  3706. Vector3.Project = function (vector, world, transform, viewport) {
  3707. var cw = viewport.width;
  3708. var ch = viewport.height;
  3709. var cx = viewport.x;
  3710. var cy = viewport.y;
  3711. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3712. 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);
  3713. var matrix = MathTmp.Matrix[0];
  3714. world.multiplyToRef(transform, matrix);
  3715. matrix.multiplyToRef(viewportMatrix, matrix);
  3716. return Vector3.TransformCoordinates(vector, matrix);
  3717. };
  3718. /**
  3719. * Unproject from screen space to object space
  3720. * @param source defines the screen space Vector3 to use
  3721. * @param viewportWidth defines the current width of the viewport
  3722. * @param viewportHeight defines the current height of the viewport
  3723. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3724. * @param transform defines the transform (view x projection) matrix to use
  3725. * @returns the new Vector3
  3726. */
  3727. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3728. var matrix = MathTmp.Matrix[0];
  3729. world.multiplyToRef(transform, matrix);
  3730. matrix.invert();
  3731. source.x = source.x / viewportWidth * 2 - 1;
  3732. source.y = -(source.y / viewportHeight * 2 - 1);
  3733. var vector = Vector3.TransformCoordinates(source, matrix);
  3734. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3735. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3736. vector = vector.scale(1.0 / num);
  3737. }
  3738. return vector;
  3739. };
  3740. /**
  3741. * Unproject from screen space to object space
  3742. * @param source defines the screen space Vector3 to use
  3743. * @param viewportWidth defines the current width of the viewport
  3744. * @param viewportHeight defines the current height of the viewport
  3745. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3746. * @param view defines the view matrix to use
  3747. * @param projection defines the projection matrix to use
  3748. * @returns the new Vector3
  3749. */
  3750. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3751. var result = Vector3.Zero();
  3752. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3753. return result;
  3754. };
  3755. /**
  3756. * Unproject from screen space to object space
  3757. * @param source defines the screen space Vector3 to use
  3758. * @param viewportWidth defines the current width of the viewport
  3759. * @param viewportHeight defines the current height of the viewport
  3760. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3761. * @param view defines the view matrix to use
  3762. * @param projection defines the projection matrix to use
  3763. * @param result defines the Vector3 where to store the result
  3764. */
  3765. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3766. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3767. };
  3768. /**
  3769. * Unproject from screen space to object space
  3770. * @param sourceX defines the screen space x coordinate to use
  3771. * @param sourceY defines the screen space y coordinate to use
  3772. * @param sourceZ defines the screen space z coordinate to use
  3773. * @param viewportWidth defines the current width of the viewport
  3774. * @param viewportHeight defines the current height of the viewport
  3775. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3776. * @param view defines the view matrix to use
  3777. * @param projection defines the projection matrix to use
  3778. * @param result defines the Vector3 where to store the result
  3779. */
  3780. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3781. var matrix = MathTmp.Matrix[0];
  3782. world.multiplyToRef(view, matrix);
  3783. matrix.multiplyToRef(projection, matrix);
  3784. matrix.invert();
  3785. var screenSource = MathTmp.Vector3[0];
  3786. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3787. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3788. screenSource.z = 2 * sourceZ - 1.0;
  3789. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3790. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3791. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3792. result.scaleInPlace(1.0 / num);
  3793. }
  3794. };
  3795. /**
  3796. * Gets the minimal coordinate values between two Vector3
  3797. * @param left defines the first operand
  3798. * @param right defines the second operand
  3799. * @returns the new Vector3
  3800. */
  3801. Vector3.Minimize = function (left, right) {
  3802. var min = left.clone();
  3803. min.minimizeInPlace(right);
  3804. return min;
  3805. };
  3806. /**
  3807. * Gets the maximal coordinate values between two Vector3
  3808. * @param left defines the first operand
  3809. * @param right defines the second operand
  3810. * @returns the new Vector3
  3811. */
  3812. Vector3.Maximize = function (left, right) {
  3813. var max = left.clone();
  3814. max.maximizeInPlace(right);
  3815. return max;
  3816. };
  3817. /**
  3818. * Returns the distance between the vectors "value1" and "value2"
  3819. * @param value1 defines the first operand
  3820. * @param value2 defines the second operand
  3821. * @returns the distance
  3822. */
  3823. Vector3.Distance = function (value1, value2) {
  3824. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3825. };
  3826. /**
  3827. * Returns the squared distance between the vectors "value1" and "value2"
  3828. * @param value1 defines the first operand
  3829. * @param value2 defines the second operand
  3830. * @returns the squared distance
  3831. */
  3832. Vector3.DistanceSquared = function (value1, value2) {
  3833. var x = value1.x - value2.x;
  3834. var y = value1.y - value2.y;
  3835. var z = value1.z - value2.z;
  3836. return (x * x) + (y * y) + (z * z);
  3837. };
  3838. /**
  3839. * Returns a new Vector3 located at the center between "value1" and "value2"
  3840. * @param value1 defines the first operand
  3841. * @param value2 defines the second operand
  3842. * @returns the new Vector3
  3843. */
  3844. Vector3.Center = function (value1, value2) {
  3845. var center = value1.add(value2);
  3846. center.scaleInPlace(0.5);
  3847. return center;
  3848. };
  3849. /**
  3850. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3851. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3852. * to something in order to rotate it from its local system to the given target system
  3853. * Note: axis1, axis2 and axis3 are normalized during this operation
  3854. * @param axis1 defines the first axis
  3855. * @param axis2 defines the second axis
  3856. * @param axis3 defines the third axis
  3857. * @returns a new Vector3
  3858. */
  3859. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3860. var rotation = Vector3.Zero();
  3861. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3862. return rotation;
  3863. };
  3864. /**
  3865. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3866. * @param axis1 defines the first axis
  3867. * @param axis2 defines the second axis
  3868. * @param axis3 defines the third axis
  3869. * @param ref defines the Vector3 where to store the result
  3870. */
  3871. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3872. var quat = MathTmp.Quaternion[0];
  3873. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3874. quat.toEulerAnglesToRef(ref);
  3875. };
  3876. return Vector3;
  3877. }());
  3878. BABYLON.Vector3 = Vector3;
  3879. //Vector4 class created for EulerAngle class conversion to Quaternion
  3880. var Vector4 = /** @class */ (function () {
  3881. /**
  3882. * Creates a Vector4 object from the given floats.
  3883. */
  3884. function Vector4(x, y, z, w) {
  3885. this.x = x;
  3886. this.y = y;
  3887. this.z = z;
  3888. this.w = w;
  3889. }
  3890. /**
  3891. * Returns the string with the Vector4 coordinates.
  3892. */
  3893. Vector4.prototype.toString = function () {
  3894. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3895. };
  3896. /**
  3897. * Returns the string "Vector4".
  3898. */
  3899. Vector4.prototype.getClassName = function () {
  3900. return "Vector4";
  3901. };
  3902. /**
  3903. * Returns the Vector4 hash code.
  3904. */
  3905. Vector4.prototype.getHashCode = function () {
  3906. var hash = this.x || 0;
  3907. hash = (hash * 397) ^ (this.y || 0);
  3908. hash = (hash * 397) ^ (this.z || 0);
  3909. hash = (hash * 397) ^ (this.w || 0);
  3910. return hash;
  3911. };
  3912. // Operators
  3913. /**
  3914. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3915. */
  3916. Vector4.prototype.asArray = function () {
  3917. var result = new Array();
  3918. this.toArray(result, 0);
  3919. return result;
  3920. };
  3921. /**
  3922. * Populates the given array from the given index with the Vector4 coordinates.
  3923. * Returns the Vector4.
  3924. */
  3925. Vector4.prototype.toArray = function (array, index) {
  3926. if (index === undefined) {
  3927. index = 0;
  3928. }
  3929. array[index] = this.x;
  3930. array[index + 1] = this.y;
  3931. array[index + 2] = this.z;
  3932. array[index + 3] = this.w;
  3933. return this;
  3934. };
  3935. /**
  3936. * Adds the given vector to the current Vector4.
  3937. * Returns the updated Vector4.
  3938. */
  3939. Vector4.prototype.addInPlace = function (otherVector) {
  3940. this.x += otherVector.x;
  3941. this.y += otherVector.y;
  3942. this.z += otherVector.z;
  3943. this.w += otherVector.w;
  3944. return this;
  3945. };
  3946. /**
  3947. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3948. */
  3949. Vector4.prototype.add = function (otherVector) {
  3950. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3951. };
  3952. /**
  3953. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3954. * Returns the current Vector4.
  3955. */
  3956. Vector4.prototype.addToRef = function (otherVector, result) {
  3957. result.x = this.x + otherVector.x;
  3958. result.y = this.y + otherVector.y;
  3959. result.z = this.z + otherVector.z;
  3960. result.w = this.w + otherVector.w;
  3961. return this;
  3962. };
  3963. /**
  3964. * Subtract in place the given vector from the current Vector4.
  3965. * Returns the updated Vector4.
  3966. */
  3967. Vector4.prototype.subtractInPlace = function (otherVector) {
  3968. this.x -= otherVector.x;
  3969. this.y -= otherVector.y;
  3970. this.z -= otherVector.z;
  3971. this.w -= otherVector.w;
  3972. return this;
  3973. };
  3974. /**
  3975. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3976. */
  3977. Vector4.prototype.subtract = function (otherVector) {
  3978. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3979. };
  3980. /**
  3981. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3982. * Returns the current Vector4.
  3983. */
  3984. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3985. result.x = this.x - otherVector.x;
  3986. result.y = this.y - otherVector.y;
  3987. result.z = this.z - otherVector.z;
  3988. result.w = this.w - otherVector.w;
  3989. return this;
  3990. };
  3991. /**
  3992. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3993. */
  3994. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3995. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3996. };
  3997. /**
  3998. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3999. * Returns the current Vector4.
  4000. */
  4001. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  4002. result.x = this.x - x;
  4003. result.y = this.y - y;
  4004. result.z = this.z - z;
  4005. result.w = this.w - w;
  4006. return this;
  4007. };
  4008. /**
  4009. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  4010. */
  4011. Vector4.prototype.negate = function () {
  4012. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  4013. };
  4014. /**
  4015. * Multiplies the current Vector4 coordinates by scale (float).
  4016. * Returns the updated Vector4.
  4017. */
  4018. Vector4.prototype.scaleInPlace = function (scale) {
  4019. this.x *= scale;
  4020. this.y *= scale;
  4021. this.z *= scale;
  4022. this.w *= scale;
  4023. return this;
  4024. };
  4025. /**
  4026. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4027. */
  4028. Vector4.prototype.scale = function (scale) {
  4029. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4030. };
  4031. /**
  4032. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4033. * Returns the current Vector4.
  4034. */
  4035. Vector4.prototype.scaleToRef = function (scale, result) {
  4036. result.x = this.x * scale;
  4037. result.y = this.y * scale;
  4038. result.z = this.z * scale;
  4039. result.w = this.w * scale;
  4040. return this;
  4041. };
  4042. /**
  4043. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4044. * @param scale defines the scale factor
  4045. * @param result defines the Vector4 object where to store the result
  4046. * @returns the unmodified current Vector4
  4047. */
  4048. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4049. result.x += this.x * scale;
  4050. result.y += this.y * scale;
  4051. result.z += this.z * scale;
  4052. result.w += this.w * scale;
  4053. return this;
  4054. };
  4055. /**
  4056. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4057. */
  4058. Vector4.prototype.equals = function (otherVector) {
  4059. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4060. };
  4061. /**
  4062. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4063. */
  4064. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4065. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4066. return otherVector
  4067. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4068. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4069. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4070. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4071. };
  4072. /**
  4073. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4074. */
  4075. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4076. return this.x === x && this.y === y && this.z === z && this.w === w;
  4077. };
  4078. /**
  4079. * Multiplies in place the current Vector4 by the given one.
  4080. * Returns the updated Vector4.
  4081. */
  4082. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4083. this.x *= otherVector.x;
  4084. this.y *= otherVector.y;
  4085. this.z *= otherVector.z;
  4086. this.w *= otherVector.w;
  4087. return this;
  4088. };
  4089. /**
  4090. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4091. */
  4092. Vector4.prototype.multiply = function (otherVector) {
  4093. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4094. };
  4095. /**
  4096. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4097. * Returns the current Vector4.
  4098. */
  4099. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4100. result.x = this.x * otherVector.x;
  4101. result.y = this.y * otherVector.y;
  4102. result.z = this.z * otherVector.z;
  4103. result.w = this.w * otherVector.w;
  4104. return this;
  4105. };
  4106. /**
  4107. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4108. */
  4109. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4110. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4111. };
  4112. /**
  4113. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4114. */
  4115. Vector4.prototype.divide = function (otherVector) {
  4116. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4117. };
  4118. /**
  4119. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4120. * Returns the current Vector4.
  4121. */
  4122. Vector4.prototype.divideToRef = function (otherVector, result) {
  4123. result.x = this.x / otherVector.x;
  4124. result.y = this.y / otherVector.y;
  4125. result.z = this.z / otherVector.z;
  4126. result.w = this.w / otherVector.w;
  4127. return this;
  4128. };
  4129. /**
  4130. * Divides the current Vector3 coordinates by the given ones.
  4131. * @returns the updated Vector3.
  4132. */
  4133. Vector4.prototype.divideInPlace = function (otherVector) {
  4134. return this.divideToRef(otherVector, this);
  4135. };
  4136. /**
  4137. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4138. * @param other defines the second operand
  4139. * @returns the current updated Vector4
  4140. */
  4141. Vector4.prototype.minimizeInPlace = function (other) {
  4142. if (other.x < this.x)
  4143. this.x = other.x;
  4144. if (other.y < this.y)
  4145. this.y = other.y;
  4146. if (other.z < this.z)
  4147. this.z = other.z;
  4148. if (other.w < this.w)
  4149. this.w = other.w;
  4150. return this;
  4151. };
  4152. /**
  4153. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4154. * @param other defines the second operand
  4155. * @returns the current updated Vector4
  4156. */
  4157. Vector4.prototype.maximizeInPlace = function (other) {
  4158. if (other.x > this.x)
  4159. this.x = other.x;
  4160. if (other.y > this.y)
  4161. this.y = other.y;
  4162. if (other.z > this.z)
  4163. this.z = other.z;
  4164. if (other.w > this.w)
  4165. this.w = other.w;
  4166. return this;
  4167. };
  4168. /**
  4169. * Gets a new Vector4 from current Vector4 floored values
  4170. * @returns a new Vector4
  4171. */
  4172. Vector4.prototype.floor = function () {
  4173. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4174. };
  4175. /**
  4176. * Gets a new Vector4 from current Vector3 floored values
  4177. * @returns a new Vector4
  4178. */
  4179. Vector4.prototype.fract = function () {
  4180. 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));
  4181. };
  4182. // Properties
  4183. /**
  4184. * Returns the Vector4 length (float).
  4185. */
  4186. Vector4.prototype.length = function () {
  4187. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4188. };
  4189. /**
  4190. * Returns the Vector4 squared length (float).
  4191. */
  4192. Vector4.prototype.lengthSquared = function () {
  4193. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4194. };
  4195. // Methods
  4196. /**
  4197. * Normalizes in place the Vector4.
  4198. * Returns the updated Vector4.
  4199. */
  4200. Vector4.prototype.normalize = function () {
  4201. var len = this.length();
  4202. if (len === 0)
  4203. return this;
  4204. var num = 1.0 / len;
  4205. this.x *= num;
  4206. this.y *= num;
  4207. this.z *= num;
  4208. this.w *= num;
  4209. return this;
  4210. };
  4211. /**
  4212. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4213. */
  4214. Vector4.prototype.toVector3 = function () {
  4215. return new Vector3(this.x, this.y, this.z);
  4216. };
  4217. /**
  4218. * Returns a new Vector4 copied from the current one.
  4219. */
  4220. Vector4.prototype.clone = function () {
  4221. return new Vector4(this.x, this.y, this.z, this.w);
  4222. };
  4223. /**
  4224. * Updates the current Vector4 with the given one coordinates.
  4225. * Returns the updated Vector4.
  4226. */
  4227. Vector4.prototype.copyFrom = function (source) {
  4228. this.x = source.x;
  4229. this.y = source.y;
  4230. this.z = source.z;
  4231. this.w = source.w;
  4232. return this;
  4233. };
  4234. /**
  4235. * Updates the current Vector4 coordinates with the given floats.
  4236. * Returns the updated Vector4.
  4237. */
  4238. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4239. this.x = x;
  4240. this.y = y;
  4241. this.z = z;
  4242. this.w = w;
  4243. return this;
  4244. };
  4245. /**
  4246. * Updates the current Vector4 coordinates with the given floats.
  4247. * Returns the updated Vector4.
  4248. */
  4249. Vector4.prototype.set = function (x, y, z, w) {
  4250. return this.copyFromFloats(x, y, z, w);
  4251. };
  4252. // Statics
  4253. /**
  4254. * Returns a new Vector4 set from the starting index of the given array.
  4255. */
  4256. Vector4.FromArray = function (array, offset) {
  4257. if (!offset) {
  4258. offset = 0;
  4259. }
  4260. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4261. };
  4262. /**
  4263. * Updates the given vector "result" from the starting index of the given array.
  4264. */
  4265. Vector4.FromArrayToRef = function (array, offset, result) {
  4266. result.x = array[offset];
  4267. result.y = array[offset + 1];
  4268. result.z = array[offset + 2];
  4269. result.w = array[offset + 3];
  4270. };
  4271. /**
  4272. * Updates the given vector "result" from the starting index of the given Float32Array.
  4273. */
  4274. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4275. Vector4.FromArrayToRef(array, offset, result);
  4276. };
  4277. /**
  4278. * Updates the given vector "result" coordinates from the given floats.
  4279. */
  4280. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4281. result.x = x;
  4282. result.y = y;
  4283. result.z = z;
  4284. result.w = w;
  4285. };
  4286. /**
  4287. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4288. */
  4289. Vector4.Zero = function () {
  4290. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4291. };
  4292. /**
  4293. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4294. */
  4295. Vector4.One = function () {
  4296. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4297. };
  4298. /**
  4299. * Returns a new normalized Vector4 from the given one.
  4300. */
  4301. Vector4.Normalize = function (vector) {
  4302. var result = Vector4.Zero();
  4303. Vector4.NormalizeToRef(vector, result);
  4304. return result;
  4305. };
  4306. /**
  4307. * Updates the given vector "result" from the normalization of the given one.
  4308. */
  4309. Vector4.NormalizeToRef = function (vector, result) {
  4310. result.copyFrom(vector);
  4311. result.normalize();
  4312. };
  4313. Vector4.Minimize = function (left, right) {
  4314. var min = left.clone();
  4315. min.minimizeInPlace(right);
  4316. return min;
  4317. };
  4318. Vector4.Maximize = function (left, right) {
  4319. var max = left.clone();
  4320. max.maximizeInPlace(right);
  4321. return max;
  4322. };
  4323. /**
  4324. * Returns the distance (float) between the vectors "value1" and "value2".
  4325. */
  4326. Vector4.Distance = function (value1, value2) {
  4327. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4328. };
  4329. /**
  4330. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4331. */
  4332. Vector4.DistanceSquared = function (value1, value2) {
  4333. var x = value1.x - value2.x;
  4334. var y = value1.y - value2.y;
  4335. var z = value1.z - value2.z;
  4336. var w = value1.w - value2.w;
  4337. return (x * x) + (y * y) + (z * z) + (w * w);
  4338. };
  4339. /**
  4340. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4341. */
  4342. Vector4.Center = function (value1, value2) {
  4343. var center = value1.add(value2);
  4344. center.scaleInPlace(0.5);
  4345. return center;
  4346. };
  4347. /**
  4348. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4349. * This methods computes transformed normalized direction vectors only.
  4350. */
  4351. Vector4.TransformNormal = function (vector, transformation) {
  4352. var result = Vector4.Zero();
  4353. Vector4.TransformNormalToRef(vector, transformation, result);
  4354. return result;
  4355. };
  4356. /**
  4357. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4358. * This methods computes transformed normalized direction vectors only.
  4359. */
  4360. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4361. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4362. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4363. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4364. result.x = x;
  4365. result.y = y;
  4366. result.z = z;
  4367. result.w = vector.w;
  4368. };
  4369. /**
  4370. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4371. * This methods computes transformed normalized direction vectors only.
  4372. */
  4373. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4374. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4375. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4376. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4377. result.w = w;
  4378. };
  4379. return Vector4;
  4380. }());
  4381. BABYLON.Vector4 = Vector4;
  4382. var Size = /** @class */ (function () {
  4383. /**
  4384. * Creates a Size object from the given width and height (floats).
  4385. */
  4386. function Size(width, height) {
  4387. this.width = width;
  4388. this.height = height;
  4389. }
  4390. // Returns a string with the Size width and height.
  4391. Size.prototype.toString = function () {
  4392. return "{W: " + this.width + ", H: " + this.height + "}";
  4393. };
  4394. /**
  4395. * Returns the string "Size"
  4396. */
  4397. Size.prototype.getClassName = function () {
  4398. return "Size";
  4399. };
  4400. /**
  4401. * Returns the Size hash code.
  4402. */
  4403. Size.prototype.getHashCode = function () {
  4404. var hash = this.width || 0;
  4405. hash = (hash * 397) ^ (this.height || 0);
  4406. return hash;
  4407. };
  4408. /**
  4409. * Updates the current size from the given one.
  4410. * Returns the updated Size.
  4411. */
  4412. Size.prototype.copyFrom = function (src) {
  4413. this.width = src.width;
  4414. this.height = src.height;
  4415. };
  4416. /**
  4417. * Updates in place the current Size from the given floats.
  4418. * Returns the updated Size.
  4419. */
  4420. Size.prototype.copyFromFloats = function (width, height) {
  4421. this.width = width;
  4422. this.height = height;
  4423. return this;
  4424. };
  4425. /**
  4426. * Updates in place the current Size from the given floats.
  4427. * Returns the updated Size.
  4428. */
  4429. Size.prototype.set = function (width, height) {
  4430. return this.copyFromFloats(width, height);
  4431. };
  4432. /**
  4433. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4434. */
  4435. Size.prototype.multiplyByFloats = function (w, h) {
  4436. return new Size(this.width * w, this.height * h);
  4437. };
  4438. /**
  4439. * Returns a new Size copied from the given one.
  4440. */
  4441. Size.prototype.clone = function () {
  4442. return new Size(this.width, this.height);
  4443. };
  4444. /**
  4445. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4446. */
  4447. Size.prototype.equals = function (other) {
  4448. if (!other) {
  4449. return false;
  4450. }
  4451. return (this.width === other.width) && (this.height === other.height);
  4452. };
  4453. Object.defineProperty(Size.prototype, "surface", {
  4454. /**
  4455. * Returns the surface of the Size : width * height (float).
  4456. */
  4457. get: function () {
  4458. return this.width * this.height;
  4459. },
  4460. enumerable: true,
  4461. configurable: true
  4462. });
  4463. /**
  4464. * Returns a new Size set to (0.0, 0.0)
  4465. */
  4466. Size.Zero = function () {
  4467. return new Size(0.0, 0.0);
  4468. };
  4469. /**
  4470. * Returns a new Size set as the addition result of the current Size and the given one.
  4471. */
  4472. Size.prototype.add = function (otherSize) {
  4473. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4474. return r;
  4475. };
  4476. /**
  4477. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4478. */
  4479. Size.prototype.subtract = function (otherSize) {
  4480. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4481. return r;
  4482. };
  4483. /**
  4484. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4485. */
  4486. Size.Lerp = function (start, end, amount) {
  4487. var w = start.width + ((end.width - start.width) * amount);
  4488. var h = start.height + ((end.height - start.height) * amount);
  4489. return new Size(w, h);
  4490. };
  4491. return Size;
  4492. }());
  4493. BABYLON.Size = Size;
  4494. /**
  4495. * Class used to store quaternion data
  4496. * @see https://en.wikipedia.org/wiki/Quaternion
  4497. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4498. */
  4499. var Quaternion = /** @class */ (function () {
  4500. /**
  4501. * Creates a new Quaternion from the given floats
  4502. * @param x defines the first component (0 by default)
  4503. * @param y defines the second component (0 by default)
  4504. * @param z defines the third component (0 by default)
  4505. * @param w defines the fourth component (1.0 by default)
  4506. */
  4507. function Quaternion(
  4508. /** defines the first component (0 by default) */
  4509. x,
  4510. /** defines the second component (0 by default) */
  4511. y,
  4512. /** defines the third component (0 by default) */
  4513. z,
  4514. /** defines the fourth component (1.0 by default) */
  4515. w) {
  4516. if (x === void 0) { x = 0.0; }
  4517. if (y === void 0) { y = 0.0; }
  4518. if (z === void 0) { z = 0.0; }
  4519. if (w === void 0) { w = 1.0; }
  4520. this.x = x;
  4521. this.y = y;
  4522. this.z = z;
  4523. this.w = w;
  4524. }
  4525. /**
  4526. * Gets a string representation for the current quaternion
  4527. * @returns a string with the Quaternion coordinates
  4528. */
  4529. Quaternion.prototype.toString = function () {
  4530. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4531. };
  4532. /**
  4533. * Gets the class name of the quaternion
  4534. * @returns the string "Quaternion"
  4535. */
  4536. Quaternion.prototype.getClassName = function () {
  4537. return "Quaternion";
  4538. };
  4539. /**
  4540. * Gets a hash code for this quaternion
  4541. * @returns the quaternion hash code
  4542. */
  4543. Quaternion.prototype.getHashCode = function () {
  4544. var hash = this.x || 0;
  4545. hash = (hash * 397) ^ (this.y || 0);
  4546. hash = (hash * 397) ^ (this.z || 0);
  4547. hash = (hash * 397) ^ (this.w || 0);
  4548. return hash;
  4549. };
  4550. /**
  4551. * Copy the quaternion to an array
  4552. * @returns a new array populated with 4 elements from the quaternion coordinates
  4553. */
  4554. Quaternion.prototype.asArray = function () {
  4555. return [this.x, this.y, this.z, this.w];
  4556. };
  4557. /**
  4558. * Check if two quaternions are equals
  4559. * @param otherQuaternion defines the second operand
  4560. * @return true if the current quaternion and the given one coordinates are strictly equals
  4561. */
  4562. Quaternion.prototype.equals = function (otherQuaternion) {
  4563. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4564. };
  4565. /**
  4566. * Clone the current quaternion
  4567. * @returns a new quaternion copied from the current one
  4568. */
  4569. Quaternion.prototype.clone = function () {
  4570. return new Quaternion(this.x, this.y, this.z, this.w);
  4571. };
  4572. /**
  4573. * Copy a quaternion to the current one
  4574. * @param other defines the other quaternion
  4575. * @returns the updated current quaternion
  4576. */
  4577. Quaternion.prototype.copyFrom = function (other) {
  4578. this.x = other.x;
  4579. this.y = other.y;
  4580. this.z = other.z;
  4581. this.w = other.w;
  4582. return this;
  4583. };
  4584. /**
  4585. * Updates the current quaternion with the given float coordinates
  4586. * @param x defines the x coordinate
  4587. * @param y defines the y coordinate
  4588. * @param z defines the z coordinate
  4589. * @param w defines the w coordinate
  4590. * @returns the updated current quaternion
  4591. */
  4592. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4593. this.x = x;
  4594. this.y = y;
  4595. this.z = z;
  4596. this.w = w;
  4597. return this;
  4598. };
  4599. /**
  4600. * Updates the current quaternion from the given float coordinates
  4601. * @param x defines the x coordinate
  4602. * @param y defines the y coordinate
  4603. * @param z defines the z coordinate
  4604. * @param w defines the w coordinate
  4605. * @returns the updated current quaternion
  4606. */
  4607. Quaternion.prototype.set = function (x, y, z, w) {
  4608. return this.copyFromFloats(x, y, z, w);
  4609. };
  4610. /**
  4611. * Adds two quaternions
  4612. * @param other defines the second operand
  4613. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4614. */
  4615. Quaternion.prototype.add = function (other) {
  4616. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4617. };
  4618. /**
  4619. * Add a quaternion to the current one
  4620. * @param other defines the quaternion to add
  4621. * @returns the current quaternion
  4622. */
  4623. Quaternion.prototype.addInPlace = function (other) {
  4624. this.x += other.x;
  4625. this.y += other.y;
  4626. this.z += other.z;
  4627. this.w += other.w;
  4628. return this;
  4629. };
  4630. /**
  4631. * Subtract two quaternions
  4632. * @param other defines the second operand
  4633. * @returns a new quaternion as the subtraction result of the given one from the current one
  4634. */
  4635. Quaternion.prototype.subtract = function (other) {
  4636. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4637. };
  4638. /**
  4639. * Multiplies the current quaternion by a scale factor
  4640. * @param value defines the scale factor
  4641. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4642. */
  4643. Quaternion.prototype.scale = function (value) {
  4644. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4645. };
  4646. /**
  4647. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4648. * @param scale defines the scale factor
  4649. * @param result defines the Quaternion object where to store the result
  4650. * @returns the unmodified current quaternion
  4651. */
  4652. Quaternion.prototype.scaleToRef = function (scale, result) {
  4653. result.x = this.x * scale;
  4654. result.y = this.y * scale;
  4655. result.z = this.z * scale;
  4656. result.w = this.w * scale;
  4657. return this;
  4658. };
  4659. /**
  4660. * Multiplies in place the current quaternion by a scale factor
  4661. * @param value defines the scale factor
  4662. * @returns the current modified quaternion
  4663. */
  4664. Quaternion.prototype.scaleInPlace = function (value) {
  4665. this.x *= value;
  4666. this.y *= value;
  4667. this.z *= value;
  4668. this.w *= value;
  4669. return this;
  4670. };
  4671. /**
  4672. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4673. * @param scale defines the scale factor
  4674. * @param result defines the Quaternion object where to store the result
  4675. * @returns the unmodified current quaternion
  4676. */
  4677. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4678. result.x += this.x * scale;
  4679. result.y += this.y * scale;
  4680. result.z += this.z * scale;
  4681. result.w += this.w * scale;
  4682. return this;
  4683. };
  4684. /**
  4685. * Multiplies two quaternions
  4686. * @param q1 defines the second operand
  4687. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4688. */
  4689. Quaternion.prototype.multiply = function (q1) {
  4690. var result = new Quaternion(0, 0, 0, 1.0);
  4691. this.multiplyToRef(q1, result);
  4692. return result;
  4693. };
  4694. /**
  4695. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4696. * @param q1 defines the second operand
  4697. * @param result defines the target quaternion
  4698. * @returns the current quaternion
  4699. */
  4700. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4701. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4702. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4703. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4704. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4705. result.copyFromFloats(x, y, z, w);
  4706. return this;
  4707. };
  4708. /**
  4709. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4710. * @param q1 defines the second operand
  4711. * @returns the currentupdated quaternion
  4712. */
  4713. Quaternion.prototype.multiplyInPlace = function (q1) {
  4714. this.multiplyToRef(q1, this);
  4715. return this;
  4716. };
  4717. /**
  4718. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4719. * @param ref defines the target quaternion
  4720. * @returns the current quaternion
  4721. */
  4722. Quaternion.prototype.conjugateToRef = function (ref) {
  4723. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4724. return this;
  4725. };
  4726. /**
  4727. * Conjugates in place (1-q) the current quaternion
  4728. * @returns the current updated quaternion
  4729. */
  4730. Quaternion.prototype.conjugateInPlace = function () {
  4731. this.x *= -1;
  4732. this.y *= -1;
  4733. this.z *= -1;
  4734. return this;
  4735. };
  4736. /**
  4737. * Conjugates in place (1-q) the current quaternion
  4738. * @returns a new quaternion
  4739. */
  4740. Quaternion.prototype.conjugate = function () {
  4741. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4742. return result;
  4743. };
  4744. /**
  4745. * Gets length of current quaternion
  4746. * @returns the quaternion length (float)
  4747. */
  4748. Quaternion.prototype.length = function () {
  4749. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4750. };
  4751. /**
  4752. * Normalize in place the current quaternion
  4753. * @returns the current updated quaternion
  4754. */
  4755. Quaternion.prototype.normalize = function () {
  4756. var length = 1.0 / this.length();
  4757. this.x *= length;
  4758. this.y *= length;
  4759. this.z *= length;
  4760. this.w *= length;
  4761. return this;
  4762. };
  4763. /**
  4764. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4765. * @param order is a reserved parameter and is ignore for now
  4766. * @returns a new Vector3 containing the Euler angles
  4767. */
  4768. Quaternion.prototype.toEulerAngles = function (order) {
  4769. if (order === void 0) { order = "YZX"; }
  4770. var result = Vector3.Zero();
  4771. this.toEulerAnglesToRef(result, order);
  4772. return result;
  4773. };
  4774. /**
  4775. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4776. * @param result defines the vector which will be filled with the Euler angles
  4777. * @param order is a reserved parameter and is ignore for now
  4778. * @returns the current unchanged quaternion
  4779. */
  4780. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4781. if (order === void 0) { order = "YZX"; }
  4782. var qz = this.z;
  4783. var qx = this.x;
  4784. var qy = this.y;
  4785. var qw = this.w;
  4786. var sqw = qw * qw;
  4787. var sqz = qz * qz;
  4788. var sqx = qx * qx;
  4789. var sqy = qy * qy;
  4790. var zAxisY = qy * qz - qx * qw;
  4791. var limit = .4999999;
  4792. if (zAxisY < -limit) {
  4793. result.y = 2 * Math.atan2(qy, qw);
  4794. result.x = Math.PI / 2;
  4795. result.z = 0;
  4796. }
  4797. else if (zAxisY > limit) {
  4798. result.y = 2 * Math.atan2(qy, qw);
  4799. result.x = -Math.PI / 2;
  4800. result.z = 0;
  4801. }
  4802. else {
  4803. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4804. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4805. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4806. }
  4807. return this;
  4808. };
  4809. /**
  4810. * Updates the given rotation matrix with the current quaternion values
  4811. * @param result defines the target matrix
  4812. * @returns the current unchanged quaternion
  4813. */
  4814. Quaternion.prototype.toRotationMatrix = function (result) {
  4815. var xx = this.x * this.x;
  4816. var yy = this.y * this.y;
  4817. var zz = this.z * this.z;
  4818. var xy = this.x * this.y;
  4819. var zw = this.z * this.w;
  4820. var zx = this.z * this.x;
  4821. var yw = this.y * this.w;
  4822. var yz = this.y * this.z;
  4823. var xw = this.x * this.w;
  4824. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4825. result.m[1] = 2.0 * (xy + zw);
  4826. result.m[2] = 2.0 * (zx - yw);
  4827. result.m[3] = 0;
  4828. result.m[4] = 2.0 * (xy - zw);
  4829. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4830. result.m[6] = 2.0 * (yz + xw);
  4831. result.m[7] = 0;
  4832. result.m[8] = 2.0 * (zx + yw);
  4833. result.m[9] = 2.0 * (yz - xw);
  4834. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4835. result.m[11] = 0;
  4836. result.m[12] = 0;
  4837. result.m[13] = 0;
  4838. result.m[14] = 0;
  4839. result.m[15] = 1.0;
  4840. result._markAsUpdated();
  4841. return this;
  4842. };
  4843. /**
  4844. * Updates the current quaternion from the given rotation matrix values
  4845. * @param matrix defines the source matrix
  4846. * @returns the current updated quaternion
  4847. */
  4848. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4849. Quaternion.FromRotationMatrixToRef(matrix, this);
  4850. return this;
  4851. };
  4852. // Statics
  4853. /**
  4854. * Creates a new quaternion from a rotation matrix
  4855. * @param matrix defines the source matrix
  4856. * @returns a new quaternion created from the given rotation matrix values
  4857. */
  4858. Quaternion.FromRotationMatrix = function (matrix) {
  4859. var result = new Quaternion();
  4860. Quaternion.FromRotationMatrixToRef(matrix, result);
  4861. return result;
  4862. };
  4863. /**
  4864. * Updates the given quaternion with the given rotation matrix values
  4865. * @param matrix defines the source matrix
  4866. * @param result defines the target quaternion
  4867. */
  4868. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4869. var data = matrix.m;
  4870. var m11 = data[0], m12 = data[4], m13 = data[8];
  4871. var m21 = data[1], m22 = data[5], m23 = data[9];
  4872. var m31 = data[2], m32 = data[6], m33 = data[10];
  4873. var trace = m11 + m22 + m33;
  4874. var s;
  4875. if (trace > 0) {
  4876. s = 0.5 / Math.sqrt(trace + 1.0);
  4877. result.w = 0.25 / s;
  4878. result.x = (m32 - m23) * s;
  4879. result.y = (m13 - m31) * s;
  4880. result.z = (m21 - m12) * s;
  4881. }
  4882. else if (m11 > m22 && m11 > m33) {
  4883. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4884. result.w = (m32 - m23) / s;
  4885. result.x = 0.25 * s;
  4886. result.y = (m12 + m21) / s;
  4887. result.z = (m13 + m31) / s;
  4888. }
  4889. else if (m22 > m33) {
  4890. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4891. result.w = (m13 - m31) / s;
  4892. result.x = (m12 + m21) / s;
  4893. result.y = 0.25 * s;
  4894. result.z = (m23 + m32) / s;
  4895. }
  4896. else {
  4897. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4898. result.w = (m21 - m12) / s;
  4899. result.x = (m13 + m31) / s;
  4900. result.y = (m23 + m32) / s;
  4901. result.z = 0.25 * s;
  4902. }
  4903. };
  4904. /**
  4905. * Returns the dot product (float) between the quaternions "left" and "right"
  4906. * @param left defines the left operand
  4907. * @param right defines the right operand
  4908. * @returns the dot product
  4909. */
  4910. Quaternion.Dot = function (left, right) {
  4911. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4912. };
  4913. /**
  4914. * Checks if the two quaternions are close to each other
  4915. * @param quat0 defines the first quaternion to check
  4916. * @param quat1 defines the second quaternion to check
  4917. * @returns true if the two quaternions are close to each other
  4918. */
  4919. Quaternion.AreClose = function (quat0, quat1) {
  4920. var dot = Quaternion.Dot(quat0, quat1);
  4921. return dot >= 0;
  4922. };
  4923. /**
  4924. * Creates an empty quaternion
  4925. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4926. */
  4927. Quaternion.Zero = function () {
  4928. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4929. };
  4930. /**
  4931. * Inverse a given quaternion
  4932. * @param q defines the source quaternion
  4933. * @returns a new quaternion as the inverted current quaternion
  4934. */
  4935. Quaternion.Inverse = function (q) {
  4936. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4937. };
  4938. /**
  4939. * Creates an identity quaternion
  4940. * @returns the identity quaternion
  4941. */
  4942. Quaternion.Identity = function () {
  4943. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4944. };
  4945. /**
  4946. * Gets a boolean indicating if the given quaternion is identity
  4947. * @param quaternion defines the quaternion to check
  4948. * @returns true if the quaternion is identity
  4949. */
  4950. Quaternion.IsIdentity = function (quaternion) {
  4951. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4952. };
  4953. /**
  4954. * Creates a quaternion from a rotation around an axis
  4955. * @param axis defines the axis to use
  4956. * @param angle defines the angle to use
  4957. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4958. */
  4959. Quaternion.RotationAxis = function (axis, angle) {
  4960. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4961. };
  4962. /**
  4963. * Creates a rotation around an axis and stores it into the given quaternion
  4964. * @param axis defines the axis to use
  4965. * @param angle defines the angle to use
  4966. * @param result defines the target quaternion
  4967. * @returns the target quaternion
  4968. */
  4969. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4970. var sin = Math.sin(angle / 2);
  4971. axis.normalize();
  4972. result.w = Math.cos(angle / 2);
  4973. result.x = axis.x * sin;
  4974. result.y = axis.y * sin;
  4975. result.z = axis.z * sin;
  4976. return result;
  4977. };
  4978. /**
  4979. * Creates a new quaternion from data stored into an array
  4980. * @param array defines the data source
  4981. * @param offset defines the offset in the source array where the data starts
  4982. * @returns a new quaternion
  4983. */
  4984. Quaternion.FromArray = function (array, offset) {
  4985. if (!offset) {
  4986. offset = 0;
  4987. }
  4988. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4989. };
  4990. /**
  4991. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4992. * @param yaw defines the rotation around Y axis
  4993. * @param pitch defines the rotation around X axis
  4994. * @param roll defines the rotation around Z axis
  4995. * @returns the new quaternion
  4996. */
  4997. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4998. var q = new Quaternion();
  4999. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  5000. return q;
  5001. };
  5002. /**
  5003. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  5004. * @param yaw defines the rotation around Y axis
  5005. * @param pitch defines the rotation around X axis
  5006. * @param roll defines the rotation around Z axis
  5007. * @param result defines the target quaternion
  5008. */
  5009. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5010. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  5011. var halfRoll = roll * 0.5;
  5012. var halfPitch = pitch * 0.5;
  5013. var halfYaw = yaw * 0.5;
  5014. var sinRoll = Math.sin(halfRoll);
  5015. var cosRoll = Math.cos(halfRoll);
  5016. var sinPitch = Math.sin(halfPitch);
  5017. var cosPitch = Math.cos(halfPitch);
  5018. var sinYaw = Math.sin(halfYaw);
  5019. var cosYaw = Math.cos(halfYaw);
  5020. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  5021. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  5022. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  5023. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  5024. };
  5025. /**
  5026. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  5027. * @param alpha defines the rotation around first axis
  5028. * @param beta defines the rotation around second axis
  5029. * @param gamma defines the rotation around third axis
  5030. * @returns the new quaternion
  5031. */
  5032. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  5033. var result = new Quaternion();
  5034. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5035. return result;
  5036. };
  5037. /**
  5038. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5039. * @param alpha defines the rotation around first axis
  5040. * @param beta defines the rotation around second axis
  5041. * @param gamma defines the rotation around third axis
  5042. * @param result defines the target quaternion
  5043. */
  5044. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5045. // Produces a quaternion from Euler angles in the z-x-z orientation
  5046. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5047. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5048. var halfBeta = beta * 0.5;
  5049. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5050. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5051. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5052. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5053. };
  5054. /**
  5055. * 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)
  5056. * @param axis1 defines the first axis
  5057. * @param axis2 defines the second axis
  5058. * @param axis3 defines the third axis
  5059. * @returns the new quaternion
  5060. */
  5061. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5062. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5063. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5064. return quat;
  5065. };
  5066. /**
  5067. * 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
  5068. * @param axis1 defines the first axis
  5069. * @param axis2 defines the second axis
  5070. * @param axis3 defines the third axis
  5071. * @param ref defines the target quaternion
  5072. */
  5073. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5074. var rotMat = MathTmp.Matrix[0];
  5075. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5076. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5077. };
  5078. /**
  5079. * Interpolates between two quaternions
  5080. * @param left defines first quaternion
  5081. * @param right defines second quaternion
  5082. * @param amount defines the gradient to use
  5083. * @returns the new interpolated quaternion
  5084. */
  5085. Quaternion.Slerp = function (left, right, amount) {
  5086. var result = Quaternion.Identity();
  5087. Quaternion.SlerpToRef(left, right, amount, result);
  5088. return result;
  5089. };
  5090. /**
  5091. * Interpolates between two quaternions and stores it into a target quaternion
  5092. * @param left defines first quaternion
  5093. * @param right defines second quaternion
  5094. * @param amount defines the gradient to use
  5095. * @param result defines the target quaternion
  5096. */
  5097. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5098. var num2;
  5099. var num3;
  5100. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5101. var flag = false;
  5102. if (num4 < 0) {
  5103. flag = true;
  5104. num4 = -num4;
  5105. }
  5106. if (num4 > 0.999999) {
  5107. num3 = 1 - amount;
  5108. num2 = flag ? -amount : amount;
  5109. }
  5110. else {
  5111. var num5 = Math.acos(num4);
  5112. var num6 = (1.0 / Math.sin(num5));
  5113. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5114. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5115. }
  5116. result.x = (num3 * left.x) + (num2 * right.x);
  5117. result.y = (num3 * left.y) + (num2 * right.y);
  5118. result.z = (num3 * left.z) + (num2 * right.z);
  5119. result.w = (num3 * left.w) + (num2 * right.w);
  5120. };
  5121. /**
  5122. * Interpolate between two quaternions using Hermite interpolation
  5123. * @param value1 defines first quaternion
  5124. * @param tangent1 defines the incoming tangent
  5125. * @param value2 defines second quaternion
  5126. * @param tangent2 defines the outgoing tangent
  5127. * @param amount defines the target quaternion
  5128. * @returns the new interpolated quaternion
  5129. */
  5130. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5131. var squared = amount * amount;
  5132. var cubed = amount * squared;
  5133. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5134. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5135. var part3 = (cubed - (2.0 * squared)) + amount;
  5136. var part4 = cubed - squared;
  5137. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5138. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5139. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5140. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5141. return new Quaternion(x, y, z, w);
  5142. };
  5143. return Quaternion;
  5144. }());
  5145. BABYLON.Quaternion = Quaternion;
  5146. /**
  5147. * Class used to store matrix data (4x4)
  5148. */
  5149. var Matrix = /** @class */ (function () {
  5150. /**
  5151. * Creates an empty matrix (filled with zeros)
  5152. */
  5153. function Matrix() {
  5154. this._isIdentity = false;
  5155. this._isIdentityDirty = true;
  5156. /**
  5157. * Gets or sets the internal data of the matrix
  5158. */
  5159. this.m = new Float32Array(16);
  5160. this._markAsUpdated();
  5161. }
  5162. /** @hidden */
  5163. Matrix.prototype._markAsUpdated = function () {
  5164. this.updateFlag = Matrix._updateFlagSeed++;
  5165. this._isIdentityDirty = true;
  5166. };
  5167. // Properties
  5168. /**
  5169. * Check if the current matrix is indentity
  5170. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5171. * @returns true is the matrix is the identity matrix
  5172. */
  5173. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5174. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5175. if (this._isIdentityDirty) {
  5176. this._isIdentityDirty = false;
  5177. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5178. this._isIdentity = false;
  5179. }
  5180. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5181. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5182. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5183. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5184. this._isIdentity = false;
  5185. }
  5186. else {
  5187. this._isIdentity = true;
  5188. }
  5189. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5190. this._isIdentity = false;
  5191. }
  5192. }
  5193. return this._isIdentity;
  5194. };
  5195. /**
  5196. * Gets the determinant of the matrix
  5197. * @returns the matrix determinant
  5198. */
  5199. Matrix.prototype.determinant = function () {
  5200. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5201. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5202. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5203. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5204. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5205. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5206. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5207. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5208. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5209. };
  5210. // Methods
  5211. /**
  5212. * Returns the matrix as a Float32Array
  5213. * @returns the matrix underlying array
  5214. */
  5215. Matrix.prototype.toArray = function () {
  5216. return this.m;
  5217. };
  5218. /**
  5219. * Returns the matrix as a Float32Array
  5220. * @returns the matrix underlying array.
  5221. */
  5222. Matrix.prototype.asArray = function () {
  5223. return this.toArray();
  5224. };
  5225. /**
  5226. * Inverts the current matrix in place
  5227. * @returns the current inverted matrix
  5228. */
  5229. Matrix.prototype.invert = function () {
  5230. this.invertToRef(this);
  5231. return this;
  5232. };
  5233. /**
  5234. * Sets all the matrix elements to zero
  5235. * @returns the current matrix
  5236. */
  5237. Matrix.prototype.reset = function () {
  5238. for (var index = 0; index < 16; index++) {
  5239. this.m[index] = 0.0;
  5240. }
  5241. this._markAsUpdated();
  5242. return this;
  5243. };
  5244. /**
  5245. * Adds the current matrix with a second one
  5246. * @param other defines the matrix to add
  5247. * @returns a new matrix as the addition of the current matrix and the given one
  5248. */
  5249. Matrix.prototype.add = function (other) {
  5250. var result = new Matrix();
  5251. this.addToRef(other, result);
  5252. return result;
  5253. };
  5254. /**
  5255. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5256. * @param other defines the matrix to add
  5257. * @param result defines the target matrix
  5258. * @returns the current matrix
  5259. */
  5260. Matrix.prototype.addToRef = function (other, result) {
  5261. for (var index = 0; index < 16; index++) {
  5262. result.m[index] = this.m[index] + other.m[index];
  5263. }
  5264. result._markAsUpdated();
  5265. return this;
  5266. };
  5267. /**
  5268. * Adds in place the given matrix to the current matrix
  5269. * @param other defines the second operand
  5270. * @returns the current updated matrix
  5271. */
  5272. Matrix.prototype.addToSelf = function (other) {
  5273. for (var index = 0; index < 16; index++) {
  5274. this.m[index] += other.m[index];
  5275. }
  5276. this._markAsUpdated();
  5277. return this;
  5278. };
  5279. /**
  5280. * Sets the given matrix to the current inverted Matrix
  5281. * @param other defines the target matrix
  5282. * @returns the unmodified current matrix
  5283. */
  5284. Matrix.prototype.invertToRef = function (other) {
  5285. var l1 = this.m[0];
  5286. var l2 = this.m[1];
  5287. var l3 = this.m[2];
  5288. var l4 = this.m[3];
  5289. var l5 = this.m[4];
  5290. var l6 = this.m[5];
  5291. var l7 = this.m[6];
  5292. var l8 = this.m[7];
  5293. var l9 = this.m[8];
  5294. var l10 = this.m[9];
  5295. var l11 = this.m[10];
  5296. var l12 = this.m[11];
  5297. var l13 = this.m[12];
  5298. var l14 = this.m[13];
  5299. var l15 = this.m[14];
  5300. var l16 = this.m[15];
  5301. var l17 = (l11 * l16) - (l12 * l15);
  5302. var l18 = (l10 * l16) - (l12 * l14);
  5303. var l19 = (l10 * l15) - (l11 * l14);
  5304. var l20 = (l9 * l16) - (l12 * l13);
  5305. var l21 = (l9 * l15) - (l11 * l13);
  5306. var l22 = (l9 * l14) - (l10 * l13);
  5307. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5308. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5309. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5310. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5311. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5312. var l28 = (l7 * l16) - (l8 * l15);
  5313. var l29 = (l6 * l16) - (l8 * l14);
  5314. var l30 = (l6 * l15) - (l7 * l14);
  5315. var l31 = (l5 * l16) - (l8 * l13);
  5316. var l32 = (l5 * l15) - (l7 * l13);
  5317. var l33 = (l5 * l14) - (l6 * l13);
  5318. var l34 = (l7 * l12) - (l8 * l11);
  5319. var l35 = (l6 * l12) - (l8 * l10);
  5320. var l36 = (l6 * l11) - (l7 * l10);
  5321. var l37 = (l5 * l12) - (l8 * l9);
  5322. var l38 = (l5 * l11) - (l7 * l9);
  5323. var l39 = (l5 * l10) - (l6 * l9);
  5324. other.m[0] = l23 * l27;
  5325. other.m[4] = l24 * l27;
  5326. other.m[8] = l25 * l27;
  5327. other.m[12] = l26 * l27;
  5328. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5329. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5330. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5331. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5332. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5333. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5334. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5335. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5336. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5337. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5338. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5339. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5340. other._markAsUpdated();
  5341. return this;
  5342. };
  5343. /**
  5344. * Inserts the translation vector (using 3 floats) in the current matrix
  5345. * @param x defines the 1st component of the translation
  5346. * @param y defines the 2nd component of the translation
  5347. * @param z defines the 3rd component of the translation
  5348. * @returns the current updated matrix
  5349. */
  5350. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5351. this.m[12] = x;
  5352. this.m[13] = y;
  5353. this.m[14] = z;
  5354. this._markAsUpdated();
  5355. return this;
  5356. };
  5357. /**
  5358. * Inserts the translation vector in the current matrix
  5359. * @param vector3 defines the translation to insert
  5360. * @returns the current updated matrix
  5361. */
  5362. Matrix.prototype.setTranslation = function (vector3) {
  5363. this.m[12] = vector3.x;
  5364. this.m[13] = vector3.y;
  5365. this.m[14] = vector3.z;
  5366. this._markAsUpdated();
  5367. return this;
  5368. };
  5369. /**
  5370. * Gets the translation value of the current matrix
  5371. * @returns a new Vector3 as the extracted translation from the matrix
  5372. */
  5373. Matrix.prototype.getTranslation = function () {
  5374. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5375. };
  5376. /**
  5377. * Fill a Vector3 with the extracted translation from the matrix
  5378. * @param result defines the Vector3 where to store the translation
  5379. * @returns the current matrix
  5380. */
  5381. Matrix.prototype.getTranslationToRef = function (result) {
  5382. result.x = this.m[12];
  5383. result.y = this.m[13];
  5384. result.z = this.m[14];
  5385. return this;
  5386. };
  5387. /**
  5388. * Remove rotation and scaling part from the matrix
  5389. * @returns the updated matrix
  5390. */
  5391. Matrix.prototype.removeRotationAndScaling = function () {
  5392. this.setRowFromFloats(0, 1, 0, 0, 0);
  5393. this.setRowFromFloats(1, 0, 1, 0, 0);
  5394. this.setRowFromFloats(2, 0, 0, 1, 0);
  5395. return this;
  5396. };
  5397. /**
  5398. * Multiply two matrices
  5399. * @param other defines the second operand
  5400. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5401. */
  5402. Matrix.prototype.multiply = function (other) {
  5403. var result = new Matrix();
  5404. this.multiplyToRef(other, result);
  5405. return result;
  5406. };
  5407. /**
  5408. * Copy the current matrix from the given one
  5409. * @param other defines the source matrix
  5410. * @returns the current updated matrix
  5411. */
  5412. Matrix.prototype.copyFrom = function (other) {
  5413. for (var index = 0; index < 16; index++) {
  5414. this.m[index] = other.m[index];
  5415. }
  5416. this._markAsUpdated();
  5417. return this;
  5418. };
  5419. /**
  5420. * Populates the given array from the starting index with the current matrix values
  5421. * @param array defines the target array
  5422. * @param offset defines the offset in the target array where to start storing values
  5423. * @returns the current matrix
  5424. */
  5425. Matrix.prototype.copyToArray = function (array, offset) {
  5426. if (offset === void 0) { offset = 0; }
  5427. for (var index = 0; index < 16; index++) {
  5428. array[offset + index] = this.m[index];
  5429. }
  5430. return this;
  5431. };
  5432. /**
  5433. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5434. * @param other defines the second operand
  5435. * @param result defines the matrix where to store the multiplication
  5436. * @returns the current matrix
  5437. */
  5438. Matrix.prototype.multiplyToRef = function (other, result) {
  5439. this.multiplyToArray(other, result.m, 0);
  5440. result._markAsUpdated();
  5441. return this;
  5442. };
  5443. /**
  5444. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5445. * @param other defines the second operand
  5446. * @param result defines the array where to store the multiplication
  5447. * @param offset defines the offset in the target array where to start storing values
  5448. * @returns the current matrix
  5449. */
  5450. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5451. var tm0 = this.m[0];
  5452. var tm1 = this.m[1];
  5453. var tm2 = this.m[2];
  5454. var tm3 = this.m[3];
  5455. var tm4 = this.m[4];
  5456. var tm5 = this.m[5];
  5457. var tm6 = this.m[6];
  5458. var tm7 = this.m[7];
  5459. var tm8 = this.m[8];
  5460. var tm9 = this.m[9];
  5461. var tm10 = this.m[10];
  5462. var tm11 = this.m[11];
  5463. var tm12 = this.m[12];
  5464. var tm13 = this.m[13];
  5465. var tm14 = this.m[14];
  5466. var tm15 = this.m[15];
  5467. var om0 = other.m[0];
  5468. var om1 = other.m[1];
  5469. var om2 = other.m[2];
  5470. var om3 = other.m[3];
  5471. var om4 = other.m[4];
  5472. var om5 = other.m[5];
  5473. var om6 = other.m[6];
  5474. var om7 = other.m[7];
  5475. var om8 = other.m[8];
  5476. var om9 = other.m[9];
  5477. var om10 = other.m[10];
  5478. var om11 = other.m[11];
  5479. var om12 = other.m[12];
  5480. var om13 = other.m[13];
  5481. var om14 = other.m[14];
  5482. var om15 = other.m[15];
  5483. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5484. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5485. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5486. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5487. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5488. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5489. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5490. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5491. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5492. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5493. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5494. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5495. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5496. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5497. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5498. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5499. return this;
  5500. };
  5501. /**
  5502. * Check equality between this matrix and a second one
  5503. * @param value defines the second matrix to compare
  5504. * @returns true is the current matrix and the given one values are strictly equal
  5505. */
  5506. Matrix.prototype.equals = function (value) {
  5507. return value &&
  5508. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5509. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5510. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5511. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5512. };
  5513. /**
  5514. * Clone the current matrix
  5515. * @returns a new matrix from the current matrix
  5516. */
  5517. Matrix.prototype.clone = function () {
  5518. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5519. };
  5520. /**
  5521. * Returns the name of the current matrix class
  5522. * @returns the string "Matrix"
  5523. */
  5524. Matrix.prototype.getClassName = function () {
  5525. return "Matrix";
  5526. };
  5527. /**
  5528. * Gets the hash code of the current matrix
  5529. * @returns the hash code
  5530. */
  5531. Matrix.prototype.getHashCode = function () {
  5532. var hash = this.m[0] || 0;
  5533. for (var i = 1; i < 16; i++) {
  5534. hash = (hash * 397) ^ (this.m[i] || 0);
  5535. }
  5536. return hash;
  5537. };
  5538. /**
  5539. * Decomposes the current Matrix into a translation, rotation and scaling components
  5540. * @param scale defines the scale vector3 given as a reference to update
  5541. * @param rotation defines the rotation quaternion given as a reference to update
  5542. * @param translation defines the translation vector3 given as a reference to update
  5543. * @returns true if operation was successful
  5544. */
  5545. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5546. if (translation) {
  5547. translation.x = this.m[12];
  5548. translation.y = this.m[13];
  5549. translation.z = this.m[14];
  5550. }
  5551. scale = scale || MathTmp.Vector3[0];
  5552. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5553. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5554. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5555. if (this.determinant() <= 0) {
  5556. scale.y *= -1;
  5557. }
  5558. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5559. if (rotation) {
  5560. rotation.x = 0;
  5561. rotation.y = 0;
  5562. rotation.z = 0;
  5563. rotation.w = 1;
  5564. }
  5565. return false;
  5566. }
  5567. if (rotation) {
  5568. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5569. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5570. }
  5571. return true;
  5572. };
  5573. /**
  5574. * Gets specific row of the matrix
  5575. * @param index defines the number of the row to get
  5576. * @returns the index-th row of the current matrix as a new Vector4
  5577. */
  5578. Matrix.prototype.getRow = function (index) {
  5579. if (index < 0 || index > 3) {
  5580. return null;
  5581. }
  5582. var i = index * 4;
  5583. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5584. };
  5585. /**
  5586. * Sets the index-th row of the current matrix to the vector4 values
  5587. * @param index defines the number of the row to set
  5588. * @param row defines the target vector4
  5589. * @returns the updated current matrix
  5590. */
  5591. Matrix.prototype.setRow = function (index, row) {
  5592. if (index < 0 || index > 3) {
  5593. return this;
  5594. }
  5595. var i = index * 4;
  5596. this.m[i + 0] = row.x;
  5597. this.m[i + 1] = row.y;
  5598. this.m[i + 2] = row.z;
  5599. this.m[i + 3] = row.w;
  5600. this._markAsUpdated();
  5601. return this;
  5602. };
  5603. /**
  5604. * Compute the transpose of the matrix
  5605. * @returns the new transposed matrix
  5606. */
  5607. Matrix.prototype.transpose = function () {
  5608. return Matrix.Transpose(this);
  5609. };
  5610. /**
  5611. * Compute the transpose of the matrix and store it in a given matrix
  5612. * @param result defines the target matrix
  5613. * @returns the current matrix
  5614. */
  5615. Matrix.prototype.transposeToRef = function (result) {
  5616. Matrix.TransposeToRef(this, result);
  5617. return this;
  5618. };
  5619. /**
  5620. * Sets the index-th row of the current matrix with the given 4 x float values
  5621. * @param index defines the row index
  5622. * @param x defines the x component to set
  5623. * @param y defines the y component to set
  5624. * @param z defines the z component to set
  5625. * @param w defines the w component to set
  5626. * @returns the updated current matrix
  5627. */
  5628. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5629. if (index < 0 || index > 3) {
  5630. return this;
  5631. }
  5632. var i = index * 4;
  5633. this.m[i + 0] = x;
  5634. this.m[i + 1] = y;
  5635. this.m[i + 2] = z;
  5636. this.m[i + 3] = w;
  5637. this._markAsUpdated();
  5638. return this;
  5639. };
  5640. /**
  5641. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5642. * @param scale defines the scale factor
  5643. * @returns a new matrix
  5644. */
  5645. Matrix.prototype.scale = function (scale) {
  5646. var result = new Matrix();
  5647. this.scaleToRef(scale, result);
  5648. return result;
  5649. };
  5650. /**
  5651. * Scale the current matrix values by a factor to a given result matrix
  5652. * @param scale defines the scale factor
  5653. * @param result defines the matrix to store the result
  5654. * @returns the current matrix
  5655. */
  5656. Matrix.prototype.scaleToRef = function (scale, result) {
  5657. for (var index = 0; index < 16; index++) {
  5658. result.m[index] = this.m[index] * scale;
  5659. }
  5660. result._markAsUpdated();
  5661. return this;
  5662. };
  5663. /**
  5664. * Scale the current matrix values by a factor and add the result to a given matrix
  5665. * @param scale defines the scale factor
  5666. * @param result defines the Matrix to store the result
  5667. * @returns the current matrix
  5668. */
  5669. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5670. for (var index = 0; index < 16; index++) {
  5671. result.m[index] += this.m[index] * scale;
  5672. }
  5673. result._markAsUpdated();
  5674. return this;
  5675. };
  5676. /**
  5677. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5678. * @param ref matrix to store the result
  5679. */
  5680. Matrix.prototype.toNormalMatrix = function (ref) {
  5681. this.invertToRef(ref);
  5682. ref.transpose();
  5683. var m = ref.m;
  5684. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5685. };
  5686. /**
  5687. * Gets only rotation part of the current matrix
  5688. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5689. */
  5690. Matrix.prototype.getRotationMatrix = function () {
  5691. var result = Matrix.Identity();
  5692. this.getRotationMatrixToRef(result);
  5693. return result;
  5694. };
  5695. /**
  5696. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5697. * @param result defines the target matrix to store data to
  5698. * @returns the current matrix
  5699. */
  5700. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5701. var m = this.m;
  5702. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5703. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5704. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5705. if (this.determinant() <= 0) {
  5706. sy *= -1;
  5707. }
  5708. if (sx === 0 || sy === 0 || sz === 0) {
  5709. Matrix.IdentityToRef(result);
  5710. }
  5711. else {
  5712. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5713. }
  5714. return this;
  5715. };
  5716. // Statics
  5717. /**
  5718. * Creates a matrix from an array
  5719. * @param array defines the source array
  5720. * @param offset defines an offset in the source array
  5721. * @returns a new Matrix set from the starting index of the given array
  5722. */
  5723. Matrix.FromArray = function (array, offset) {
  5724. var result = new Matrix();
  5725. if (!offset) {
  5726. offset = 0;
  5727. }
  5728. Matrix.FromArrayToRef(array, offset, result);
  5729. return result;
  5730. };
  5731. /**
  5732. * Copy the content of an array into a given matrix
  5733. * @param array defines the source array
  5734. * @param offset defines an offset in the source array
  5735. * @param result defines the target matrix
  5736. */
  5737. Matrix.FromArrayToRef = function (array, offset, result) {
  5738. for (var index = 0; index < 16; index++) {
  5739. result.m[index] = array[index + offset];
  5740. }
  5741. result._markAsUpdated();
  5742. };
  5743. /**
  5744. * Stores an array into a matrix after having multiplied each component by a given factor
  5745. * @param array defines the source array
  5746. * @param offset defines the offset in the source array
  5747. * @param scale defines the scaling factor
  5748. * @param result defines the target matrix
  5749. */
  5750. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5751. for (var index = 0; index < 16; index++) {
  5752. result.m[index] = array[index + offset] * scale;
  5753. }
  5754. result._markAsUpdated();
  5755. };
  5756. /**
  5757. * Stores a list of values (16) inside a given matrix
  5758. * @param initialM11 defines 1st value of 1st row
  5759. * @param initialM12 defines 2nd value of 1st row
  5760. * @param initialM13 defines 3rd value of 1st row
  5761. * @param initialM14 defines 4th value of 1st row
  5762. * @param initialM21 defines 1st value of 2nd row
  5763. * @param initialM22 defines 2nd value of 2nd row
  5764. * @param initialM23 defines 3rd value of 2nd row
  5765. * @param initialM24 defines 4th value of 2nd row
  5766. * @param initialM31 defines 1st value of 3rd row
  5767. * @param initialM32 defines 2nd value of 3rd row
  5768. * @param initialM33 defines 3rd value of 3rd row
  5769. * @param initialM34 defines 4th value of 3rd row
  5770. * @param initialM41 defines 1st value of 4th row
  5771. * @param initialM42 defines 2nd value of 4th row
  5772. * @param initialM43 defines 3rd value of 4th row
  5773. * @param initialM44 defines 4th value of 4th row
  5774. * @param result defines the target matrix
  5775. */
  5776. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5777. result.m[0] = initialM11;
  5778. result.m[1] = initialM12;
  5779. result.m[2] = initialM13;
  5780. result.m[3] = initialM14;
  5781. result.m[4] = initialM21;
  5782. result.m[5] = initialM22;
  5783. result.m[6] = initialM23;
  5784. result.m[7] = initialM24;
  5785. result.m[8] = initialM31;
  5786. result.m[9] = initialM32;
  5787. result.m[10] = initialM33;
  5788. result.m[11] = initialM34;
  5789. result.m[12] = initialM41;
  5790. result.m[13] = initialM42;
  5791. result.m[14] = initialM43;
  5792. result.m[15] = initialM44;
  5793. result._markAsUpdated();
  5794. };
  5795. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5796. /**
  5797. * Gets an identity matrix that must not be updated
  5798. */
  5799. get: function () {
  5800. return Matrix._identityReadOnly;
  5801. },
  5802. enumerable: true,
  5803. configurable: true
  5804. });
  5805. /**
  5806. * Creates new matrix from a list of values (16)
  5807. * @param initialM11 defines 1st value of 1st row
  5808. * @param initialM12 defines 2nd value of 1st row
  5809. * @param initialM13 defines 3rd value of 1st row
  5810. * @param initialM14 defines 4th value of 1st row
  5811. * @param initialM21 defines 1st value of 2nd row
  5812. * @param initialM22 defines 2nd value of 2nd row
  5813. * @param initialM23 defines 3rd value of 2nd row
  5814. * @param initialM24 defines 4th value of 2nd row
  5815. * @param initialM31 defines 1st value of 3rd row
  5816. * @param initialM32 defines 2nd value of 3rd row
  5817. * @param initialM33 defines 3rd value of 3rd row
  5818. * @param initialM34 defines 4th value of 3rd row
  5819. * @param initialM41 defines 1st value of 4th row
  5820. * @param initialM42 defines 2nd value of 4th row
  5821. * @param initialM43 defines 3rd value of 4th row
  5822. * @param initialM44 defines 4th value of 4th row
  5823. * @returns the new matrix
  5824. */
  5825. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5826. var result = new Matrix();
  5827. result.m[0] = initialM11;
  5828. result.m[1] = initialM12;
  5829. result.m[2] = initialM13;
  5830. result.m[3] = initialM14;
  5831. result.m[4] = initialM21;
  5832. result.m[5] = initialM22;
  5833. result.m[6] = initialM23;
  5834. result.m[7] = initialM24;
  5835. result.m[8] = initialM31;
  5836. result.m[9] = initialM32;
  5837. result.m[10] = initialM33;
  5838. result.m[11] = initialM34;
  5839. result.m[12] = initialM41;
  5840. result.m[13] = initialM42;
  5841. result.m[14] = initialM43;
  5842. result.m[15] = initialM44;
  5843. return result;
  5844. };
  5845. /**
  5846. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5847. * @param scale defines the scale vector3
  5848. * @param rotation defines the rotation quaternion
  5849. * @param translation defines the translation vector3
  5850. * @returns a new matrix
  5851. */
  5852. Matrix.Compose = function (scale, rotation, translation) {
  5853. var result = Matrix.Identity();
  5854. Matrix.ComposeToRef(scale, rotation, translation, result);
  5855. return result;
  5856. };
  5857. /**
  5858. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5859. * @param scale defines the scale vector3
  5860. * @param rotation defines the rotation quaternion
  5861. * @param translation defines the translation vector3
  5862. * @param result defines the target matrix
  5863. */
  5864. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5865. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5866. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5867. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5868. result.setTranslation(translation);
  5869. };
  5870. /**
  5871. * Creates a new identity matrix
  5872. * @returns a new identity matrix
  5873. */
  5874. Matrix.Identity = function () {
  5875. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5876. };
  5877. /**
  5878. * Creates a new identity matrix and stores the result in a given matrix
  5879. * @param result defines the target matrix
  5880. */
  5881. Matrix.IdentityToRef = function (result) {
  5882. 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);
  5883. };
  5884. /**
  5885. * Creates a new zero matrix
  5886. * @returns a new zero matrix
  5887. */
  5888. Matrix.Zero = function () {
  5889. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5890. };
  5891. /**
  5892. * Creates a new rotation matrix for "angle" radians around the X axis
  5893. * @param angle defines the angle (in radians) to use
  5894. * @return the new matrix
  5895. */
  5896. Matrix.RotationX = function (angle) {
  5897. var result = new Matrix();
  5898. Matrix.RotationXToRef(angle, result);
  5899. return result;
  5900. };
  5901. /**
  5902. * Creates a new matrix as the invert of a given matrix
  5903. * @param source defines the source matrix
  5904. * @returns the new matrix
  5905. */
  5906. Matrix.Invert = function (source) {
  5907. var result = new Matrix();
  5908. source.invertToRef(result);
  5909. return result;
  5910. };
  5911. /**
  5912. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5913. * @param angle defines the angle (in radians) to use
  5914. * @param result defines the target matrix
  5915. */
  5916. Matrix.RotationXToRef = function (angle, result) {
  5917. var s = Math.sin(angle);
  5918. var c = Math.cos(angle);
  5919. result.m[0] = 1.0;
  5920. result.m[15] = 1.0;
  5921. result.m[5] = c;
  5922. result.m[10] = c;
  5923. result.m[9] = -s;
  5924. result.m[6] = s;
  5925. result.m[1] = 0.0;
  5926. result.m[2] = 0.0;
  5927. result.m[3] = 0.0;
  5928. result.m[4] = 0.0;
  5929. result.m[7] = 0.0;
  5930. result.m[8] = 0.0;
  5931. result.m[11] = 0.0;
  5932. result.m[12] = 0.0;
  5933. result.m[13] = 0.0;
  5934. result.m[14] = 0.0;
  5935. result._markAsUpdated();
  5936. };
  5937. /**
  5938. * Creates a new rotation matrix for "angle" radians around the Y axis
  5939. * @param angle defines the angle (in radians) to use
  5940. * @return the new matrix
  5941. */
  5942. Matrix.RotationY = function (angle) {
  5943. var result = new Matrix();
  5944. Matrix.RotationYToRef(angle, result);
  5945. return result;
  5946. };
  5947. /**
  5948. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5949. * @param angle defines the angle (in radians) to use
  5950. * @param result defines the target matrix
  5951. */
  5952. Matrix.RotationYToRef = function (angle, result) {
  5953. var s = Math.sin(angle);
  5954. var c = Math.cos(angle);
  5955. result.m[5] = 1.0;
  5956. result.m[15] = 1.0;
  5957. result.m[0] = c;
  5958. result.m[2] = -s;
  5959. result.m[8] = s;
  5960. result.m[10] = c;
  5961. result.m[1] = 0.0;
  5962. result.m[3] = 0.0;
  5963. result.m[4] = 0.0;
  5964. result.m[6] = 0.0;
  5965. result.m[7] = 0.0;
  5966. result.m[9] = 0.0;
  5967. result.m[11] = 0.0;
  5968. result.m[12] = 0.0;
  5969. result.m[13] = 0.0;
  5970. result.m[14] = 0.0;
  5971. result._markAsUpdated();
  5972. };
  5973. /**
  5974. * Creates a new rotation matrix for "angle" radians around the Z axis
  5975. * @param angle defines the angle (in radians) to use
  5976. * @return the new matrix
  5977. */
  5978. Matrix.RotationZ = function (angle) {
  5979. var result = new Matrix();
  5980. Matrix.RotationZToRef(angle, result);
  5981. return result;
  5982. };
  5983. /**
  5984. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5985. * @param angle defines the angle (in radians) to use
  5986. * @param result defines the target matrix
  5987. */
  5988. Matrix.RotationZToRef = function (angle, result) {
  5989. var s = Math.sin(angle);
  5990. var c = Math.cos(angle);
  5991. result.m[10] = 1.0;
  5992. result.m[15] = 1.0;
  5993. result.m[0] = c;
  5994. result.m[1] = s;
  5995. result.m[4] = -s;
  5996. result.m[5] = c;
  5997. result.m[2] = 0.0;
  5998. result.m[3] = 0.0;
  5999. result.m[6] = 0.0;
  6000. result.m[7] = 0.0;
  6001. result.m[8] = 0.0;
  6002. result.m[9] = 0.0;
  6003. result.m[11] = 0.0;
  6004. result.m[12] = 0.0;
  6005. result.m[13] = 0.0;
  6006. result.m[14] = 0.0;
  6007. result._markAsUpdated();
  6008. };
  6009. /**
  6010. * Creates a new rotation matrix for "angle" radians around the given axis
  6011. * @param axis defines the axis to use
  6012. * @param angle defines the angle (in radians) to use
  6013. * @return the new matrix
  6014. */
  6015. Matrix.RotationAxis = function (axis, angle) {
  6016. var result = Matrix.Zero();
  6017. Matrix.RotationAxisToRef(axis, angle, result);
  6018. return result;
  6019. };
  6020. /**
  6021. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  6022. * @param axis defines the axis to use
  6023. * @param angle defines the angle (in radians) to use
  6024. * @param result defines the target matrix
  6025. */
  6026. Matrix.RotationAxisToRef = function (axis, angle, result) {
  6027. var s = Math.sin(-angle);
  6028. var c = Math.cos(-angle);
  6029. var c1 = 1 - c;
  6030. axis.normalize();
  6031. result.m[0] = (axis.x * axis.x) * c1 + c;
  6032. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  6033. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  6034. result.m[3] = 0.0;
  6035. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6036. result.m[5] = (axis.y * axis.y) * c1 + c;
  6037. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6038. result.m[7] = 0.0;
  6039. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6040. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6041. result.m[10] = (axis.z * axis.z) * c1 + c;
  6042. result.m[11] = 0.0;
  6043. result.m[15] = 1.0;
  6044. result._markAsUpdated();
  6045. };
  6046. /**
  6047. * Creates a rotation matrix
  6048. * @param yaw defines the yaw angle in radians (Y axis)
  6049. * @param pitch defines the pitch angle in radians (X axis)
  6050. * @param roll defines the roll angle in radians (X axis)
  6051. * @returns the new rotation matrix
  6052. */
  6053. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6054. var result = new Matrix();
  6055. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6056. return result;
  6057. };
  6058. /**
  6059. * Creates a rotation matrix and stores it in a given matrix
  6060. * @param yaw defines the yaw angle in radians (Y axis)
  6061. * @param pitch defines the pitch angle in radians (X axis)
  6062. * @param roll defines the roll angle in radians (X axis)
  6063. * @param result defines the target matrix
  6064. */
  6065. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6066. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6067. this._tempQuaternion.toRotationMatrix(result);
  6068. };
  6069. /**
  6070. * Creates a scaling matrix
  6071. * @param x defines the scale factor on X axis
  6072. * @param y defines the scale factor on Y axis
  6073. * @param z defines the scale factor on Z axis
  6074. * @returns the new matrix
  6075. */
  6076. Matrix.Scaling = function (x, y, z) {
  6077. var result = Matrix.Zero();
  6078. Matrix.ScalingToRef(x, y, z, result);
  6079. return result;
  6080. };
  6081. /**
  6082. * Creates a scaling matrix and stores it in a given matrix
  6083. * @param x defines the scale factor on X axis
  6084. * @param y defines the scale factor on Y axis
  6085. * @param z defines the scale factor on Z axis
  6086. * @param result defines the target matrix
  6087. */
  6088. Matrix.ScalingToRef = function (x, y, z, result) {
  6089. result.m[0] = x;
  6090. result.m[1] = 0.0;
  6091. result.m[2] = 0.0;
  6092. result.m[3] = 0.0;
  6093. result.m[4] = 0.0;
  6094. result.m[5] = y;
  6095. result.m[6] = 0.0;
  6096. result.m[7] = 0.0;
  6097. result.m[8] = 0.0;
  6098. result.m[9] = 0.0;
  6099. result.m[10] = z;
  6100. result.m[11] = 0.0;
  6101. result.m[12] = 0.0;
  6102. result.m[13] = 0.0;
  6103. result.m[14] = 0.0;
  6104. result.m[15] = 1.0;
  6105. result._markAsUpdated();
  6106. };
  6107. /**
  6108. * Creates a translation matrix
  6109. * @param x defines the translation on X axis
  6110. * @param y defines the translation on Y axis
  6111. * @param z defines the translationon Z axis
  6112. * @returns the new matrix
  6113. */
  6114. Matrix.Translation = function (x, y, z) {
  6115. var result = Matrix.Identity();
  6116. Matrix.TranslationToRef(x, y, z, result);
  6117. return result;
  6118. };
  6119. /**
  6120. * Creates a translation matrix and stores it in a given matrix
  6121. * @param x defines the translation on X axis
  6122. * @param y defines the translation on Y axis
  6123. * @param z defines the translationon Z axis
  6124. * @param result defines the target matrix
  6125. */
  6126. Matrix.TranslationToRef = function (x, y, z, result) {
  6127. 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);
  6128. };
  6129. /**
  6130. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6131. * @param startValue defines the start value
  6132. * @param endValue defines the end value
  6133. * @param gradient defines the gradient factor
  6134. * @returns the new matrix
  6135. */
  6136. Matrix.Lerp = function (startValue, endValue, gradient) {
  6137. var result = Matrix.Zero();
  6138. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6139. return result;
  6140. };
  6141. /**
  6142. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6143. * @param startValue defines the start value
  6144. * @param endValue defines the end value
  6145. * @param gradient defines the gradient factor
  6146. * @param result defines the Matrix object where to store data
  6147. */
  6148. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6149. for (var index = 0; index < 16; index++) {
  6150. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6151. }
  6152. result._markAsUpdated();
  6153. };
  6154. /**
  6155. * Builds a new matrix whose values are computed by:
  6156. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6157. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6158. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6159. * @param startValue defines the first matrix
  6160. * @param endValue defines the second matrix
  6161. * @param gradient defines the gradient between the two matrices
  6162. * @returns the new matrix
  6163. */
  6164. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6165. var result = Matrix.Zero();
  6166. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6167. return result;
  6168. };
  6169. /**
  6170. * Update a matrix to values which are computed by:
  6171. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6172. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6173. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6174. * @param startValue defines the first matrix
  6175. * @param endValue defines the second matrix
  6176. * @param gradient defines the gradient between the two matrices
  6177. * @param result defines the target matrix
  6178. */
  6179. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6180. var startScale = MathTmp.Vector3[0];
  6181. var startRotation = MathTmp.Quaternion[0];
  6182. var startTranslation = MathTmp.Vector3[1];
  6183. startValue.decompose(startScale, startRotation, startTranslation);
  6184. var endScale = MathTmp.Vector3[2];
  6185. var endRotation = MathTmp.Quaternion[1];
  6186. var endTranslation = MathTmp.Vector3[3];
  6187. endValue.decompose(endScale, endRotation, endTranslation);
  6188. var resultScale = MathTmp.Vector3[4];
  6189. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6190. var resultRotation = MathTmp.Quaternion[2];
  6191. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6192. var resultTranslation = MathTmp.Vector3[5];
  6193. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6194. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6195. };
  6196. /**
  6197. * 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"
  6198. * This function works in left handed mode
  6199. * @param eye defines the final position of the entity
  6200. * @param target defines where the entity should look at
  6201. * @param up defines the up vector for the entity
  6202. * @returns the new matrix
  6203. */
  6204. Matrix.LookAtLH = function (eye, target, up) {
  6205. var result = Matrix.Zero();
  6206. Matrix.LookAtLHToRef(eye, target, up, result);
  6207. return result;
  6208. };
  6209. /**
  6210. * 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".
  6211. * This function works in left handed mode
  6212. * @param eye defines the final position of the entity
  6213. * @param target defines where the entity should look at
  6214. * @param up defines the up vector for the entity
  6215. * @param result defines the target matrix
  6216. */
  6217. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6218. // Z axis
  6219. target.subtractToRef(eye, this._zAxis);
  6220. this._zAxis.normalize();
  6221. // X axis
  6222. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6223. if (this._xAxis.lengthSquared() === 0) {
  6224. this._xAxis.x = 1.0;
  6225. }
  6226. else {
  6227. this._xAxis.normalize();
  6228. }
  6229. // Y axis
  6230. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6231. this._yAxis.normalize();
  6232. // Eye angles
  6233. var ex = -Vector3.Dot(this._xAxis, eye);
  6234. var ey = -Vector3.Dot(this._yAxis, eye);
  6235. var ez = -Vector3.Dot(this._zAxis, eye);
  6236. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6237. };
  6238. /**
  6239. * 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"
  6240. * This function works in right handed mode
  6241. * @param eye defines the final position of the entity
  6242. * @param target defines where the entity should look at
  6243. * @param up defines the up vector for the entity
  6244. * @returns the new matrix
  6245. */
  6246. Matrix.LookAtRH = function (eye, target, up) {
  6247. var result = Matrix.Zero();
  6248. Matrix.LookAtRHToRef(eye, target, up, result);
  6249. return result;
  6250. };
  6251. /**
  6252. * 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".
  6253. * This function works in right handed mode
  6254. * @param eye defines the final position of the entity
  6255. * @param target defines where the entity should look at
  6256. * @param up defines the up vector for the entity
  6257. * @param result defines the target matrix
  6258. */
  6259. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6260. // Z axis
  6261. eye.subtractToRef(target, this._zAxis);
  6262. this._zAxis.normalize();
  6263. // X axis
  6264. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6265. if (this._xAxis.lengthSquared() === 0) {
  6266. this._xAxis.x = 1.0;
  6267. }
  6268. else {
  6269. this._xAxis.normalize();
  6270. }
  6271. // Y axis
  6272. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6273. this._yAxis.normalize();
  6274. // Eye angles
  6275. var ex = -Vector3.Dot(this._xAxis, eye);
  6276. var ey = -Vector3.Dot(this._yAxis, eye);
  6277. var ez = -Vector3.Dot(this._zAxis, eye);
  6278. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6279. };
  6280. /**
  6281. * Create a left-handed orthographic projection matrix
  6282. * @param width defines the viewport width
  6283. * @param height defines the viewport height
  6284. * @param znear defines the near clip plane
  6285. * @param zfar defines the far clip plane
  6286. * @returns a new matrix as a left-handed orthographic projection matrix
  6287. */
  6288. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6289. var matrix = Matrix.Zero();
  6290. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6291. return matrix;
  6292. };
  6293. /**
  6294. * Store a left-handed orthographic projection to a given matrix
  6295. * @param width defines the viewport width
  6296. * @param height defines the viewport height
  6297. * @param znear defines the near clip plane
  6298. * @param zfar defines the far clip plane
  6299. * @param result defines the target matrix
  6300. */
  6301. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6302. var n = znear;
  6303. var f = zfar;
  6304. var a = 2.0 / width;
  6305. var b = 2.0 / height;
  6306. var c = 2.0 / (f - n);
  6307. var d = -(f + n) / (f - n);
  6308. 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);
  6309. };
  6310. /**
  6311. * Create a left-handed orthographic projection matrix
  6312. * @param left defines the viewport left coordinate
  6313. * @param right defines the viewport right coordinate
  6314. * @param bottom defines the viewport bottom coordinate
  6315. * @param top defines the viewport top coordinate
  6316. * @param znear defines the near clip plane
  6317. * @param zfar defines the far clip plane
  6318. * @returns a new matrix as a left-handed orthographic projection matrix
  6319. */
  6320. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6321. var matrix = Matrix.Zero();
  6322. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6323. return matrix;
  6324. };
  6325. /**
  6326. * Stores a left-handed orthographic projection into a given matrix
  6327. * @param left defines the viewport left coordinate
  6328. * @param right defines the viewport right coordinate
  6329. * @param bottom defines the viewport bottom coordinate
  6330. * @param top defines the viewport top coordinate
  6331. * @param znear defines the near clip plane
  6332. * @param zfar defines the far clip plane
  6333. * @param result defines the target matrix
  6334. */
  6335. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6336. var n = znear;
  6337. var f = zfar;
  6338. var a = 2.0 / (right - left);
  6339. var b = 2.0 / (top - bottom);
  6340. var c = 2.0 / (f - n);
  6341. var d = -(f + n) / (f - n);
  6342. var i0 = (left + right) / (left - right);
  6343. var i1 = (top + bottom) / (bottom - top);
  6344. 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);
  6345. };
  6346. /**
  6347. * Creates a right-handed orthographic projection matrix
  6348. * @param left defines the viewport left coordinate
  6349. * @param right defines the viewport right coordinate
  6350. * @param bottom defines the viewport bottom coordinate
  6351. * @param top defines the viewport top coordinate
  6352. * @param znear defines the near clip plane
  6353. * @param zfar defines the far clip plane
  6354. * @returns a new matrix as a right-handed orthographic projection matrix
  6355. */
  6356. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6357. var matrix = Matrix.Zero();
  6358. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6359. return matrix;
  6360. };
  6361. /**
  6362. * Stores a right-handed orthographic projection into a given matrix
  6363. * @param left defines the viewport left coordinate
  6364. * @param right defines the viewport right coordinate
  6365. * @param bottom defines the viewport bottom coordinate
  6366. * @param top defines the viewport top coordinate
  6367. * @param znear defines the near clip plane
  6368. * @param zfar defines the far clip plane
  6369. * @param result defines the target matrix
  6370. */
  6371. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6372. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6373. result.m[10] *= -1.0;
  6374. };
  6375. /**
  6376. * Creates a left-handed perspective projection matrix
  6377. * @param width defines the viewport width
  6378. * @param height defines the viewport height
  6379. * @param znear defines the near clip plane
  6380. * @param zfar defines the far clip plane
  6381. * @returns a new matrix as a left-handed perspective projection matrix
  6382. */
  6383. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6384. var matrix = Matrix.Zero();
  6385. var n = znear;
  6386. var f = zfar;
  6387. var a = 2.0 * n / width;
  6388. var b = 2.0 * n / height;
  6389. var c = (f + n) / (f - n);
  6390. var d = -2.0 * f * n / (f - n);
  6391. 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);
  6392. return matrix;
  6393. };
  6394. /**
  6395. * Creates a left-handed perspective projection matrix
  6396. * @param fov defines the horizontal field of view
  6397. * @param aspect defines the aspect ratio
  6398. * @param znear defines the near clip plane
  6399. * @param zfar defines the far clip plane
  6400. * @returns a new matrix as a left-handed perspective projection matrix
  6401. */
  6402. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6403. var matrix = Matrix.Zero();
  6404. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6405. return matrix;
  6406. };
  6407. /**
  6408. * Stores a left-handed perspective projection into a given matrix
  6409. * @param fov defines the horizontal field of view
  6410. * @param aspect defines the aspect ratio
  6411. * @param znear defines the near clip plane
  6412. * @param zfar defines the far clip plane
  6413. * @param result defines the target matrix
  6414. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6415. */
  6416. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6417. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6418. var n = znear;
  6419. var f = zfar;
  6420. var t = 1.0 / (Math.tan(fov * 0.5));
  6421. var a = isVerticalFovFixed ? (t / aspect) : t;
  6422. var b = isVerticalFovFixed ? t : (t * aspect);
  6423. var c = (f + n) / (f - n);
  6424. var d = -2.0 * f * n / (f - n);
  6425. 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);
  6426. };
  6427. /**
  6428. * Creates a right-handed perspective projection matrix
  6429. * @param fov defines the horizontal field of view
  6430. * @param aspect defines the aspect ratio
  6431. * @param znear defines the near clip plane
  6432. * @param zfar defines the far clip plane
  6433. * @returns a new matrix as a right-handed perspective projection matrix
  6434. */
  6435. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6436. var matrix = Matrix.Zero();
  6437. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6438. return matrix;
  6439. };
  6440. /**
  6441. * Stores a right-handed perspective projection into a given matrix
  6442. * @param fov defines the horizontal field of view
  6443. * @param aspect defines the aspect ratio
  6444. * @param znear defines the near clip plane
  6445. * @param zfar defines the far clip plane
  6446. * @param result defines the target matrix
  6447. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6448. */
  6449. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6450. //alternatively this could be expressed as:
  6451. // m = PerspectiveFovLHToRef
  6452. // m[10] *= -1.0;
  6453. // m[11] *= -1.0;
  6454. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6455. var n = znear;
  6456. var f = zfar;
  6457. var t = 1.0 / (Math.tan(fov * 0.5));
  6458. var a = isVerticalFovFixed ? (t / aspect) : t;
  6459. var b = isVerticalFovFixed ? t : (t * aspect);
  6460. var c = -(f + n) / (f - n);
  6461. var d = -2 * f * n / (f - n);
  6462. 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);
  6463. };
  6464. /**
  6465. * Stores a perspective projection for WebVR info a given matrix
  6466. * @param fov defines the field of view
  6467. * @param znear defines the near clip plane
  6468. * @param zfar defines the far clip plane
  6469. * @param result defines the target matrix
  6470. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6471. */
  6472. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6473. if (rightHanded === void 0) { rightHanded = false; }
  6474. var rightHandedFactor = rightHanded ? -1 : 1;
  6475. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6476. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6477. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6478. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6479. var xScale = 2.0 / (leftTan + rightTan);
  6480. var yScale = 2.0 / (upTan + downTan);
  6481. result.m[0] = xScale;
  6482. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6483. result.m[5] = yScale;
  6484. result.m[6] = result.m[7] = 0.0;
  6485. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6486. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6487. result.m[10] = -zfar / (znear - zfar);
  6488. result.m[11] = 1.0 * rightHandedFactor;
  6489. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6490. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6491. result._markAsUpdated();
  6492. };
  6493. /**
  6494. * Computes a complete transformation matrix
  6495. * @param viewport defines the viewport to use
  6496. * @param world defines the world matrix
  6497. * @param view defines the view matrix
  6498. * @param projection defines the projection matrix
  6499. * @param zmin defines the near clip plane
  6500. * @param zmax defines the far clip plane
  6501. * @returns the transformation matrix
  6502. */
  6503. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6504. var cw = viewport.width;
  6505. var ch = viewport.height;
  6506. var cx = viewport.x;
  6507. var cy = viewport.y;
  6508. 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);
  6509. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6510. };
  6511. /**
  6512. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6513. * @param matrix defines the matrix to use
  6514. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6515. */
  6516. Matrix.GetAsMatrix2x2 = function (matrix) {
  6517. return new Float32Array([
  6518. matrix.m[0], matrix.m[1],
  6519. matrix.m[4], matrix.m[5]
  6520. ]);
  6521. };
  6522. /**
  6523. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6524. * @param matrix defines the matrix to use
  6525. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6526. */
  6527. Matrix.GetAsMatrix3x3 = function (matrix) {
  6528. return new Float32Array([
  6529. matrix.m[0], matrix.m[1], matrix.m[2],
  6530. matrix.m[4], matrix.m[5], matrix.m[6],
  6531. matrix.m[8], matrix.m[9], matrix.m[10]
  6532. ]);
  6533. };
  6534. /**
  6535. * Compute the transpose of a given matrix
  6536. * @param matrix defines the matrix to transpose
  6537. * @returns the new matrix
  6538. */
  6539. Matrix.Transpose = function (matrix) {
  6540. var result = new Matrix();
  6541. Matrix.TransposeToRef(matrix, result);
  6542. return result;
  6543. };
  6544. /**
  6545. * Compute the transpose of a matrix and store it in a target matrix
  6546. * @param matrix defines the matrix to transpose
  6547. * @param result defines the target matrix
  6548. */
  6549. Matrix.TransposeToRef = function (matrix, result) {
  6550. result.m[0] = matrix.m[0];
  6551. result.m[1] = matrix.m[4];
  6552. result.m[2] = matrix.m[8];
  6553. result.m[3] = matrix.m[12];
  6554. result.m[4] = matrix.m[1];
  6555. result.m[5] = matrix.m[5];
  6556. result.m[6] = matrix.m[9];
  6557. result.m[7] = matrix.m[13];
  6558. result.m[8] = matrix.m[2];
  6559. result.m[9] = matrix.m[6];
  6560. result.m[10] = matrix.m[10];
  6561. result.m[11] = matrix.m[14];
  6562. result.m[12] = matrix.m[3];
  6563. result.m[13] = matrix.m[7];
  6564. result.m[14] = matrix.m[11];
  6565. result.m[15] = matrix.m[15];
  6566. };
  6567. /**
  6568. * Computes a reflection matrix from a plane
  6569. * @param plane defines the reflection plane
  6570. * @returns a new matrix
  6571. */
  6572. Matrix.Reflection = function (plane) {
  6573. var matrix = new Matrix();
  6574. Matrix.ReflectionToRef(plane, matrix);
  6575. return matrix;
  6576. };
  6577. /**
  6578. * Computes a reflection matrix from a plane
  6579. * @param plane defines the reflection plane
  6580. * @param result defines the target matrix
  6581. */
  6582. Matrix.ReflectionToRef = function (plane, result) {
  6583. plane.normalize();
  6584. var x = plane.normal.x;
  6585. var y = plane.normal.y;
  6586. var z = plane.normal.z;
  6587. var temp = -2 * x;
  6588. var temp2 = -2 * y;
  6589. var temp3 = -2 * z;
  6590. result.m[0] = (temp * x) + 1;
  6591. result.m[1] = temp2 * x;
  6592. result.m[2] = temp3 * x;
  6593. result.m[3] = 0.0;
  6594. result.m[4] = temp * y;
  6595. result.m[5] = (temp2 * y) + 1;
  6596. result.m[6] = temp3 * y;
  6597. result.m[7] = 0.0;
  6598. result.m[8] = temp * z;
  6599. result.m[9] = temp2 * z;
  6600. result.m[10] = (temp3 * z) + 1;
  6601. result.m[11] = 0.0;
  6602. result.m[12] = temp * plane.d;
  6603. result.m[13] = temp2 * plane.d;
  6604. result.m[14] = temp3 * plane.d;
  6605. result.m[15] = 1.0;
  6606. result._markAsUpdated();
  6607. };
  6608. /**
  6609. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6610. * @param xaxis defines the value of the 1st axis
  6611. * @param yaxis defines the value of the 2nd axis
  6612. * @param zaxis defines the value of the 3rd axis
  6613. * @param result defines the target matrix
  6614. */
  6615. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6616. result.m[0] = xaxis.x;
  6617. result.m[1] = xaxis.y;
  6618. result.m[2] = xaxis.z;
  6619. result.m[3] = 0.0;
  6620. result.m[4] = yaxis.x;
  6621. result.m[5] = yaxis.y;
  6622. result.m[6] = yaxis.z;
  6623. result.m[7] = 0.0;
  6624. result.m[8] = zaxis.x;
  6625. result.m[9] = zaxis.y;
  6626. result.m[10] = zaxis.z;
  6627. result.m[11] = 0.0;
  6628. result.m[12] = 0.0;
  6629. result.m[13] = 0.0;
  6630. result.m[14] = 0.0;
  6631. result.m[15] = 1.0;
  6632. result._markAsUpdated();
  6633. };
  6634. /**
  6635. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6636. * @param quat defines the quaternion to use
  6637. * @param result defines the target matrix
  6638. */
  6639. Matrix.FromQuaternionToRef = function (quat, result) {
  6640. var xx = quat.x * quat.x;
  6641. var yy = quat.y * quat.y;
  6642. var zz = quat.z * quat.z;
  6643. var xy = quat.x * quat.y;
  6644. var zw = quat.z * quat.w;
  6645. var zx = quat.z * quat.x;
  6646. var yw = quat.y * quat.w;
  6647. var yz = quat.y * quat.z;
  6648. var xw = quat.x * quat.w;
  6649. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6650. result.m[1] = 2.0 * (xy + zw);
  6651. result.m[2] = 2.0 * (zx - yw);
  6652. result.m[3] = 0.0;
  6653. result.m[4] = 2.0 * (xy - zw);
  6654. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6655. result.m[6] = 2.0 * (yz + xw);
  6656. result.m[7] = 0.0;
  6657. result.m[8] = 2.0 * (zx + yw);
  6658. result.m[9] = 2.0 * (yz - xw);
  6659. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6660. result.m[11] = 0.0;
  6661. result.m[12] = 0.0;
  6662. result.m[13] = 0.0;
  6663. result.m[14] = 0.0;
  6664. result.m[15] = 1.0;
  6665. result._markAsUpdated();
  6666. };
  6667. Matrix._tempQuaternion = new Quaternion();
  6668. Matrix._xAxis = Vector3.Zero();
  6669. Matrix._yAxis = Vector3.Zero();
  6670. Matrix._zAxis = Vector3.Zero();
  6671. Matrix._updateFlagSeed = 0;
  6672. Matrix._identityReadOnly = Matrix.Identity();
  6673. return Matrix;
  6674. }());
  6675. BABYLON.Matrix = Matrix;
  6676. var Plane = /** @class */ (function () {
  6677. /**
  6678. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6679. */
  6680. function Plane(a, b, c, d) {
  6681. this.normal = new Vector3(a, b, c);
  6682. this.d = d;
  6683. }
  6684. /**
  6685. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6686. */
  6687. Plane.prototype.asArray = function () {
  6688. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6689. };
  6690. // Methods
  6691. /**
  6692. * Returns a new plane copied from the current Plane.
  6693. */
  6694. Plane.prototype.clone = function () {
  6695. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6696. };
  6697. /**
  6698. * Returns the string "Plane".
  6699. */
  6700. Plane.prototype.getClassName = function () {
  6701. return "Plane";
  6702. };
  6703. /**
  6704. * Returns the Plane hash code.
  6705. */
  6706. Plane.prototype.getHashCode = function () {
  6707. var hash = this.normal.getHashCode();
  6708. hash = (hash * 397) ^ (this.d || 0);
  6709. return hash;
  6710. };
  6711. /**
  6712. * Normalize the current Plane in place.
  6713. * Returns the updated Plane.
  6714. */
  6715. Plane.prototype.normalize = function () {
  6716. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6717. var magnitude = 0.0;
  6718. if (norm !== 0) {
  6719. magnitude = 1.0 / norm;
  6720. }
  6721. this.normal.x *= magnitude;
  6722. this.normal.y *= magnitude;
  6723. this.normal.z *= magnitude;
  6724. this.d *= magnitude;
  6725. return this;
  6726. };
  6727. /**
  6728. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6729. */
  6730. Plane.prototype.transform = function (transformation) {
  6731. var transposedMatrix = Matrix.Transpose(transformation);
  6732. var x = this.normal.x;
  6733. var y = this.normal.y;
  6734. var z = this.normal.z;
  6735. var d = this.d;
  6736. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6737. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6738. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6739. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6740. return new Plane(normalX, normalY, normalZ, finalD);
  6741. };
  6742. /**
  6743. * Returns the dot product (float) of the point coordinates and the plane normal.
  6744. */
  6745. Plane.prototype.dotCoordinate = function (point) {
  6746. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6747. };
  6748. /**
  6749. * Updates the current Plane from the plane defined by the three given points.
  6750. * Returns the updated Plane.
  6751. */
  6752. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6753. var x1 = point2.x - point1.x;
  6754. var y1 = point2.y - point1.y;
  6755. var z1 = point2.z - point1.z;
  6756. var x2 = point3.x - point1.x;
  6757. var y2 = point3.y - point1.y;
  6758. var z2 = point3.z - point1.z;
  6759. var yz = (y1 * z2) - (z1 * y2);
  6760. var xz = (z1 * x2) - (x1 * z2);
  6761. var xy = (x1 * y2) - (y1 * x2);
  6762. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6763. var invPyth;
  6764. if (pyth !== 0) {
  6765. invPyth = 1.0 / pyth;
  6766. }
  6767. else {
  6768. invPyth = 0.0;
  6769. }
  6770. this.normal.x = yz * invPyth;
  6771. this.normal.y = xz * invPyth;
  6772. this.normal.z = xy * invPyth;
  6773. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6774. return this;
  6775. };
  6776. /**
  6777. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6778. */
  6779. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6780. var dot = Vector3.Dot(this.normal, direction);
  6781. return (dot <= epsilon);
  6782. };
  6783. /**
  6784. * Returns the signed distance (float) from the given point to the Plane.
  6785. */
  6786. Plane.prototype.signedDistanceTo = function (point) {
  6787. return Vector3.Dot(point, this.normal) + this.d;
  6788. };
  6789. // Statics
  6790. /**
  6791. * Returns a new Plane from the given array.
  6792. */
  6793. Plane.FromArray = function (array) {
  6794. return new Plane(array[0], array[1], array[2], array[3]);
  6795. };
  6796. /**
  6797. * Returns a new Plane defined by the three given points.
  6798. */
  6799. Plane.FromPoints = function (point1, point2, point3) {
  6800. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6801. result.copyFromPoints(point1, point2, point3);
  6802. return result;
  6803. };
  6804. /**
  6805. * Returns a new Plane the normal vector to this plane at the given origin point.
  6806. * Note : the vector "normal" is updated because normalized.
  6807. */
  6808. Plane.FromPositionAndNormal = function (origin, normal) {
  6809. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6810. normal.normalize();
  6811. result.normal = normal;
  6812. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6813. return result;
  6814. };
  6815. /**
  6816. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6817. */
  6818. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6819. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6820. return Vector3.Dot(point, normal) + d;
  6821. };
  6822. return Plane;
  6823. }());
  6824. BABYLON.Plane = Plane;
  6825. /**
  6826. * Class used to represent a viewport on screen
  6827. */
  6828. var Viewport = /** @class */ (function () {
  6829. /**
  6830. * Creates a Viewport object located at (x, y) and sized (width, height)
  6831. * @param x defines viewport left coordinate
  6832. * @param y defines viewport top coordinate
  6833. * @param width defines the viewport width
  6834. * @param height defines the viewport height
  6835. */
  6836. function Viewport(
  6837. /** viewport left coordinate */
  6838. x,
  6839. /** viewport top coordinate */
  6840. y,
  6841. /**viewport width */
  6842. width,
  6843. /** viewport height */
  6844. height) {
  6845. this.x = x;
  6846. this.y = y;
  6847. this.width = width;
  6848. this.height = height;
  6849. }
  6850. /**
  6851. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  6852. * @param renderWidthOrEngine defines either an engine or the rendering width
  6853. * @param renderHeight defines the rendering height
  6854. * @returns a new Viewport
  6855. */
  6856. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6857. if (renderWidthOrEngine.getRenderWidth) {
  6858. var engine = renderWidthOrEngine;
  6859. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6860. }
  6861. var renderWidth = renderWidthOrEngine;
  6862. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6863. };
  6864. /**
  6865. * Returns a new Viewport copied from the current one
  6866. * @returns a new Viewport
  6867. */
  6868. Viewport.prototype.clone = function () {
  6869. return new Viewport(this.x, this.y, this.width, this.height);
  6870. };
  6871. return Viewport;
  6872. }());
  6873. BABYLON.Viewport = Viewport;
  6874. var Frustum = /** @class */ (function () {
  6875. function Frustum() {
  6876. }
  6877. /**
  6878. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6879. */
  6880. Frustum.GetPlanes = function (transform) {
  6881. var frustumPlanes = [];
  6882. for (var index = 0; index < 6; index++) {
  6883. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6884. }
  6885. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6886. return frustumPlanes;
  6887. };
  6888. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6889. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6890. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6891. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6892. frustumPlane.d = transform.m[15] + transform.m[14];
  6893. frustumPlane.normalize();
  6894. };
  6895. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6896. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6897. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6898. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6899. frustumPlane.d = transform.m[15] - transform.m[14];
  6900. frustumPlane.normalize();
  6901. };
  6902. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6903. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6904. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6905. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6906. frustumPlane.d = transform.m[15] + transform.m[12];
  6907. frustumPlane.normalize();
  6908. };
  6909. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6910. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6911. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6912. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6913. frustumPlane.d = transform.m[15] - transform.m[12];
  6914. frustumPlane.normalize();
  6915. };
  6916. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6917. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6918. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6919. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6920. frustumPlane.d = transform.m[15] - transform.m[13];
  6921. frustumPlane.normalize();
  6922. };
  6923. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6924. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6925. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6926. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6927. frustumPlane.d = transform.m[15] + transform.m[13];
  6928. frustumPlane.normalize();
  6929. };
  6930. /**
  6931. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6932. */
  6933. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6934. // Near
  6935. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6936. // Far
  6937. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6938. // Left
  6939. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6940. // Right
  6941. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6942. // Top
  6943. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6944. // Bottom
  6945. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6946. };
  6947. return Frustum;
  6948. }());
  6949. BABYLON.Frustum = Frustum;
  6950. /** Defines supported spaces */
  6951. var Space;
  6952. (function (Space) {
  6953. /** Local (object) space */
  6954. Space[Space["LOCAL"] = 0] = "LOCAL";
  6955. /** World space */
  6956. Space[Space["WORLD"] = 1] = "WORLD";
  6957. /** Bone space */
  6958. Space[Space["BONE"] = 2] = "BONE";
  6959. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6960. /** Defines the 3 main axes */
  6961. var Axis = /** @class */ (function () {
  6962. function Axis() {
  6963. }
  6964. /** X axis */
  6965. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6966. /** Y axis */
  6967. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6968. /** Z axis */
  6969. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6970. return Axis;
  6971. }());
  6972. BABYLON.Axis = Axis;
  6973. ;
  6974. /** Class used to represent a Bezier curve */
  6975. var BezierCurve = /** @class */ (function () {
  6976. function BezierCurve() {
  6977. }
  6978. /**
  6979. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  6980. * @param t defines the time
  6981. * @param x1 defines the left coordinate on X axis
  6982. * @param y1 defines the left coordinate on Y axis
  6983. * @param x2 defines the right coordinate on X axis
  6984. * @param y2 defines the right coordinate on Y axis
  6985. * @returns the interpolated value
  6986. */
  6987. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  6988. // Extract X (which is equal to time here)
  6989. var f0 = 1 - 3 * x2 + 3 * x1;
  6990. var f1 = 3 * x2 - 6 * x1;
  6991. var f2 = 3 * x1;
  6992. var refinedT = t;
  6993. for (var i = 0; i < 5; i++) {
  6994. var refinedT2 = refinedT * refinedT;
  6995. var refinedT3 = refinedT2 * refinedT;
  6996. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6997. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6998. refinedT -= (x - t) * slope;
  6999. refinedT = Math.min(1, Math.max(0, refinedT));
  7000. }
  7001. // Resolve cubic bezier for the given x
  7002. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  7003. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  7004. Math.pow(refinedT, 3);
  7005. };
  7006. return BezierCurve;
  7007. }());
  7008. BABYLON.BezierCurve = BezierCurve;
  7009. /**
  7010. * Defines potential orientation for back face culling
  7011. */
  7012. var Orientation;
  7013. (function (Orientation) {
  7014. /**
  7015. * Clockwise
  7016. */
  7017. Orientation[Orientation["CW"] = 0] = "CW";
  7018. /** Counter clockwise */
  7019. Orientation[Orientation["CCW"] = 1] = "CCW";
  7020. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  7021. /**
  7022. * Defines angle representation
  7023. */
  7024. var Angle = /** @class */ (function () {
  7025. /**
  7026. * Creates an Angle object of "radians" radians (float).
  7027. */
  7028. function Angle(radians) {
  7029. this._radians = radians;
  7030. if (this._radians < 0.0)
  7031. this._radians += (2.0 * Math.PI);
  7032. }
  7033. /**
  7034. * Get value in degrees
  7035. * @returns the Angle value in degrees (float)
  7036. */
  7037. Angle.prototype.degrees = function () {
  7038. return this._radians * 180.0 / Math.PI;
  7039. };
  7040. /**
  7041. * Get value in radians
  7042. * @returns the Angle value in radians (float)
  7043. */
  7044. Angle.prototype.radians = function () {
  7045. return this._radians;
  7046. };
  7047. /**
  7048. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  7049. * @param a defines first vector
  7050. * @param b defines second vector
  7051. * @returns a new Angle
  7052. */
  7053. Angle.BetweenTwoPoints = function (a, b) {
  7054. var delta = b.subtract(a);
  7055. var theta = Math.atan2(delta.y, delta.x);
  7056. return new Angle(theta);
  7057. };
  7058. /**
  7059. * Gets a new Angle object from the given float in radians
  7060. * @param radians defines the angle value in radians
  7061. * @returns a new Angle
  7062. */
  7063. Angle.FromRadians = function (radians) {
  7064. return new Angle(radians);
  7065. };
  7066. /**
  7067. * Gets a new Angle object from the given float in degrees
  7068. * @param degrees defines the angle value in degrees
  7069. * @returns a new Angle
  7070. */
  7071. Angle.FromDegrees = function (degrees) {
  7072. return new Angle(degrees * Math.PI / 180.0);
  7073. };
  7074. return Angle;
  7075. }());
  7076. BABYLON.Angle = Angle;
  7077. /**
  7078. * This represents an arc in a 2d space.
  7079. */
  7080. var Arc2 = /** @class */ (function () {
  7081. /**
  7082. * Creates an Arc object from the three given points : start, middle and end.
  7083. * @param startPoint Defines the start point of the arc
  7084. * @param midPoint Defines the midlle point of the arc
  7085. * @param endPoint Defines the end point of the arc
  7086. */
  7087. function Arc2(
  7088. /** Defines the start point of the arc */
  7089. startPoint,
  7090. /** Defines the mid point of the arc */
  7091. midPoint,
  7092. /** Defines the end point of the arc */
  7093. endPoint) {
  7094. this.startPoint = startPoint;
  7095. this.midPoint = midPoint;
  7096. this.endPoint = endPoint;
  7097. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7098. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7099. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7100. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7101. 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);
  7102. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7103. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7104. var a1 = this.startAngle.degrees();
  7105. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7106. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7107. // angles correction
  7108. if (a2 - a1 > +180.0)
  7109. a2 -= 360.0;
  7110. if (a2 - a1 < -180.0)
  7111. a2 += 360.0;
  7112. if (a3 - a2 > +180.0)
  7113. a3 -= 360.0;
  7114. if (a3 - a2 < -180.0)
  7115. a3 += 360.0;
  7116. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7117. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7118. }
  7119. return Arc2;
  7120. }());
  7121. BABYLON.Arc2 = Arc2;
  7122. var Path2 = /** @class */ (function () {
  7123. /**
  7124. * Creates a Path2 object from the starting 2D coordinates x and y.
  7125. */
  7126. function Path2(x, y) {
  7127. this._points = new Array();
  7128. this._length = 0.0;
  7129. this.closed = false;
  7130. this._points.push(new Vector2(x, y));
  7131. }
  7132. /**
  7133. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7134. * Returns the updated Path2.
  7135. */
  7136. Path2.prototype.addLineTo = function (x, y) {
  7137. if (this.closed) {
  7138. return this;
  7139. }
  7140. var newPoint = new Vector2(x, y);
  7141. var previousPoint = this._points[this._points.length - 1];
  7142. this._points.push(newPoint);
  7143. this._length += newPoint.subtract(previousPoint).length();
  7144. return this;
  7145. };
  7146. /**
  7147. * 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.
  7148. * Returns the updated Path2.
  7149. */
  7150. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7151. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7152. if (this.closed) {
  7153. return this;
  7154. }
  7155. var startPoint = this._points[this._points.length - 1];
  7156. var midPoint = new Vector2(midX, midY);
  7157. var endPoint = new Vector2(endX, endY);
  7158. var arc = new Arc2(startPoint, midPoint, endPoint);
  7159. var increment = arc.angle.radians() / numberOfSegments;
  7160. if (arc.orientation === Orientation.CW)
  7161. increment *= -1;
  7162. var currentAngle = arc.startAngle.radians() + increment;
  7163. for (var i = 0; i < numberOfSegments; i++) {
  7164. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7165. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7166. this.addLineTo(x, y);
  7167. currentAngle += increment;
  7168. }
  7169. return this;
  7170. };
  7171. /**
  7172. * Closes the Path2.
  7173. * Returns the Path2.
  7174. */
  7175. Path2.prototype.close = function () {
  7176. this.closed = true;
  7177. return this;
  7178. };
  7179. /**
  7180. * Returns the Path2 total length (float).
  7181. */
  7182. Path2.prototype.length = function () {
  7183. var result = this._length;
  7184. if (!this.closed) {
  7185. var lastPoint = this._points[this._points.length - 1];
  7186. var firstPoint = this._points[0];
  7187. result += (firstPoint.subtract(lastPoint).length());
  7188. }
  7189. return result;
  7190. };
  7191. /**
  7192. * Returns the Path2 internal array of points.
  7193. */
  7194. Path2.prototype.getPoints = function () {
  7195. return this._points;
  7196. };
  7197. /**
  7198. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7199. */
  7200. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7201. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7202. return Vector2.Zero();
  7203. }
  7204. var lengthPosition = normalizedLengthPosition * this.length();
  7205. var previousOffset = 0;
  7206. for (var i = 0; i < this._points.length; i++) {
  7207. var j = (i + 1) % this._points.length;
  7208. var a = this._points[i];
  7209. var b = this._points[j];
  7210. var bToA = b.subtract(a);
  7211. var nextOffset = (bToA.length() + previousOffset);
  7212. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7213. var dir = bToA.normalize();
  7214. var localOffset = lengthPosition - previousOffset;
  7215. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7216. }
  7217. previousOffset = nextOffset;
  7218. }
  7219. return Vector2.Zero();
  7220. };
  7221. /**
  7222. * Returns a new Path2 starting at the coordinates (x, y).
  7223. */
  7224. Path2.StartingAt = function (x, y) {
  7225. return new Path2(x, y);
  7226. };
  7227. return Path2;
  7228. }());
  7229. BABYLON.Path2 = Path2;
  7230. var Path3D = /** @class */ (function () {
  7231. /**
  7232. * new Path3D(path, normal, raw)
  7233. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7234. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7235. * path : an array of Vector3, the curve axis of the Path3D
  7236. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7237. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7238. */
  7239. function Path3D(path, firstNormal, raw) {
  7240. if (firstNormal === void 0) { firstNormal = null; }
  7241. this.path = path;
  7242. this._curve = new Array();
  7243. this._distances = new Array();
  7244. this._tangents = new Array();
  7245. this._normals = new Array();
  7246. this._binormals = new Array();
  7247. for (var p = 0; p < path.length; p++) {
  7248. this._curve[p] = path[p].clone(); // hard copy
  7249. }
  7250. this._raw = raw || false;
  7251. this._compute(firstNormal);
  7252. }
  7253. /**
  7254. * Returns the Path3D array of successive Vector3 designing its curve.
  7255. */
  7256. Path3D.prototype.getCurve = function () {
  7257. return this._curve;
  7258. };
  7259. /**
  7260. * Returns an array populated with tangent vectors on each Path3D curve point.
  7261. */
  7262. Path3D.prototype.getTangents = function () {
  7263. return this._tangents;
  7264. };
  7265. /**
  7266. * Returns an array populated with normal vectors on each Path3D curve point.
  7267. */
  7268. Path3D.prototype.getNormals = function () {
  7269. return this._normals;
  7270. };
  7271. /**
  7272. * Returns an array populated with binormal vectors on each Path3D curve point.
  7273. */
  7274. Path3D.prototype.getBinormals = function () {
  7275. return this._binormals;
  7276. };
  7277. /**
  7278. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7279. */
  7280. Path3D.prototype.getDistances = function () {
  7281. return this._distances;
  7282. };
  7283. /**
  7284. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7285. * Returns the same object updated.
  7286. */
  7287. Path3D.prototype.update = function (path, firstNormal) {
  7288. if (firstNormal === void 0) { firstNormal = null; }
  7289. for (var p = 0; p < path.length; p++) {
  7290. this._curve[p].x = path[p].x;
  7291. this._curve[p].y = path[p].y;
  7292. this._curve[p].z = path[p].z;
  7293. }
  7294. this._compute(firstNormal);
  7295. return this;
  7296. };
  7297. // private function compute() : computes tangents, normals and binormals
  7298. Path3D.prototype._compute = function (firstNormal) {
  7299. var l = this._curve.length;
  7300. // first and last tangents
  7301. this._tangents[0] = this._getFirstNonNullVector(0);
  7302. if (!this._raw) {
  7303. this._tangents[0].normalize();
  7304. }
  7305. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7306. if (!this._raw) {
  7307. this._tangents[l - 1].normalize();
  7308. }
  7309. // normals and binormals at first point : arbitrary vector with _normalVector()
  7310. var tg0 = this._tangents[0];
  7311. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7312. this._normals[0] = pp0;
  7313. if (!this._raw) {
  7314. this._normals[0].normalize();
  7315. }
  7316. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7317. if (!this._raw) {
  7318. this._binormals[0].normalize();
  7319. }
  7320. this._distances[0] = 0.0;
  7321. // normals and binormals : next points
  7322. var prev; // previous vector (segment)
  7323. var cur; // current vector (segment)
  7324. var curTang; // current tangent
  7325. // previous normal
  7326. var prevBinor; // previous binormal
  7327. for (var i = 1; i < l; i++) {
  7328. // tangents
  7329. prev = this._getLastNonNullVector(i);
  7330. if (i < l - 1) {
  7331. cur = this._getFirstNonNullVector(i);
  7332. this._tangents[i] = prev.add(cur);
  7333. this._tangents[i].normalize();
  7334. }
  7335. this._distances[i] = this._distances[i - 1] + prev.length();
  7336. // normals and binormals
  7337. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7338. curTang = this._tangents[i];
  7339. prevBinor = this._binormals[i - 1];
  7340. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7341. if (!this._raw) {
  7342. this._normals[i].normalize();
  7343. }
  7344. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7345. if (!this._raw) {
  7346. this._binormals[i].normalize();
  7347. }
  7348. }
  7349. };
  7350. // private function getFirstNonNullVector(index)
  7351. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7352. Path3D.prototype._getFirstNonNullVector = function (index) {
  7353. var i = 1;
  7354. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7355. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7356. i++;
  7357. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7358. }
  7359. return nNVector;
  7360. };
  7361. // private function getLastNonNullVector(index)
  7362. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7363. Path3D.prototype._getLastNonNullVector = function (index) {
  7364. var i = 1;
  7365. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7366. while (nLVector.length() === 0 && index > i + 1) {
  7367. i++;
  7368. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7369. }
  7370. return nLVector;
  7371. };
  7372. // private function normalVector(v0, vt, va) :
  7373. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7374. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7375. Path3D.prototype._normalVector = function (v0, vt, va) {
  7376. var normal0;
  7377. var tgl = vt.length();
  7378. if (tgl === 0.0) {
  7379. tgl = 1.0;
  7380. }
  7381. if (va === undefined || va === null) {
  7382. var point;
  7383. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7384. point = new Vector3(0.0, -1.0, 0.0);
  7385. }
  7386. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7387. point = new Vector3(1.0, 0.0, 0.0);
  7388. }
  7389. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7390. point = new Vector3(0.0, 0.0, 1.0);
  7391. }
  7392. else {
  7393. point = Vector3.Zero();
  7394. }
  7395. normal0 = Vector3.Cross(vt, point);
  7396. }
  7397. else {
  7398. normal0 = Vector3.Cross(vt, va);
  7399. Vector3.CrossToRef(normal0, vt, normal0);
  7400. }
  7401. normal0.normalize();
  7402. return normal0;
  7403. };
  7404. return Path3D;
  7405. }());
  7406. BABYLON.Path3D = Path3D;
  7407. var Curve3 = /** @class */ (function () {
  7408. /**
  7409. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7410. * A Curve3 is designed from a series of successive Vector3.
  7411. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7412. */
  7413. function Curve3(points) {
  7414. this._length = 0.0;
  7415. this._points = points;
  7416. this._length = this._computeLength(points);
  7417. }
  7418. /**
  7419. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7420. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7421. * @param v1 (Vector3) the control point
  7422. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7423. * @param nbPoints (integer) the wanted number of points in the curve
  7424. */
  7425. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7426. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7427. var bez = new Array();
  7428. var equation = function (t, val0, val1, val2) {
  7429. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7430. return res;
  7431. };
  7432. for (var i = 0; i <= nbPoints; i++) {
  7433. 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)));
  7434. }
  7435. return new Curve3(bez);
  7436. };
  7437. /**
  7438. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7439. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7440. * @param v1 (Vector3) the first control point
  7441. * @param v2 (Vector3) the second control point
  7442. * @param v3 (Vector3) the end point of the Cubic Bezier
  7443. * @param nbPoints (integer) the wanted number of points in the curve
  7444. */
  7445. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7446. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7447. var bez = new Array();
  7448. var equation = function (t, val0, val1, val2, val3) {
  7449. 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;
  7450. return res;
  7451. };
  7452. for (var i = 0; i <= nbPoints; i++) {
  7453. 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)));
  7454. }
  7455. return new Curve3(bez);
  7456. };
  7457. /**
  7458. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7459. * @param p1 (Vector3) the origin point of the Hermite Spline
  7460. * @param t1 (Vector3) the tangent vector at the origin point
  7461. * @param p2 (Vector3) the end point of the Hermite Spline
  7462. * @param t2 (Vector3) the tangent vector at the end point
  7463. * @param nbPoints (integer) the wanted number of points in the curve
  7464. */
  7465. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7466. var hermite = new Array();
  7467. var step = 1.0 / nbPoints;
  7468. for (var i = 0; i <= nbPoints; i++) {
  7469. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7470. }
  7471. return new Curve3(hermite);
  7472. };
  7473. /**
  7474. * Returns a Curve3 object along a CatmullRom Spline curve :
  7475. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7476. * @param nbPoints (integer) the wanted number of points between each curve control points
  7477. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7478. */
  7479. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7480. var catmullRom = new Array();
  7481. var step = 1.0 / nbPoints;
  7482. var amount = 0.0;
  7483. if (closed) {
  7484. var pointsCount = points.length;
  7485. for (var i = 0; i < pointsCount; i++) {
  7486. amount = 0;
  7487. for (var c = 0; c < nbPoints; c++) {
  7488. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7489. amount += step;
  7490. }
  7491. }
  7492. catmullRom.push(catmullRom[0]);
  7493. }
  7494. else {
  7495. var totalPoints = new Array();
  7496. totalPoints.push(points[0].clone());
  7497. Array.prototype.push.apply(totalPoints, points);
  7498. totalPoints.push(points[points.length - 1].clone());
  7499. for (var i = 0; i < totalPoints.length - 3; i++) {
  7500. amount = 0;
  7501. for (var c = 0; c < nbPoints; c++) {
  7502. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7503. amount += step;
  7504. }
  7505. }
  7506. i--;
  7507. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7508. }
  7509. return new Curve3(catmullRom);
  7510. };
  7511. /**
  7512. * Returns the Curve3 stored array of successive Vector3
  7513. */
  7514. Curve3.prototype.getPoints = function () {
  7515. return this._points;
  7516. };
  7517. /**
  7518. * Returns the computed length (float) of the curve.
  7519. */
  7520. Curve3.prototype.length = function () {
  7521. return this._length;
  7522. };
  7523. /**
  7524. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7525. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7526. * curveA and curveB keep unchanged.
  7527. */
  7528. Curve3.prototype.continue = function (curve) {
  7529. var lastPoint = this._points[this._points.length - 1];
  7530. var continuedPoints = this._points.slice();
  7531. var curvePoints = curve.getPoints();
  7532. for (var i = 1; i < curvePoints.length; i++) {
  7533. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7534. }
  7535. var continuedCurve = new Curve3(continuedPoints);
  7536. return continuedCurve;
  7537. };
  7538. Curve3.prototype._computeLength = function (path) {
  7539. var l = 0;
  7540. for (var i = 1; i < path.length; i++) {
  7541. l += (path[i].subtract(path[i - 1])).length();
  7542. }
  7543. return l;
  7544. };
  7545. return Curve3;
  7546. }());
  7547. BABYLON.Curve3 = Curve3;
  7548. // Vertex formats
  7549. var PositionNormalVertex = /** @class */ (function () {
  7550. function PositionNormalVertex(position, normal) {
  7551. if (position === void 0) { position = Vector3.Zero(); }
  7552. if (normal === void 0) { normal = Vector3.Up(); }
  7553. this.position = position;
  7554. this.normal = normal;
  7555. }
  7556. PositionNormalVertex.prototype.clone = function () {
  7557. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7558. };
  7559. return PositionNormalVertex;
  7560. }());
  7561. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7562. var PositionNormalTextureVertex = /** @class */ (function () {
  7563. function PositionNormalTextureVertex(position, normal, uv) {
  7564. if (position === void 0) { position = Vector3.Zero(); }
  7565. if (normal === void 0) { normal = Vector3.Up(); }
  7566. if (uv === void 0) { uv = Vector2.Zero(); }
  7567. this.position = position;
  7568. this.normal = normal;
  7569. this.uv = uv;
  7570. }
  7571. PositionNormalTextureVertex.prototype.clone = function () {
  7572. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7573. };
  7574. return PositionNormalTextureVertex;
  7575. }());
  7576. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7577. // Temporary pre-allocated objects for engine internal use
  7578. // usage in any internal function :
  7579. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7580. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7581. var Tmp = /** @class */ (function () {
  7582. function Tmp() {
  7583. }
  7584. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7585. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7586. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7587. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7588. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7589. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7590. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7591. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7592. Matrix.Zero(), Matrix.Zero(),
  7593. Matrix.Zero(), Matrix.Zero(),
  7594. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7595. return Tmp;
  7596. }());
  7597. BABYLON.Tmp = Tmp;
  7598. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7599. var MathTmp = /** @class */ (function () {
  7600. function MathTmp() {
  7601. }
  7602. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7603. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7604. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7605. return MathTmp;
  7606. }());
  7607. })(BABYLON || (BABYLON = {}));
  7608. //# sourceMappingURL=babylon.math.js.map
  7609. var BABYLON;
  7610. (function (BABYLON) {
  7611. var Scalar = /** @class */ (function () {
  7612. function Scalar() {
  7613. }
  7614. /**
  7615. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7616. */
  7617. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7618. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7619. var num = a - b;
  7620. return -epsilon <= num && num <= epsilon;
  7621. };
  7622. /**
  7623. * Returns a string : the upper case translation of the number i to hexadecimal.
  7624. */
  7625. Scalar.ToHex = function (i) {
  7626. var str = i.toString(16);
  7627. if (i <= 15) {
  7628. return ("0" + str).toUpperCase();
  7629. }
  7630. return str.toUpperCase();
  7631. };
  7632. /**
  7633. * Returns -1 if value is negative and +1 is value is positive.
  7634. * Returns the value itself if it's equal to zero.
  7635. */
  7636. Scalar.Sign = function (value) {
  7637. value = +value; // convert to a number
  7638. if (value === 0 || isNaN(value))
  7639. return value;
  7640. return value > 0 ? 1 : -1;
  7641. };
  7642. /**
  7643. * Returns the value itself if it's between min and max.
  7644. * Returns min if the value is lower than min.
  7645. * Returns max if the value is greater than max.
  7646. */
  7647. Scalar.Clamp = function (value, min, max) {
  7648. if (min === void 0) { min = 0; }
  7649. if (max === void 0) { max = 1; }
  7650. return Math.min(max, Math.max(min, value));
  7651. };
  7652. /**
  7653. * Returns the log2 of value.
  7654. */
  7655. Scalar.Log2 = function (value) {
  7656. return Math.log(value) * Math.LOG2E;
  7657. };
  7658. /**
  7659. * Loops the value, so that it is never larger than length and never smaller than 0.
  7660. *
  7661. * This is similar to the modulo operator but it works with floating point numbers.
  7662. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7663. * With t = 5 and length = 2.5, the result would be 0.0.
  7664. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7665. */
  7666. Scalar.Repeat = function (value, length) {
  7667. return value - Math.floor(value / length) * length;
  7668. };
  7669. /**
  7670. * Normalize the value between 0.0 and 1.0 using min and max values
  7671. */
  7672. Scalar.Normalize = function (value, min, max) {
  7673. return (value - min) / (max - min);
  7674. };
  7675. /**
  7676. * Denormalize the value from 0.0 and 1.0 using min and max values
  7677. */
  7678. Scalar.Denormalize = function (normalized, min, max) {
  7679. return (normalized * (max - min) + min);
  7680. };
  7681. /**
  7682. * Calculates the shortest difference between two given angles given in degrees.
  7683. */
  7684. Scalar.DeltaAngle = function (current, target) {
  7685. var num = Scalar.Repeat(target - current, 360.0);
  7686. if (num > 180.0) {
  7687. num -= 360.0;
  7688. }
  7689. return num;
  7690. };
  7691. /**
  7692. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7693. *
  7694. * The returned value will move back and forth between 0 and length
  7695. */
  7696. Scalar.PingPong = function (tx, length) {
  7697. var t = Scalar.Repeat(tx, length * 2.0);
  7698. return length - Math.abs(t - length);
  7699. };
  7700. /**
  7701. * Interpolates between min and max with smoothing at the limits.
  7702. *
  7703. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7704. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7705. */
  7706. Scalar.SmoothStep = function (from, to, tx) {
  7707. var t = Scalar.Clamp(tx);
  7708. t = -2.0 * t * t * t + 3.0 * t * t;
  7709. return to * t + from * (1.0 - t);
  7710. };
  7711. /**
  7712. * Moves a value current towards target.
  7713. *
  7714. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7715. * Negative values of maxDelta pushes the value away from target.
  7716. */
  7717. Scalar.MoveTowards = function (current, target, maxDelta) {
  7718. var result = 0;
  7719. if (Math.abs(target - current) <= maxDelta) {
  7720. result = target;
  7721. }
  7722. else {
  7723. result = current + Scalar.Sign(target - current) * maxDelta;
  7724. }
  7725. return result;
  7726. };
  7727. /**
  7728. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7729. *
  7730. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7731. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7732. */
  7733. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7734. var num = Scalar.DeltaAngle(current, target);
  7735. var result = 0;
  7736. if (-maxDelta < num && num < maxDelta) {
  7737. result = target;
  7738. }
  7739. else {
  7740. target = current + num;
  7741. result = Scalar.MoveTowards(current, target, maxDelta);
  7742. }
  7743. return result;
  7744. };
  7745. /**
  7746. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7747. */
  7748. Scalar.Lerp = function (start, end, amount) {
  7749. return start + ((end - start) * amount);
  7750. };
  7751. /**
  7752. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7753. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7754. */
  7755. Scalar.LerpAngle = function (start, end, amount) {
  7756. var num = Scalar.Repeat(end - start, 360.0);
  7757. if (num > 180.0) {
  7758. num -= 360.0;
  7759. }
  7760. return start + num * Scalar.Clamp(amount);
  7761. };
  7762. /**
  7763. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7764. */
  7765. Scalar.InverseLerp = function (a, b, value) {
  7766. var result = 0;
  7767. if (a != b) {
  7768. result = Scalar.Clamp((value - a) / (b - a));
  7769. }
  7770. else {
  7771. result = 0.0;
  7772. }
  7773. return result;
  7774. };
  7775. /**
  7776. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7777. */
  7778. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7779. var squared = amount * amount;
  7780. var cubed = amount * squared;
  7781. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7782. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7783. var part3 = (cubed - (2.0 * squared)) + amount;
  7784. var part4 = cubed - squared;
  7785. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7786. };
  7787. /**
  7788. * Returns a random float number between and min and max values
  7789. */
  7790. Scalar.RandomRange = function (min, max) {
  7791. if (min === max)
  7792. return min;
  7793. return ((Math.random() * (max - min)) + min);
  7794. };
  7795. /**
  7796. * This function returns percentage of a number in a given range.
  7797. *
  7798. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7799. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7800. */
  7801. Scalar.RangeToPercent = function (number, min, max) {
  7802. return ((number - min) / (max - min));
  7803. };
  7804. /**
  7805. * This function returns number that corresponds to the percentage in a given range.
  7806. *
  7807. * PercentToRange(0.34,0,100) will return 34.
  7808. */
  7809. Scalar.PercentToRange = function (percent, min, max) {
  7810. return ((max - min) * percent + min);
  7811. };
  7812. /**
  7813. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7814. * @param angle The angle to normalize in radian.
  7815. * @return The converted angle.
  7816. */
  7817. Scalar.NormalizeRadians = function (angle) {
  7818. // More precise but slower version kept for reference.
  7819. // angle = angle % Tools.TwoPi;
  7820. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7821. //if (angle > Math.PI) {
  7822. // angle -= Tools.TwoPi;
  7823. //}
  7824. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7825. return angle;
  7826. };
  7827. /**
  7828. * Two pi constants convenient for computation.
  7829. */
  7830. Scalar.TwoPi = Math.PI * 2;
  7831. return Scalar;
  7832. }());
  7833. BABYLON.Scalar = Scalar;
  7834. })(BABYLON || (BABYLON = {}));
  7835. //# sourceMappingURL=babylon.math.scalar.js.map
  7836. //# sourceMappingURL=babylon.mixins.js.map
  7837. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7838. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7839. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7840. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7841. //# sourceMappingURL=babylon.webgl2.js.map
  7842. var BABYLON;
  7843. (function (BABYLON) {
  7844. var __decoratorInitialStore = {};
  7845. var __mergedStore = {};
  7846. var _copySource = function (creationFunction, source, instanciate) {
  7847. var destination = creationFunction();
  7848. // Tags
  7849. if (BABYLON.Tags) {
  7850. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7851. }
  7852. var classStore = getMergedStore(destination);
  7853. // Properties
  7854. for (var property in classStore) {
  7855. var propertyDescriptor = classStore[property];
  7856. var sourceProperty = source[property];
  7857. var propertyType = propertyDescriptor.type;
  7858. if (sourceProperty !== undefined && sourceProperty !== null) {
  7859. switch (propertyType) {
  7860. case 0: // Value
  7861. case 6: // Mesh reference
  7862. case 11: // Camera reference
  7863. destination[property] = sourceProperty;
  7864. break;
  7865. case 1: // Texture
  7866. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7867. break;
  7868. case 2: // Color3
  7869. case 3: // FresnelParameters
  7870. case 4: // Vector2
  7871. case 5: // Vector3
  7872. case 7: // Color Curves
  7873. case 10: // Quaternion
  7874. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7875. break;
  7876. }
  7877. }
  7878. }
  7879. return destination;
  7880. };
  7881. function getDirectStore(target) {
  7882. var classKey = target.getClassName();
  7883. if (!__decoratorInitialStore[classKey]) {
  7884. __decoratorInitialStore[classKey] = {};
  7885. }
  7886. return __decoratorInitialStore[classKey];
  7887. }
  7888. /**
  7889. * Return the list of properties flagged as serializable
  7890. * @param target: host object
  7891. */
  7892. function getMergedStore(target) {
  7893. var classKey = target.getClassName();
  7894. if (__mergedStore[classKey]) {
  7895. return __mergedStore[classKey];
  7896. }
  7897. __mergedStore[classKey] = {};
  7898. var store = __mergedStore[classKey];
  7899. var currentTarget = target;
  7900. var currentKey = classKey;
  7901. while (currentKey) {
  7902. var initialStore = __decoratorInitialStore[currentKey];
  7903. for (var property in initialStore) {
  7904. store[property] = initialStore[property];
  7905. }
  7906. var parent_1 = void 0;
  7907. var done = false;
  7908. do {
  7909. parent_1 = Object.getPrototypeOf(currentTarget);
  7910. if (!parent_1.getClassName) {
  7911. done = true;
  7912. break;
  7913. }
  7914. if (parent_1.getClassName() !== currentKey) {
  7915. break;
  7916. }
  7917. currentTarget = parent_1;
  7918. } while (parent_1);
  7919. if (done) {
  7920. break;
  7921. }
  7922. currentKey = parent_1.getClassName();
  7923. currentTarget = parent_1;
  7924. }
  7925. return store;
  7926. }
  7927. function generateSerializableMember(type, sourceName) {
  7928. return function (target, propertyKey) {
  7929. var classStore = getDirectStore(target);
  7930. if (!classStore[propertyKey]) {
  7931. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7932. }
  7933. };
  7934. }
  7935. function generateExpandMember(setCallback, targetKey) {
  7936. if (targetKey === void 0) { targetKey = null; }
  7937. return function (target, propertyKey) {
  7938. var key = targetKey || ("_" + propertyKey);
  7939. Object.defineProperty(target, propertyKey, {
  7940. get: function () {
  7941. return this[key];
  7942. },
  7943. set: function (value) {
  7944. if (this[key] === value) {
  7945. return;
  7946. }
  7947. this[key] = value;
  7948. target[setCallback].apply(this);
  7949. },
  7950. enumerable: true,
  7951. configurable: true
  7952. });
  7953. };
  7954. }
  7955. function expandToProperty(callback, targetKey) {
  7956. if (targetKey === void 0) { targetKey = null; }
  7957. return generateExpandMember(callback, targetKey);
  7958. }
  7959. BABYLON.expandToProperty = expandToProperty;
  7960. function serialize(sourceName) {
  7961. return generateSerializableMember(0, sourceName); // value member
  7962. }
  7963. BABYLON.serialize = serialize;
  7964. function serializeAsTexture(sourceName) {
  7965. return generateSerializableMember(1, sourceName); // texture member
  7966. }
  7967. BABYLON.serializeAsTexture = serializeAsTexture;
  7968. function serializeAsColor3(sourceName) {
  7969. return generateSerializableMember(2, sourceName); // color3 member
  7970. }
  7971. BABYLON.serializeAsColor3 = serializeAsColor3;
  7972. function serializeAsFresnelParameters(sourceName) {
  7973. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7974. }
  7975. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7976. function serializeAsVector2(sourceName) {
  7977. return generateSerializableMember(4, sourceName); // vector2 member
  7978. }
  7979. BABYLON.serializeAsVector2 = serializeAsVector2;
  7980. function serializeAsVector3(sourceName) {
  7981. return generateSerializableMember(5, sourceName); // vector3 member
  7982. }
  7983. BABYLON.serializeAsVector3 = serializeAsVector3;
  7984. function serializeAsMeshReference(sourceName) {
  7985. return generateSerializableMember(6, sourceName); // mesh reference member
  7986. }
  7987. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7988. function serializeAsColorCurves(sourceName) {
  7989. return generateSerializableMember(7, sourceName); // color curves
  7990. }
  7991. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7992. function serializeAsColor4(sourceName) {
  7993. return generateSerializableMember(8, sourceName); // color 4
  7994. }
  7995. BABYLON.serializeAsColor4 = serializeAsColor4;
  7996. function serializeAsImageProcessingConfiguration(sourceName) {
  7997. return generateSerializableMember(9, sourceName); // image processing
  7998. }
  7999. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  8000. function serializeAsQuaternion(sourceName) {
  8001. return generateSerializableMember(10, sourceName); // quaternion member
  8002. }
  8003. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  8004. /**
  8005. * Decorator used to define property that can be serialized as reference to a camera
  8006. * @param sourceName defines the name of the property to decorate
  8007. */
  8008. function serializeAsCameraReference(sourceName) {
  8009. return generateSerializableMember(11, sourceName); // camera reference member
  8010. }
  8011. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  8012. var SerializationHelper = /** @class */ (function () {
  8013. function SerializationHelper() {
  8014. }
  8015. SerializationHelper.Serialize = function (entity, serializationObject) {
  8016. if (!serializationObject) {
  8017. serializationObject = {};
  8018. }
  8019. // Tags
  8020. if (BABYLON.Tags) {
  8021. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  8022. }
  8023. var serializedProperties = getMergedStore(entity);
  8024. // Properties
  8025. for (var property in serializedProperties) {
  8026. var propertyDescriptor = serializedProperties[property];
  8027. var targetPropertyName = propertyDescriptor.sourceName || property;
  8028. var propertyType = propertyDescriptor.type;
  8029. var sourceProperty = entity[property];
  8030. if (sourceProperty !== undefined && sourceProperty !== null) {
  8031. switch (propertyType) {
  8032. case 0: // Value
  8033. serializationObject[targetPropertyName] = sourceProperty;
  8034. break;
  8035. case 1: // Texture
  8036. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8037. break;
  8038. case 2: // Color3
  8039. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8040. break;
  8041. case 3: // FresnelParameters
  8042. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8043. break;
  8044. case 4: // Vector2
  8045. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8046. break;
  8047. case 5: // Vector3
  8048. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8049. break;
  8050. case 6: // Mesh reference
  8051. serializationObject[targetPropertyName] = sourceProperty.id;
  8052. break;
  8053. case 7: // Color Curves
  8054. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8055. break;
  8056. case 8: // Color 4
  8057. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8058. break;
  8059. case 9: // Image Processing
  8060. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8061. break;
  8062. case 10: // Quaternion
  8063. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8064. break;
  8065. case 11: // Camera reference
  8066. serializationObject[targetPropertyName] = sourceProperty.id;
  8067. break;
  8068. }
  8069. }
  8070. }
  8071. return serializationObject;
  8072. };
  8073. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8074. if (rootUrl === void 0) { rootUrl = null; }
  8075. var destination = creationFunction();
  8076. if (!rootUrl) {
  8077. rootUrl = "";
  8078. }
  8079. // Tags
  8080. if (BABYLON.Tags) {
  8081. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8082. }
  8083. var classStore = getMergedStore(destination);
  8084. // Properties
  8085. for (var property in classStore) {
  8086. var propertyDescriptor = classStore[property];
  8087. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8088. var propertyType = propertyDescriptor.type;
  8089. if (sourceProperty !== undefined && sourceProperty !== null) {
  8090. var dest = destination;
  8091. switch (propertyType) {
  8092. case 0: // Value
  8093. dest[property] = sourceProperty;
  8094. break;
  8095. case 1: // Texture
  8096. if (scene) {
  8097. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8098. }
  8099. break;
  8100. case 2: // Color3
  8101. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8102. break;
  8103. case 3: // FresnelParameters
  8104. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8105. break;
  8106. case 4: // Vector2
  8107. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8108. break;
  8109. case 5: // Vector3
  8110. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8111. break;
  8112. case 6: // Mesh reference
  8113. if (scene) {
  8114. dest[property] = scene.getLastMeshByID(sourceProperty);
  8115. }
  8116. break;
  8117. case 7: // Color Curves
  8118. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8119. break;
  8120. case 8: // Color 4
  8121. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8122. break;
  8123. case 9: // Image Processing
  8124. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8125. break;
  8126. case 10: // Quaternion
  8127. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8128. break;
  8129. case 11: // Camera reference
  8130. if (scene) {
  8131. dest[property] = scene.getCameraByID(sourceProperty);
  8132. }
  8133. break;
  8134. }
  8135. }
  8136. }
  8137. return destination;
  8138. };
  8139. SerializationHelper.Clone = function (creationFunction, source) {
  8140. return _copySource(creationFunction, source, false);
  8141. };
  8142. SerializationHelper.Instanciate = function (creationFunction, source) {
  8143. return _copySource(creationFunction, source, true);
  8144. };
  8145. return SerializationHelper;
  8146. }());
  8147. BABYLON.SerializationHelper = SerializationHelper;
  8148. })(BABYLON || (BABYLON = {}));
  8149. //# sourceMappingURL=babylon.decorators.js.map
  8150. var BABYLON;
  8151. (function (BABYLON) {
  8152. /**
  8153. * Wrapper class for promise with external resolve and reject.
  8154. */
  8155. var Deferred = /** @class */ (function () {
  8156. /**
  8157. * Constructor for this deferred object.
  8158. */
  8159. function Deferred() {
  8160. var _this = this;
  8161. this.promise = new Promise(function (resolve, reject) {
  8162. _this._resolve = resolve;
  8163. _this._reject = reject;
  8164. });
  8165. }
  8166. Object.defineProperty(Deferred.prototype, "resolve", {
  8167. /**
  8168. * The resolve method of the promise associated with this deferred object.
  8169. */
  8170. get: function () {
  8171. return this._resolve;
  8172. },
  8173. enumerable: true,
  8174. configurable: true
  8175. });
  8176. Object.defineProperty(Deferred.prototype, "reject", {
  8177. /**
  8178. * The reject method of the promise associated with this deferred object.
  8179. */
  8180. get: function () {
  8181. return this._reject;
  8182. },
  8183. enumerable: true,
  8184. configurable: true
  8185. });
  8186. return Deferred;
  8187. }());
  8188. BABYLON.Deferred = Deferred;
  8189. })(BABYLON || (BABYLON = {}));
  8190. //# sourceMappingURL=babylon.deferred.js.map
  8191. var BABYLON;
  8192. (function (BABYLON) {
  8193. /**
  8194. * A class serves as a medium between the observable and its observers
  8195. */
  8196. var EventState = /** @class */ (function () {
  8197. /**
  8198. * Create a new EventState
  8199. * @param mask defines the mask associated with this state
  8200. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8201. * @param target defines the original target of the state
  8202. * @param currentTarget defines the current target of the state
  8203. */
  8204. function EventState(mask, skipNextObservers, target, currentTarget) {
  8205. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8206. this.initalize(mask, skipNextObservers, target, currentTarget);
  8207. }
  8208. /**
  8209. * Initialize the current event state
  8210. * @param mask defines the mask associated with this state
  8211. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8212. * @param target defines the original target of the state
  8213. * @param currentTarget defines the current target of the state
  8214. * @returns the current event state
  8215. */
  8216. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8217. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8218. this.mask = mask;
  8219. this.skipNextObservers = skipNextObservers;
  8220. this.target = target;
  8221. this.currentTarget = currentTarget;
  8222. return this;
  8223. };
  8224. return EventState;
  8225. }());
  8226. BABYLON.EventState = EventState;
  8227. /**
  8228. * Represent an Observer registered to a given Observable object.
  8229. */
  8230. var Observer = /** @class */ (function () {
  8231. /**
  8232. * Creates a new observer
  8233. * @param callback defines the callback to call when the observer is notified
  8234. * @param mask defines the mask of the observer (used to filter notifications)
  8235. * @param scope defines the current scope used to restore the JS context
  8236. */
  8237. function Observer(
  8238. /**
  8239. * Defines the callback to call when the observer is notified
  8240. */
  8241. callback,
  8242. /**
  8243. * Defines the mask of the observer (used to filter notifications)
  8244. */
  8245. mask,
  8246. /**
  8247. * Defines the current scope used to restore the JS context
  8248. */
  8249. scope) {
  8250. if (scope === void 0) { scope = null; }
  8251. this.callback = callback;
  8252. this.mask = mask;
  8253. this.scope = scope;
  8254. /** @hidden */
  8255. this._willBeUnregistered = false;
  8256. /**
  8257. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8258. */
  8259. this.unregisterOnNextCall = false;
  8260. }
  8261. return Observer;
  8262. }());
  8263. BABYLON.Observer = Observer;
  8264. /**
  8265. * Represent a list of observers registered to multiple Observables object.
  8266. */
  8267. var MultiObserver = /** @class */ (function () {
  8268. function MultiObserver() {
  8269. }
  8270. /**
  8271. * Release associated resources
  8272. */
  8273. MultiObserver.prototype.dispose = function () {
  8274. if (this._observers && this._observables) {
  8275. for (var index = 0; index < this._observers.length; index++) {
  8276. this._observables[index].remove(this._observers[index]);
  8277. }
  8278. }
  8279. this._observers = null;
  8280. this._observables = null;
  8281. };
  8282. /**
  8283. * Raise a callback when one of the observable will notify
  8284. * @param observables defines a list of observables to watch
  8285. * @param callback defines the callback to call on notification
  8286. * @param mask defines the mask used to filter notifications
  8287. * @param scope defines the current scope used to restore the JS context
  8288. * @returns the new MultiObserver
  8289. */
  8290. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8291. if (mask === void 0) { mask = -1; }
  8292. if (scope === void 0) { scope = null; }
  8293. var result = new MultiObserver();
  8294. result._observers = new Array();
  8295. result._observables = observables;
  8296. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8297. var observable = observables_1[_i];
  8298. var observer = observable.add(callback, mask, false, scope);
  8299. if (observer) {
  8300. result._observers.push(observer);
  8301. }
  8302. }
  8303. return result;
  8304. };
  8305. return MultiObserver;
  8306. }());
  8307. BABYLON.MultiObserver = MultiObserver;
  8308. /**
  8309. * The Observable class is a simple implementation of the Observable pattern.
  8310. *
  8311. * 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.
  8312. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8313. * 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).
  8314. * 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.
  8315. */
  8316. var Observable = /** @class */ (function () {
  8317. /**
  8318. * Creates a new observable
  8319. * @param onObserverAdded defines a callback to call when a new observer is added
  8320. */
  8321. function Observable(onObserverAdded) {
  8322. this._observers = new Array();
  8323. this._eventState = new EventState(0);
  8324. if (onObserverAdded) {
  8325. this._onObserverAdded = onObserverAdded;
  8326. }
  8327. }
  8328. /**
  8329. * Create a new Observer with the specified callback
  8330. * @param callback the callback that will be executed for that Observer
  8331. * @param mask the mask used to filter observers
  8332. * @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.
  8333. * @param scope optional scope for the callback to be called from
  8334. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8335. * @returns the new observer created for the callback
  8336. */
  8337. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8338. if (mask === void 0) { mask = -1; }
  8339. if (insertFirst === void 0) { insertFirst = false; }
  8340. if (scope === void 0) { scope = null; }
  8341. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8342. if (!callback) {
  8343. return null;
  8344. }
  8345. var observer = new Observer(callback, mask, scope);
  8346. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8347. if (insertFirst) {
  8348. this._observers.unshift(observer);
  8349. }
  8350. else {
  8351. this._observers.push(observer);
  8352. }
  8353. if (this._onObserverAdded) {
  8354. this._onObserverAdded(observer);
  8355. }
  8356. return observer;
  8357. };
  8358. /**
  8359. * Create a new Observer with the specified callback and unregisters after the next notification
  8360. * @param callback the callback that will be executed for that Observer
  8361. * @returns the new observer created for the callback
  8362. */
  8363. Observable.prototype.addOnce = function (callback) {
  8364. return this.add(callback, undefined, undefined, undefined, true);
  8365. };
  8366. /**
  8367. * Remove an Observer from the Observable object
  8368. * @param observer the instance of the Observer to remove
  8369. * @returns false if it doesn't belong to this Observable
  8370. */
  8371. Observable.prototype.remove = function (observer) {
  8372. if (!observer) {
  8373. return false;
  8374. }
  8375. var index = this._observers.indexOf(observer);
  8376. if (index !== -1) {
  8377. this._deferUnregister(observer);
  8378. return true;
  8379. }
  8380. return false;
  8381. };
  8382. /**
  8383. * Remove a callback from the Observable object
  8384. * @param callback the callback to remove
  8385. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8386. * @returns false if it doesn't belong to this Observable
  8387. */
  8388. Observable.prototype.removeCallback = function (callback, scope) {
  8389. for (var index = 0; index < this._observers.length; index++) {
  8390. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8391. this._deferUnregister(this._observers[index]);
  8392. return true;
  8393. }
  8394. }
  8395. return false;
  8396. };
  8397. Observable.prototype._deferUnregister = function (observer) {
  8398. var _this = this;
  8399. observer.unregisterOnNextCall = false;
  8400. observer._willBeUnregistered = true;
  8401. BABYLON.Tools.SetImmediate(function () {
  8402. _this._remove(observer);
  8403. });
  8404. };
  8405. // This should only be called when not iterating over _observers to avoid callback skipping.
  8406. // Removes an observer from the _observer Array.
  8407. Observable.prototype._remove = function (observer) {
  8408. if (!observer) {
  8409. return false;
  8410. }
  8411. var index = this._observers.indexOf(observer);
  8412. if (index !== -1) {
  8413. this._observers.splice(index, 1);
  8414. return true;
  8415. }
  8416. return false;
  8417. };
  8418. /**
  8419. * Notify all Observers by calling their respective callback with the given data
  8420. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8421. * @param eventData defines the data to send to all observers
  8422. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8423. * @param target defines the original target of the state
  8424. * @param currentTarget defines the current target of the state
  8425. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8426. */
  8427. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8428. if (mask === void 0) { mask = -1; }
  8429. if (!this._observers.length) {
  8430. return true;
  8431. }
  8432. var state = this._eventState;
  8433. state.mask = mask;
  8434. state.target = target;
  8435. state.currentTarget = currentTarget;
  8436. state.skipNextObservers = false;
  8437. state.lastReturnValue = eventData;
  8438. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8439. var obs = _a[_i];
  8440. if (obs._willBeUnregistered) {
  8441. continue;
  8442. }
  8443. if (obs.mask & mask) {
  8444. if (obs.scope) {
  8445. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8446. }
  8447. else {
  8448. state.lastReturnValue = obs.callback(eventData, state);
  8449. }
  8450. if (obs.unregisterOnNextCall) {
  8451. this._deferUnregister(obs);
  8452. }
  8453. }
  8454. if (state.skipNextObservers) {
  8455. return false;
  8456. }
  8457. }
  8458. return true;
  8459. };
  8460. /**
  8461. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8462. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8463. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8464. * and it is crucial that all callbacks will be executed.
  8465. * The order of the callbacks is kept, callbacks are not executed parallel.
  8466. *
  8467. * @param eventData The data to be sent to each callback
  8468. * @param mask is used to filter observers defaults to -1
  8469. * @param target defines the callback target (see EventState)
  8470. * @param currentTarget defines he current object in the bubbling phase
  8471. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8472. */
  8473. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8474. var _this = this;
  8475. if (mask === void 0) { mask = -1; }
  8476. // create an empty promise
  8477. var p = Promise.resolve(eventData);
  8478. // no observers? return this promise.
  8479. if (!this._observers.length) {
  8480. return p;
  8481. }
  8482. var state = this._eventState;
  8483. state.mask = mask;
  8484. state.target = target;
  8485. state.currentTarget = currentTarget;
  8486. state.skipNextObservers = false;
  8487. // execute one callback after another (not using Promise.all, the order is important)
  8488. this._observers.forEach(function (obs) {
  8489. if (state.skipNextObservers) {
  8490. return;
  8491. }
  8492. if (obs._willBeUnregistered) {
  8493. return;
  8494. }
  8495. if (obs.mask & mask) {
  8496. if (obs.scope) {
  8497. p = p.then(function (lastReturnedValue) {
  8498. state.lastReturnValue = lastReturnedValue;
  8499. return obs.callback.apply(obs.scope, [eventData, state]);
  8500. });
  8501. }
  8502. else {
  8503. p = p.then(function (lastReturnedValue) {
  8504. state.lastReturnValue = lastReturnedValue;
  8505. return obs.callback(eventData, state);
  8506. });
  8507. }
  8508. if (obs.unregisterOnNextCall) {
  8509. _this._deferUnregister(obs);
  8510. }
  8511. }
  8512. });
  8513. // return the eventData
  8514. return p.then(function () { return eventData; });
  8515. };
  8516. /**
  8517. * Notify a specific observer
  8518. * @param observer defines the observer to notify
  8519. * @param eventData defines the data to be sent to each callback
  8520. * @param mask is used to filter observers defaults to -1
  8521. */
  8522. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8523. if (mask === void 0) { mask = -1; }
  8524. var state = this._eventState;
  8525. state.mask = mask;
  8526. state.skipNextObservers = false;
  8527. observer.callback(eventData, state);
  8528. };
  8529. /**
  8530. * Gets a boolean indicating if the observable has at least one observer
  8531. * @returns true is the Observable has at least one Observer registered
  8532. */
  8533. Observable.prototype.hasObservers = function () {
  8534. return this._observers.length > 0;
  8535. };
  8536. /**
  8537. * Clear the list of observers
  8538. */
  8539. Observable.prototype.clear = function () {
  8540. this._observers = new Array();
  8541. this._onObserverAdded = null;
  8542. };
  8543. /**
  8544. * Clone the current observable
  8545. * @returns a new observable
  8546. */
  8547. Observable.prototype.clone = function () {
  8548. var result = new Observable();
  8549. result._observers = this._observers.slice(0);
  8550. return result;
  8551. };
  8552. /**
  8553. * Does this observable handles observer registered with a given mask
  8554. * @param mask defines the mask to be tested
  8555. * @return whether or not one observer registered with the given mask is handeled
  8556. **/
  8557. Observable.prototype.hasSpecificMask = function (mask) {
  8558. if (mask === void 0) { mask = -1; }
  8559. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8560. var obs = _a[_i];
  8561. if (obs.mask & mask || obs.mask === mask) {
  8562. return true;
  8563. }
  8564. }
  8565. return false;
  8566. };
  8567. return Observable;
  8568. }());
  8569. BABYLON.Observable = Observable;
  8570. })(BABYLON || (BABYLON = {}));
  8571. //# sourceMappingURL=babylon.observable.js.map
  8572. var BABYLON;
  8573. (function (BABYLON) {
  8574. /**
  8575. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8576. */
  8577. var SmartArray = /** @class */ (function () {
  8578. /**
  8579. * Instantiates a Smart Array.
  8580. * @param capacity defines the default capacity of the array.
  8581. */
  8582. function SmartArray(capacity) {
  8583. /**
  8584. * The active length of the array.
  8585. */
  8586. this.length = 0;
  8587. this.data = new Array(capacity);
  8588. this._id = SmartArray._GlobalId++;
  8589. }
  8590. /**
  8591. * Pushes a value at the end of the active data.
  8592. * @param value defines the object to push in the array.
  8593. */
  8594. SmartArray.prototype.push = function (value) {
  8595. this.data[this.length++] = value;
  8596. if (this.length > this.data.length) {
  8597. this.data.length *= 2;
  8598. }
  8599. };
  8600. /**
  8601. * Iterates over the active data and apply the lambda to them.
  8602. * @param func defines the action to apply on each value.
  8603. */
  8604. SmartArray.prototype.forEach = function (func) {
  8605. for (var index = 0; index < this.length; index++) {
  8606. func(this.data[index]);
  8607. }
  8608. };
  8609. /**
  8610. * Sorts the full sets of data.
  8611. * @param compareFn defines the comparison function to apply.
  8612. */
  8613. SmartArray.prototype.sort = function (compareFn) {
  8614. this.data.sort(compareFn);
  8615. };
  8616. /**
  8617. * Resets the active data to an empty array.
  8618. */
  8619. SmartArray.prototype.reset = function () {
  8620. this.length = 0;
  8621. };
  8622. /**
  8623. * Releases all the data from the array as well as the array.
  8624. */
  8625. SmartArray.prototype.dispose = function () {
  8626. this.reset();
  8627. if (this.data) {
  8628. this.data.length = 0;
  8629. this.data = [];
  8630. }
  8631. };
  8632. /**
  8633. * Concats the active data with a given array.
  8634. * @param array defines the data to concatenate with.
  8635. */
  8636. SmartArray.prototype.concat = function (array) {
  8637. if (array.length === 0) {
  8638. return;
  8639. }
  8640. if (this.length + array.length > this.data.length) {
  8641. this.data.length = (this.length + array.length) * 2;
  8642. }
  8643. for (var index = 0; index < array.length; index++) {
  8644. this.data[this.length++] = (array.data || array)[index];
  8645. }
  8646. };
  8647. /**
  8648. * Returns the position of a value in the active data.
  8649. * @param value defines the value to find the index for
  8650. * @returns the index if found in the active data otherwise -1
  8651. */
  8652. SmartArray.prototype.indexOf = function (value) {
  8653. var position = this.data.indexOf(value);
  8654. if (position >= this.length) {
  8655. return -1;
  8656. }
  8657. return position;
  8658. };
  8659. /**
  8660. * Returns whether an element is part of the active data.
  8661. * @param value defines the value to look for
  8662. * @returns true if found in the active data otherwise false
  8663. */
  8664. SmartArray.prototype.contains = function (value) {
  8665. return this.indexOf(value) !== -1;
  8666. };
  8667. // Statics
  8668. SmartArray._GlobalId = 0;
  8669. return SmartArray;
  8670. }());
  8671. BABYLON.SmartArray = SmartArray;
  8672. /**
  8673. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8674. * The data in this array can only be present once
  8675. */
  8676. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8677. __extends(SmartArrayNoDuplicate, _super);
  8678. function SmartArrayNoDuplicate() {
  8679. var _this = _super !== null && _super.apply(this, arguments) || this;
  8680. _this._duplicateId = 0;
  8681. return _this;
  8682. }
  8683. /**
  8684. * Pushes a value at the end of the active data.
  8685. * THIS DOES NOT PREVENT DUPPLICATE DATA
  8686. * @param value defines the object to push in the array.
  8687. */
  8688. SmartArrayNoDuplicate.prototype.push = function (value) {
  8689. _super.prototype.push.call(this, value);
  8690. if (!value.__smartArrayFlags) {
  8691. value.__smartArrayFlags = {};
  8692. }
  8693. value.__smartArrayFlags[this._id] = this._duplicateId;
  8694. };
  8695. /**
  8696. * Pushes a value at the end of the active data.
  8697. * If the data is already present, it won t be added again
  8698. * @param value defines the object to push in the array.
  8699. * @returns true if added false if it was already present
  8700. */
  8701. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8702. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8703. return false;
  8704. }
  8705. this.push(value);
  8706. return true;
  8707. };
  8708. /**
  8709. * Resets the active data to an empty array.
  8710. */
  8711. SmartArrayNoDuplicate.prototype.reset = function () {
  8712. _super.prototype.reset.call(this);
  8713. this._duplicateId++;
  8714. };
  8715. /**
  8716. * Concats the active data with a given array.
  8717. * This ensures no dupplicate will be present in the result.
  8718. * @param array defines the data to concatenate with.
  8719. */
  8720. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8721. if (array.length === 0) {
  8722. return;
  8723. }
  8724. if (this.length + array.length > this.data.length) {
  8725. this.data.length = (this.length + array.length) * 2;
  8726. }
  8727. for (var index = 0; index < array.length; index++) {
  8728. var item = (array.data || array)[index];
  8729. this.pushNoDuplicate(item);
  8730. }
  8731. };
  8732. return SmartArrayNoDuplicate;
  8733. }(SmartArray));
  8734. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8735. })(BABYLON || (BABYLON = {}));
  8736. //# sourceMappingURL=babylon.smartArray.js.map
  8737. var BABYLON;
  8738. (function (BABYLON) {
  8739. /** Class used to store color4 gradient */
  8740. var ColorGradient = /** @class */ (function () {
  8741. function ColorGradient() {
  8742. }
  8743. /**
  8744. * Will get a color picked randomly between color1 and color2.
  8745. * If color2 is undefined then color1 will be used
  8746. * @param result defines the target Color4 to store the result in
  8747. */
  8748. ColorGradient.prototype.getColorToRef = function (result) {
  8749. if (!this.color2) {
  8750. result.copyFrom(this.color1);
  8751. return;
  8752. }
  8753. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8754. };
  8755. return ColorGradient;
  8756. }());
  8757. BABYLON.ColorGradient = ColorGradient;
  8758. /** Class used to store color 3 gradient */
  8759. var Color3Gradient = /** @class */ (function () {
  8760. function Color3Gradient() {
  8761. }
  8762. return Color3Gradient;
  8763. }());
  8764. BABYLON.Color3Gradient = Color3Gradient;
  8765. /** Class used to store factor gradient */
  8766. var FactorGradient = /** @class */ (function () {
  8767. function FactorGradient() {
  8768. }
  8769. /**
  8770. * Will get a number picked randomly between factor1 and factor2.
  8771. * If factor2 is undefined then factor1 will be used
  8772. * @returns the picked number
  8773. */
  8774. FactorGradient.prototype.getFactor = function () {
  8775. if (this.factor2 === undefined) {
  8776. return this.factor1;
  8777. }
  8778. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8779. };
  8780. return FactorGradient;
  8781. }());
  8782. BABYLON.FactorGradient = FactorGradient;
  8783. /**
  8784. * Application error to support additional information when loading a file
  8785. */
  8786. var LoadFileError = /** @class */ (function (_super) {
  8787. __extends(LoadFileError, _super);
  8788. /**
  8789. * Creates a new LoadFileError
  8790. * @param message defines the message of the error
  8791. * @param request defines the optional XHR request
  8792. */
  8793. function LoadFileError(message, request) {
  8794. var _this = _super.call(this, message) || this;
  8795. _this.request = request;
  8796. _this.name = "LoadFileError";
  8797. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8798. return _this;
  8799. }
  8800. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8801. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8802. // Polyfill for Object.setPrototypeOf if necessary.
  8803. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8804. return LoadFileError;
  8805. }(Error));
  8806. BABYLON.LoadFileError = LoadFileError;
  8807. /**
  8808. * Class used to define a retry strategy when error happens while loading assets
  8809. */
  8810. var RetryStrategy = /** @class */ (function () {
  8811. function RetryStrategy() {
  8812. }
  8813. /**
  8814. * Function used to defines an exponential back off strategy
  8815. * @param maxRetries defines the maximum number of retries (3 by default)
  8816. * @param baseInterval defines the interval between retries
  8817. * @returns the strategy function to use
  8818. */
  8819. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8820. if (maxRetries === void 0) { maxRetries = 3; }
  8821. if (baseInterval === void 0) { baseInterval = 500; }
  8822. return function (url, request, retryIndex) {
  8823. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8824. return -1;
  8825. }
  8826. return Math.pow(2, retryIndex) * baseInterval;
  8827. };
  8828. };
  8829. return RetryStrategy;
  8830. }());
  8831. BABYLON.RetryStrategy = RetryStrategy;
  8832. // Screenshots
  8833. var screenshotCanvas;
  8834. var cloneValue = function (source, destinationObject) {
  8835. if (!source)
  8836. return null;
  8837. if (source instanceof BABYLON.Mesh) {
  8838. return null;
  8839. }
  8840. if (source instanceof BABYLON.SubMesh) {
  8841. return source.clone(destinationObject);
  8842. }
  8843. else if (source.clone) {
  8844. return source.clone();
  8845. }
  8846. return null;
  8847. };
  8848. /**
  8849. * Class containing a set of static utilities functions
  8850. */
  8851. var Tools = /** @class */ (function () {
  8852. function Tools() {
  8853. }
  8854. /**
  8855. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8856. * @param u defines the coordinate on X axis
  8857. * @param v defines the coordinate on Y axis
  8858. * @param width defines the width of the source data
  8859. * @param height defines the height of the source data
  8860. * @param pixels defines the source byte array
  8861. * @param color defines the output color
  8862. */
  8863. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8864. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8865. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8866. var position = (wrappedU + wrappedV * width) * 4;
  8867. color.r = pixels[position] / 255;
  8868. color.g = pixels[position + 1] / 255;
  8869. color.b = pixels[position + 2] / 255;
  8870. color.a = pixels[position + 3] / 255;
  8871. };
  8872. /**
  8873. * Interpolates between a and b via alpha
  8874. * @param a The lower value (returned when alpha = 0)
  8875. * @param b The upper value (returned when alpha = 1)
  8876. * @param alpha The interpolation-factor
  8877. * @return The mixed value
  8878. */
  8879. Tools.Mix = function (a, b, alpha) {
  8880. return a * (1 - alpha) + b * alpha;
  8881. };
  8882. /**
  8883. * Tries to instantiate a new object from a given class name
  8884. * @param className defines the class name to instantiate
  8885. * @returns the new object or null if the system was not able to do the instantiation
  8886. */
  8887. Tools.Instantiate = function (className) {
  8888. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8889. return Tools.RegisteredExternalClasses[className];
  8890. }
  8891. var arr = className.split(".");
  8892. var fn = (window || this);
  8893. for (var i = 0, len = arr.length; i < len; i++) {
  8894. fn = fn[arr[i]];
  8895. }
  8896. if (typeof fn !== "function") {
  8897. return null;
  8898. }
  8899. return fn;
  8900. };
  8901. /**
  8902. * Provides a slice function that will work even on IE
  8903. * @param data defines the array to slice
  8904. * @param start defines the start of the data (optional)
  8905. * @param end defines the end of the data (optional)
  8906. * @returns the new sliced array
  8907. */
  8908. Tools.Slice = function (data, start, end) {
  8909. if (data.slice) {
  8910. return data.slice(start, end);
  8911. }
  8912. return Array.prototype.slice.call(data, start, end);
  8913. };
  8914. /**
  8915. * Polyfill for setImmediate
  8916. * @param action defines the action to execute after the current execution block
  8917. */
  8918. Tools.SetImmediate = function (action) {
  8919. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8920. window.setImmediate(action);
  8921. }
  8922. else {
  8923. setTimeout(action, 1);
  8924. }
  8925. };
  8926. /**
  8927. * Function indicating if a number is an exponent of 2
  8928. * @param value defines the value to test
  8929. * @returns true if the value is an exponent of 2
  8930. */
  8931. Tools.IsExponentOfTwo = function (value) {
  8932. var count = 1;
  8933. do {
  8934. count *= 2;
  8935. } while (count < value);
  8936. return count === value;
  8937. };
  8938. /**
  8939. * Returns the nearest 32-bit single precision float representation of a Number
  8940. * @param value A Number. If the parameter is of a different type, it will get converted
  8941. * to a number or to NaN if it cannot be converted
  8942. * @returns number
  8943. */
  8944. Tools.FloatRound = function (value) {
  8945. if (Math.fround) {
  8946. return Math.fround(value);
  8947. }
  8948. return (Tools._tmpFloatArray[0] = value);
  8949. };
  8950. /**
  8951. * Find the next highest power of two.
  8952. * @param x Number to start search from.
  8953. * @return Next highest power of two.
  8954. */
  8955. Tools.CeilingPOT = function (x) {
  8956. x--;
  8957. x |= x >> 1;
  8958. x |= x >> 2;
  8959. x |= x >> 4;
  8960. x |= x >> 8;
  8961. x |= x >> 16;
  8962. x++;
  8963. return x;
  8964. };
  8965. /**
  8966. * Find the next lowest power of two.
  8967. * @param x Number to start search from.
  8968. * @return Next lowest power of two.
  8969. */
  8970. Tools.FloorPOT = function (x) {
  8971. x = x | (x >> 1);
  8972. x = x | (x >> 2);
  8973. x = x | (x >> 4);
  8974. x = x | (x >> 8);
  8975. x = x | (x >> 16);
  8976. return x - (x >> 1);
  8977. };
  8978. /**
  8979. * Find the nearest power of two.
  8980. * @param x Number to start search from.
  8981. * @return Next nearest power of two.
  8982. */
  8983. Tools.NearestPOT = function (x) {
  8984. var c = Tools.CeilingPOT(x);
  8985. var f = Tools.FloorPOT(x);
  8986. return (c - x) > (x - f) ? f : c;
  8987. };
  8988. /**
  8989. * Get the closest exponent of two
  8990. * @param value defines the value to approximate
  8991. * @param max defines the maximum value to return
  8992. * @param mode defines how to define the closest value
  8993. * @returns closest exponent of two of the given value
  8994. */
  8995. Tools.GetExponentOfTwo = function (value, max, mode) {
  8996. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8997. var pot;
  8998. switch (mode) {
  8999. case BABYLON.Engine.SCALEMODE_FLOOR:
  9000. pot = Tools.FloorPOT(value);
  9001. break;
  9002. case BABYLON.Engine.SCALEMODE_NEAREST:
  9003. pot = Tools.NearestPOT(value);
  9004. break;
  9005. case BABYLON.Engine.SCALEMODE_CEILING:
  9006. default:
  9007. pot = Tools.CeilingPOT(value);
  9008. break;
  9009. }
  9010. return Math.min(pot, max);
  9011. };
  9012. /**
  9013. * Extracts the filename from a path
  9014. * @param path defines the path to use
  9015. * @returns the filename
  9016. */
  9017. Tools.GetFilename = function (path) {
  9018. var index = path.lastIndexOf("/");
  9019. if (index < 0)
  9020. return path;
  9021. return path.substring(index + 1);
  9022. };
  9023. /**
  9024. * Extracts the "folder" part of a path (everything before the filename).
  9025. * @param uri The URI to extract the info from
  9026. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  9027. * @returns The "folder" part of the path
  9028. */
  9029. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  9030. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  9031. var index = uri.lastIndexOf("/");
  9032. if (index < 0) {
  9033. if (returnUnchangedIfNoSlash) {
  9034. return uri;
  9035. }
  9036. return "";
  9037. }
  9038. return uri.substring(0, index + 1);
  9039. };
  9040. /**
  9041. * Extracts text content from a DOM element hierarchy
  9042. * @param element defines the root element
  9043. * @returns a string
  9044. */
  9045. Tools.GetDOMTextContent = function (element) {
  9046. var result = "";
  9047. var child = element.firstChild;
  9048. while (child) {
  9049. if (child.nodeType === 3) {
  9050. result += child.textContent;
  9051. }
  9052. child = child.nextSibling;
  9053. }
  9054. return result;
  9055. };
  9056. /**
  9057. * Convert an angle in radians to degrees
  9058. * @param angle defines the angle to convert
  9059. * @returns the angle in degrees
  9060. */
  9061. Tools.ToDegrees = function (angle) {
  9062. return angle * 180 / Math.PI;
  9063. };
  9064. /**
  9065. * Convert an angle in degrees to radians
  9066. * @param angle defines the angle to convert
  9067. * @returns the angle in radians
  9068. */
  9069. Tools.ToRadians = function (angle) {
  9070. return angle * Math.PI / 180;
  9071. };
  9072. /**
  9073. * Encode a buffer to a base64 string
  9074. * @param buffer defines the buffer to encode
  9075. * @returns the encoded string
  9076. */
  9077. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  9078. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  9079. var output = "";
  9080. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  9081. var i = 0;
  9082. var bytes = new Uint8Array(buffer);
  9083. while (i < bytes.length) {
  9084. chr1 = bytes[i++];
  9085. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  9086. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  9087. enc1 = chr1 >> 2;
  9088. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  9089. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  9090. enc4 = chr3 & 63;
  9091. if (isNaN(chr2)) {
  9092. enc3 = enc4 = 64;
  9093. }
  9094. else if (isNaN(chr3)) {
  9095. enc4 = 64;
  9096. }
  9097. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  9098. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  9099. }
  9100. return "data:image/png;base64," + output;
  9101. };
  9102. /**
  9103. * Extracts minimum and maximum values from a list of indexed positions
  9104. * @param positions defines the positions to use
  9105. * @param indices defines the indices to the positions
  9106. * @param indexStart defines the start index
  9107. * @param indexCount defines the end index
  9108. * @param bias defines bias value to add to the result
  9109. * @return minimum and maximum values
  9110. */
  9111. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  9112. if (bias === void 0) { bias = null; }
  9113. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9114. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9115. for (var index = indexStart; index < indexStart + indexCount; index++) {
  9116. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  9117. minimum = BABYLON.Vector3.Minimize(current, minimum);
  9118. maximum = BABYLON.Vector3.Maximize(current, maximum);
  9119. }
  9120. if (bias) {
  9121. minimum.x -= minimum.x * bias.x + bias.y;
  9122. minimum.y -= minimum.y * bias.x + bias.y;
  9123. minimum.z -= minimum.z * bias.x + bias.y;
  9124. maximum.x += maximum.x * bias.x + bias.y;
  9125. maximum.y += maximum.y * bias.x + bias.y;
  9126. maximum.z += maximum.z * bias.x + bias.y;
  9127. }
  9128. return {
  9129. minimum: minimum,
  9130. maximum: maximum
  9131. };
  9132. };
  9133. /**
  9134. * Extracts minimum and maximum values from a list of positions
  9135. * @param positions defines the positions to use
  9136. * @param start defines the start index in the positions array
  9137. * @param count defines the number of positions to handle
  9138. * @param bias defines bias value to add to the result
  9139. * @param stride defines the stride size to use (distance between two positions in the positions array)
  9140. * @return minimum and maximum values
  9141. */
  9142. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  9143. if (bias === void 0) { bias = null; }
  9144. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9145. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9146. if (!stride) {
  9147. stride = 3;
  9148. }
  9149. for (var index = start; index < start + count; index++) {
  9150. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  9151. minimum = BABYLON.Vector3.Minimize(current, minimum);
  9152. maximum = BABYLON.Vector3.Maximize(current, maximum);
  9153. }
  9154. if (bias) {
  9155. minimum.x -= minimum.x * bias.x + bias.y;
  9156. minimum.y -= minimum.y * bias.x + bias.y;
  9157. minimum.z -= minimum.z * bias.x + bias.y;
  9158. maximum.x += maximum.x * bias.x + bias.y;
  9159. maximum.y += maximum.y * bias.x + bias.y;
  9160. maximum.z += maximum.z * bias.x + bias.y;
  9161. }
  9162. return {
  9163. minimum: minimum,
  9164. maximum: maximum
  9165. };
  9166. };
  9167. /**
  9168. * Returns an array if obj is not an array
  9169. * @param obj defines the object to evaluate as an array
  9170. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  9171. * @returns either obj directly if obj is an array or a new array containing obj
  9172. */
  9173. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9174. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9175. return null;
  9176. return Array.isArray(obj) ? obj : [obj];
  9177. };
  9178. /**
  9179. * Gets the pointer prefix to use
  9180. * @returns "pointer" if touch is enabled. Else returns "mouse"
  9181. */
  9182. Tools.GetPointerPrefix = function () {
  9183. var eventPrefix = "pointer";
  9184. // Check if pointer events are supported
  9185. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9186. eventPrefix = "mouse";
  9187. }
  9188. return eventPrefix;
  9189. };
  9190. /**
  9191. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  9192. * @param func - the function to be called
  9193. * @param requester - the object that will request the next frame. Falls back to window.
  9194. * @returns frame number
  9195. */
  9196. Tools.QueueNewFrame = function (func, requester) {
  9197. if (!Tools.IsWindowObjectExist()) {
  9198. return setTimeout(func, 16);
  9199. }
  9200. if (!requester) {
  9201. requester = window;
  9202. }
  9203. if (requester.requestAnimationFrame) {
  9204. return requester.requestAnimationFrame(func);
  9205. }
  9206. else if (requester.msRequestAnimationFrame) {
  9207. return requester.msRequestAnimationFrame(func);
  9208. }
  9209. else if (requester.webkitRequestAnimationFrame) {
  9210. return requester.webkitRequestAnimationFrame(func);
  9211. }
  9212. else if (requester.mozRequestAnimationFrame) {
  9213. return requester.mozRequestAnimationFrame(func);
  9214. }
  9215. else if (requester.oRequestAnimationFrame) {
  9216. return requester.oRequestAnimationFrame(func);
  9217. }
  9218. else {
  9219. return window.setTimeout(func, 16);
  9220. }
  9221. };
  9222. /**
  9223. * Ask the browser to promote the current element to fullscreen rendering mode
  9224. * @param element defines the DOM element to promote
  9225. */
  9226. Tools.RequestFullscreen = function (element) {
  9227. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9228. if (!requestFunction)
  9229. return;
  9230. requestFunction.call(element);
  9231. };
  9232. /**
  9233. * Asks the browser to exit fullscreen mode
  9234. */
  9235. Tools.ExitFullscreen = function () {
  9236. if (document.exitFullscreen) {
  9237. document.exitFullscreen();
  9238. }
  9239. else if (document.mozCancelFullScreen) {
  9240. document.mozCancelFullScreen();
  9241. }
  9242. else if (document.webkitCancelFullScreen) {
  9243. document.webkitCancelFullScreen();
  9244. }
  9245. else if (document.msCancelFullScreen) {
  9246. document.msCancelFullScreen();
  9247. }
  9248. };
  9249. /**
  9250. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  9251. * @param url define the url we are trying
  9252. * @param element define the dom element where to configure the cors policy
  9253. */
  9254. Tools.SetCorsBehavior = function (url, element) {
  9255. if (url && url.indexOf("data:") === 0) {
  9256. return;
  9257. }
  9258. if (Tools.CorsBehavior) {
  9259. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9260. element.crossOrigin = Tools.CorsBehavior;
  9261. }
  9262. else {
  9263. var result = Tools.CorsBehavior(url);
  9264. if (result) {
  9265. element.crossOrigin = result;
  9266. }
  9267. }
  9268. }
  9269. };
  9270. // External files
  9271. /**
  9272. * Removes unwanted characters from an url
  9273. * @param url defines the url to clean
  9274. * @returns the cleaned url
  9275. */
  9276. Tools.CleanUrl = function (url) {
  9277. url = url.replace(/#/mg, "%23");
  9278. return url;
  9279. };
  9280. /**
  9281. * Loads an image as an HTMLImageElement.
  9282. * @param input url string, ArrayBuffer, or Blob to load
  9283. * @param onLoad callback called when the image successfully loads
  9284. * @param onError callback called when the image fails to load
  9285. * @param database database for caching
  9286. * @returns the HTMLImageElement of the loaded image
  9287. */
  9288. Tools.LoadImage = function (input, onLoad, onError, database) {
  9289. var url;
  9290. var usingObjectURL = false;
  9291. if (input instanceof ArrayBuffer) {
  9292. url = URL.createObjectURL(new Blob([input]));
  9293. usingObjectURL = true;
  9294. }
  9295. else if (input instanceof Blob) {
  9296. url = URL.createObjectURL(input);
  9297. usingObjectURL = true;
  9298. }
  9299. else {
  9300. url = Tools.CleanUrl(input);
  9301. url = Tools.PreprocessUrl(input);
  9302. }
  9303. var img = new Image();
  9304. Tools.SetCorsBehavior(url, img);
  9305. var loadHandler = function () {
  9306. if (usingObjectURL && img.src) {
  9307. URL.revokeObjectURL(img.src);
  9308. }
  9309. img.removeEventListener("load", loadHandler);
  9310. img.removeEventListener("error", errorHandler);
  9311. onLoad(img);
  9312. };
  9313. var errorHandler = function (err) {
  9314. if (usingObjectURL && img.src) {
  9315. URL.revokeObjectURL(img.src);
  9316. }
  9317. img.removeEventListener("load", loadHandler);
  9318. img.removeEventListener("error", errorHandler);
  9319. Tools.Error("Error while trying to load image: " + input);
  9320. if (onError) {
  9321. onError("Error while trying to load image: " + input, err);
  9322. }
  9323. };
  9324. img.addEventListener("load", loadHandler);
  9325. img.addEventListener("error", errorHandler);
  9326. var noIndexedDB = function () {
  9327. img.src = url;
  9328. };
  9329. var loadFromIndexedDB = function () {
  9330. if (database) {
  9331. database.loadImageFromDB(url, img);
  9332. }
  9333. };
  9334. //ANY database to do!
  9335. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9336. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9337. }
  9338. else {
  9339. if (url.indexOf("file:") !== -1) {
  9340. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9341. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9342. try {
  9343. var blobURL;
  9344. try {
  9345. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9346. }
  9347. catch (ex) {
  9348. // Chrome doesn't support oneTimeOnly parameter
  9349. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9350. }
  9351. img.src = blobURL;
  9352. usingObjectURL = true;
  9353. }
  9354. catch (e) {
  9355. img.src = "";
  9356. }
  9357. return img;
  9358. }
  9359. }
  9360. noIndexedDB();
  9361. }
  9362. return img;
  9363. };
  9364. /**
  9365. * Loads a file
  9366. * @param url url string, ArrayBuffer, or Blob to load
  9367. * @param onSuccess callback called when the file successfully loads
  9368. * @param onProgress callback called while file is loading (if the server supports this mode)
  9369. * @param database database for caching
  9370. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  9371. * @param onError callback called when the file fails to load
  9372. * @returns a file request object
  9373. */
  9374. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9375. url = Tools.CleanUrl(url);
  9376. url = Tools.PreprocessUrl(url);
  9377. // If file and file input are set
  9378. if (url.indexOf("file:") !== -1) {
  9379. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9380. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9381. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9382. }
  9383. }
  9384. var loadUrl = Tools.BaseUrl + url;
  9385. var aborted = false;
  9386. var fileRequest = {
  9387. onCompleteObservable: new BABYLON.Observable(),
  9388. abort: function () { return aborted = true; },
  9389. };
  9390. var requestFile = function () {
  9391. var request = new XMLHttpRequest();
  9392. var retryHandle = null;
  9393. fileRequest.abort = function () {
  9394. aborted = true;
  9395. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9396. request.abort();
  9397. }
  9398. if (retryHandle !== null) {
  9399. clearTimeout(retryHandle);
  9400. retryHandle = null;
  9401. }
  9402. };
  9403. var retryLoop = function (retryIndex) {
  9404. request.open('GET', loadUrl, true);
  9405. if (useArrayBuffer) {
  9406. request.responseType = "arraybuffer";
  9407. }
  9408. if (onProgress) {
  9409. request.addEventListener("progress", onProgress);
  9410. }
  9411. var onLoadEnd = function () {
  9412. request.removeEventListener("loadend", onLoadEnd);
  9413. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9414. fileRequest.onCompleteObservable.clear();
  9415. };
  9416. request.addEventListener("loadend", onLoadEnd);
  9417. var onReadyStateChange = function () {
  9418. if (aborted) {
  9419. return;
  9420. }
  9421. // In case of undefined state in some browsers.
  9422. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9423. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9424. request.removeEventListener("readystatechange", onReadyStateChange);
  9425. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9426. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9427. return;
  9428. }
  9429. var retryStrategy = Tools.DefaultRetryStrategy;
  9430. if (retryStrategy) {
  9431. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9432. if (waitTime !== -1) {
  9433. // Prevent the request from completing for retry.
  9434. request.removeEventListener("loadend", onLoadEnd);
  9435. request = new XMLHttpRequest();
  9436. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9437. return;
  9438. }
  9439. }
  9440. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9441. if (onError) {
  9442. onError(request, e);
  9443. }
  9444. else {
  9445. throw e;
  9446. }
  9447. }
  9448. };
  9449. request.addEventListener("readystatechange", onReadyStateChange);
  9450. request.send();
  9451. };
  9452. retryLoop(0);
  9453. };
  9454. // Caching all files
  9455. if (database && database.enableSceneOffline) {
  9456. var noIndexedDB_1 = function (request) {
  9457. if (request && request.status > 400) {
  9458. if (onError) {
  9459. onError(request);
  9460. }
  9461. }
  9462. else {
  9463. if (!aborted) {
  9464. requestFile();
  9465. }
  9466. }
  9467. };
  9468. var loadFromIndexedDB = function () {
  9469. // TODO: database needs to support aborting and should return a IFileRequest
  9470. if (aborted) {
  9471. return;
  9472. }
  9473. if (database) {
  9474. database.loadFileFromDB(url, function (data) {
  9475. if (!aborted) {
  9476. onSuccess(data);
  9477. }
  9478. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9479. }, onProgress ? function (event) {
  9480. if (!aborted) {
  9481. onProgress(event);
  9482. }
  9483. } : undefined, noIndexedDB_1, useArrayBuffer);
  9484. }
  9485. };
  9486. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9487. }
  9488. else {
  9489. requestFile();
  9490. }
  9491. return fileRequest;
  9492. };
  9493. /**
  9494. * Load a script (identified by an url). When the url returns, the
  9495. * content of this file is added into a new script element, attached to the DOM (body element)
  9496. * @param scriptUrl defines the url of the script to laod
  9497. * @param onSuccess defines the callback called when the script is loaded
  9498. * @param onError defines the callback to call if an error occurs
  9499. */
  9500. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9501. if (!Tools.IsWindowObjectExist()) {
  9502. return;
  9503. }
  9504. var head = document.getElementsByTagName('head')[0];
  9505. var script = document.createElement('script');
  9506. script.type = 'text/javascript';
  9507. script.src = scriptUrl;
  9508. script.onload = function () {
  9509. if (onSuccess) {
  9510. onSuccess();
  9511. }
  9512. };
  9513. script.onerror = function (e) {
  9514. if (onError) {
  9515. onError("Unable to load script '" + scriptUrl + "'", e);
  9516. }
  9517. };
  9518. head.appendChild(script);
  9519. };
  9520. /**
  9521. * Loads a file from a blob
  9522. * @param fileToLoad defines the blob to use
  9523. * @param callback defines the callback to call when data is loaded
  9524. * @param progressCallback defines the callback to call during loading process
  9525. * @returns a file request object
  9526. */
  9527. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9528. var reader = new FileReader();
  9529. var request = {
  9530. onCompleteObservable: new BABYLON.Observable(),
  9531. abort: function () { return reader.abort(); },
  9532. };
  9533. reader.onloadend = function (e) {
  9534. request.onCompleteObservable.notifyObservers(request);
  9535. };
  9536. reader.onload = function (e) {
  9537. //target doesn't have result from ts 1.3
  9538. callback(e.target['result']);
  9539. };
  9540. reader.onprogress = progressCallback;
  9541. reader.readAsDataURL(fileToLoad);
  9542. return request;
  9543. };
  9544. /**
  9545. * Loads a file
  9546. * @param fileToLoad defines the file to load
  9547. * @param callback defines the callback to call when data is loaded
  9548. * @param progressCallBack defines the callback to call during loading process
  9549. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  9550. * @returns a file request object
  9551. */
  9552. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9553. var reader = new FileReader();
  9554. var request = {
  9555. onCompleteObservable: new BABYLON.Observable(),
  9556. abort: function () { return reader.abort(); },
  9557. };
  9558. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9559. reader.onerror = function (e) {
  9560. Tools.Log("Error while reading file: " + fileToLoad.name);
  9561. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9562. };
  9563. reader.onload = function (e) {
  9564. //target doesn't have result from ts 1.3
  9565. callback(e.target['result']);
  9566. };
  9567. if (progressCallBack) {
  9568. reader.onprogress = progressCallBack;
  9569. }
  9570. if (!useArrayBuffer) {
  9571. // Asynchronous read
  9572. reader.readAsText(fileToLoad);
  9573. }
  9574. else {
  9575. reader.readAsArrayBuffer(fileToLoad);
  9576. }
  9577. return request;
  9578. };
  9579. /**
  9580. * Creates a data url from a given string content
  9581. * @param content defines the content to convert
  9582. * @returns the new data url link
  9583. */
  9584. Tools.FileAsURL = function (content) {
  9585. var fileBlob = new Blob([content]);
  9586. var url = window.URL || window.webkitURL;
  9587. var link = url.createObjectURL(fileBlob);
  9588. return link;
  9589. };
  9590. /**
  9591. * Format the given number to a specific decimal format
  9592. * @param value defines the number to format
  9593. * @param decimals defines the number of decimals to use
  9594. * @returns the formatted string
  9595. */
  9596. Tools.Format = function (value, decimals) {
  9597. if (decimals === void 0) { decimals = 2; }
  9598. return value.toFixed(decimals);
  9599. };
  9600. /**
  9601. * Checks if a given vector is inside a specific range
  9602. * @param v defines the vector to test
  9603. * @param min defines the minimum range
  9604. * @param max defines the maximum range
  9605. */
  9606. Tools.CheckExtends = function (v, min, max) {
  9607. if (v.x < min.x)
  9608. min.x = v.x;
  9609. if (v.y < min.y)
  9610. min.y = v.y;
  9611. if (v.z < min.z)
  9612. min.z = v.z;
  9613. if (v.x > max.x)
  9614. max.x = v.x;
  9615. if (v.y > max.y)
  9616. max.y = v.y;
  9617. if (v.z > max.z)
  9618. max.z = v.z;
  9619. };
  9620. /**
  9621. * Tries to copy an object by duplicating every property
  9622. * @param source defines the source object
  9623. * @param destination defines the target object
  9624. * @param doNotCopyList defines a list of properties to avoid
  9625. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  9626. */
  9627. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9628. for (var prop in source) {
  9629. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9630. continue;
  9631. }
  9632. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9633. continue;
  9634. }
  9635. var sourceValue = source[prop];
  9636. var typeOfSourceValue = typeof sourceValue;
  9637. if (typeOfSourceValue === "function") {
  9638. continue;
  9639. }
  9640. try {
  9641. if (typeOfSourceValue === "object") {
  9642. if (sourceValue instanceof Array) {
  9643. destination[prop] = [];
  9644. if (sourceValue.length > 0) {
  9645. if (typeof sourceValue[0] == "object") {
  9646. for (var index = 0; index < sourceValue.length; index++) {
  9647. var clonedValue = cloneValue(sourceValue[index], destination);
  9648. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9649. destination[prop].push(clonedValue);
  9650. }
  9651. }
  9652. }
  9653. else {
  9654. destination[prop] = sourceValue.slice(0);
  9655. }
  9656. }
  9657. }
  9658. else {
  9659. destination[prop] = cloneValue(sourceValue, destination);
  9660. }
  9661. }
  9662. else {
  9663. destination[prop] = sourceValue;
  9664. }
  9665. }
  9666. catch (e) {
  9667. // Just ignore error (it could be because of a read-only property)
  9668. }
  9669. }
  9670. };
  9671. /**
  9672. * Gets a boolean indicating if the given object has no own property
  9673. * @param obj defines the object to test
  9674. * @returns true if object has no own property
  9675. */
  9676. Tools.IsEmpty = function (obj) {
  9677. for (var i in obj) {
  9678. if (obj.hasOwnProperty(i)) {
  9679. return false;
  9680. }
  9681. }
  9682. return true;
  9683. };
  9684. /**
  9685. * Function used to register events at window level
  9686. * @param events defines the events to register
  9687. */
  9688. Tools.RegisterTopRootEvents = function (events) {
  9689. for (var index = 0; index < events.length; index++) {
  9690. var event = events[index];
  9691. window.addEventListener(event.name, event.handler, false);
  9692. try {
  9693. if (window.parent) {
  9694. window.parent.addEventListener(event.name, event.handler, false);
  9695. }
  9696. }
  9697. catch (e) {
  9698. // Silently fails...
  9699. }
  9700. }
  9701. };
  9702. /**
  9703. * Function used to unregister events from window level
  9704. * @param events defines the events to unregister
  9705. */
  9706. Tools.UnregisterTopRootEvents = function (events) {
  9707. for (var index = 0; index < events.length; index++) {
  9708. var event = events[index];
  9709. window.removeEventListener(event.name, event.handler);
  9710. try {
  9711. if (window.parent) {
  9712. window.parent.removeEventListener(event.name, event.handler);
  9713. }
  9714. }
  9715. catch (e) {
  9716. // Silently fails...
  9717. }
  9718. }
  9719. };
  9720. /**
  9721. * Dumps the current bound framebuffer
  9722. * @param width defines the rendering width
  9723. * @param height defines the rendering height
  9724. * @param engine defines the hosting engine
  9725. * @param successCallback defines the callback triggered once the data are available
  9726. * @param mimeType defines the mime type of the result
  9727. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  9728. */
  9729. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9730. if (mimeType === void 0) { mimeType = "image/png"; }
  9731. // Read the contents of the framebuffer
  9732. var numberOfChannelsByLine = width * 4;
  9733. var halfHeight = height / 2;
  9734. //Reading datas from WebGL
  9735. var data = engine.readPixels(0, 0, width, height);
  9736. //To flip image on Y axis.
  9737. for (var i = 0; i < halfHeight; i++) {
  9738. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9739. var currentCell = j + i * numberOfChannelsByLine;
  9740. var targetLine = height - i - 1;
  9741. var targetCell = j + targetLine * numberOfChannelsByLine;
  9742. var temp = data[currentCell];
  9743. data[currentCell] = data[targetCell];
  9744. data[targetCell] = temp;
  9745. }
  9746. }
  9747. // Create a 2D canvas to store the result
  9748. if (!screenshotCanvas) {
  9749. screenshotCanvas = document.createElement('canvas');
  9750. }
  9751. screenshotCanvas.width = width;
  9752. screenshotCanvas.height = height;
  9753. var context = screenshotCanvas.getContext('2d');
  9754. if (context) {
  9755. // Copy the pixels to a 2D canvas
  9756. var imageData = context.createImageData(width, height);
  9757. var castData = (imageData.data);
  9758. castData.set(data);
  9759. context.putImageData(imageData, 0, 0);
  9760. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9761. }
  9762. };
  9763. /**
  9764. * Converts the canvas data to blob.
  9765. * This acts as a polyfill for browsers not supporting the to blob function.
  9766. * @param canvas Defines the canvas to extract the data from
  9767. * @param successCallback Defines the callback triggered once the data are available
  9768. * @param mimeType Defines the mime type of the result
  9769. */
  9770. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9771. if (mimeType === void 0) { mimeType = "image/png"; }
  9772. // We need HTMLCanvasElement.toBlob for HD screenshots
  9773. if (!canvas.toBlob) {
  9774. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9775. canvas.toBlob = function (callback, type, quality) {
  9776. var _this = this;
  9777. setTimeout(function () {
  9778. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9779. for (var i = 0; i < len; i++) {
  9780. arr[i] = binStr.charCodeAt(i);
  9781. }
  9782. callback(new Blob([arr]));
  9783. });
  9784. };
  9785. }
  9786. canvas.toBlob(function (blob) {
  9787. successCallback(blob);
  9788. }, mimeType);
  9789. };
  9790. /**
  9791. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9792. * @param successCallback defines the callback triggered once the data are available
  9793. * @param mimeType defines the mime type of the result
  9794. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  9795. */
  9796. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9797. if (mimeType === void 0) { mimeType = "image/png"; }
  9798. if (successCallback) {
  9799. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9800. successCallback(base64Image);
  9801. }
  9802. else {
  9803. this.ToBlob(screenshotCanvas, function (blob) {
  9804. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9805. if (("download" in document.createElement("a"))) {
  9806. if (!fileName) {
  9807. var date = new Date();
  9808. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9809. fileName = "screenshot_" + stringDate + ".png";
  9810. }
  9811. Tools.Download(blob, fileName);
  9812. }
  9813. else {
  9814. var url = URL.createObjectURL(blob);
  9815. var newWindow = window.open("");
  9816. if (!newWindow)
  9817. return;
  9818. var img = newWindow.document.createElement("img");
  9819. img.onload = function () {
  9820. // no longer need to read the blob so it's revoked
  9821. URL.revokeObjectURL(url);
  9822. };
  9823. img.src = url;
  9824. newWindow.document.body.appendChild(img);
  9825. }
  9826. }, mimeType);
  9827. }
  9828. };
  9829. /**
  9830. * Downloads a blob in the browser
  9831. * @param blob defines the blob to download
  9832. * @param fileName defines the name of the downloaded file
  9833. */
  9834. Tools.Download = function (blob, fileName) {
  9835. if (navigator && navigator.msSaveBlob) {
  9836. navigator.msSaveBlob(blob, fileName);
  9837. return;
  9838. }
  9839. var url = window.URL.createObjectURL(blob);
  9840. var a = document.createElement("a");
  9841. document.body.appendChild(a);
  9842. a.style.display = "none";
  9843. a.href = url;
  9844. a.download = fileName;
  9845. a.addEventListener("click", function () {
  9846. if (a.parentElement) {
  9847. a.parentElement.removeChild(a);
  9848. }
  9849. });
  9850. a.click();
  9851. window.URL.revokeObjectURL(url);
  9852. };
  9853. /**
  9854. * Captures a screenshot of the current rendering
  9855. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  9856. * @param engine defines the rendering engine
  9857. * @param camera defines the source camera
  9858. * @param size This parameter can be set to a single number or to an object with the
  9859. * following (optional) properties: precision, width, height. If a single number is passed,
  9860. * it will be used for both width and height. If an object is passed, the screenshot size
  9861. * will be derived from the parameters. The precision property is a multiplier allowing
  9862. * rendering at a higher or lower resolution
  9863. * @param successCallback defines the callback receives a single parameter which contains the
  9864. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9865. * src parameter of an <img> to display it
  9866. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  9867. * Check your browser for supported MIME types
  9868. */
  9869. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9870. if (mimeType === void 0) { mimeType = "image/png"; }
  9871. var width;
  9872. var height;
  9873. // If a precision value is specified
  9874. if (size.precision) {
  9875. width = Math.round(engine.getRenderWidth() * size.precision);
  9876. height = Math.round(width / engine.getAspectRatio(camera));
  9877. }
  9878. else if (size.width && size.height) {
  9879. width = size.width;
  9880. height = size.height;
  9881. }
  9882. //If passing only width, computing height to keep display canvas ratio.
  9883. else if (size.width && !size.height) {
  9884. width = size.width;
  9885. height = Math.round(width / engine.getAspectRatio(camera));
  9886. }
  9887. //If passing only height, computing width to keep display canvas ratio.
  9888. else if (size.height && !size.width) {
  9889. height = size.height;
  9890. width = Math.round(height * engine.getAspectRatio(camera));
  9891. }
  9892. //Assuming here that "size" parameter is a number
  9893. else if (!isNaN(size)) {
  9894. height = size;
  9895. width = size;
  9896. }
  9897. else {
  9898. Tools.Error("Invalid 'size' parameter !");
  9899. return;
  9900. }
  9901. if (!screenshotCanvas) {
  9902. screenshotCanvas = document.createElement('canvas');
  9903. }
  9904. screenshotCanvas.width = width;
  9905. screenshotCanvas.height = height;
  9906. var renderContext = screenshotCanvas.getContext("2d");
  9907. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9908. var newWidth = width;
  9909. var newHeight = newWidth / ratio;
  9910. if (newHeight > height) {
  9911. newHeight = height;
  9912. newWidth = newHeight * ratio;
  9913. }
  9914. var offsetX = Math.max(0, width - newWidth) / 2;
  9915. var offsetY = Math.max(0, height - newHeight) / 2;
  9916. var renderingCanvas = engine.getRenderingCanvas();
  9917. if (renderContext && renderingCanvas) {
  9918. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9919. }
  9920. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9921. };
  9922. /**
  9923. * Generates an image screenshot from the specified camera.
  9924. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  9925. * @param engine The engine to use for rendering
  9926. * @param camera The camera to use for rendering
  9927. * @param size This parameter can be set to a single number or to an object with the
  9928. * following (optional) properties: precision, width, height. If a single number is passed,
  9929. * it will be used for both width and height. If an object is passed, the screenshot size
  9930. * will be derived from the parameters. The precision property is a multiplier allowing
  9931. * rendering at a higher or lower resolution
  9932. * @param successCallback The callback receives a single parameter which contains the
  9933. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9934. * src parameter of an <img> to display it
  9935. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9936. * Check your browser for supported MIME types
  9937. * @param samples Texture samples (default: 1)
  9938. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9939. * @param fileName A name for for the downloaded file.
  9940. */
  9941. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9942. if (mimeType === void 0) { mimeType = "image/png"; }
  9943. if (samples === void 0) { samples = 1; }
  9944. if (antialiasing === void 0) { antialiasing = false; }
  9945. var width;
  9946. var height;
  9947. //If a precision value is specified
  9948. if (size.precision) {
  9949. width = Math.round(engine.getRenderWidth() * size.precision);
  9950. height = Math.round(width / engine.getAspectRatio(camera));
  9951. size = { width: width, height: height };
  9952. }
  9953. else if (size.width && size.height) {
  9954. width = size.width;
  9955. height = size.height;
  9956. }
  9957. //If passing only width, computing height to keep display canvas ratio.
  9958. else if (size.width && !size.height) {
  9959. width = size.width;
  9960. height = Math.round(width / engine.getAspectRatio(camera));
  9961. size = { width: width, height: height };
  9962. }
  9963. //If passing only height, computing width to keep display canvas ratio.
  9964. else if (size.height && !size.width) {
  9965. height = size.height;
  9966. width = Math.round(height * engine.getAspectRatio(camera));
  9967. size = { width: width, height: height };
  9968. }
  9969. //Assuming here that "size" parameter is a number
  9970. else if (!isNaN(size)) {
  9971. height = size;
  9972. width = size;
  9973. }
  9974. else {
  9975. Tools.Error("Invalid 'size' parameter !");
  9976. return;
  9977. }
  9978. var scene = camera.getScene();
  9979. var previousCamera = null;
  9980. if (scene.activeCamera !== camera) {
  9981. previousCamera = scene.activeCamera;
  9982. scene.activeCamera = camera;
  9983. }
  9984. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9985. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9986. texture.renderList = null;
  9987. texture.samples = samples;
  9988. if (antialiasing) {
  9989. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9990. }
  9991. texture.onAfterRenderObservable.add(function () {
  9992. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9993. });
  9994. scene.incrementRenderId();
  9995. scene.resetCachedMaterial();
  9996. texture.render(true);
  9997. texture.dispose();
  9998. if (previousCamera) {
  9999. scene.activeCamera = previousCamera;
  10000. }
  10001. camera.getProjectionMatrix(true); // Force cache refresh;
  10002. };
  10003. /**
  10004. * Validates if xhr data is correct
  10005. * @param xhr defines the request to validate
  10006. * @param dataType defines the expected data type
  10007. * @returns true if data is correct
  10008. */
  10009. Tools.ValidateXHRData = function (xhr, dataType) {
  10010. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  10011. if (dataType === void 0) { dataType = 7; }
  10012. try {
  10013. if (dataType & 1) {
  10014. if (xhr.responseText && xhr.responseText.length > 0) {
  10015. return true;
  10016. }
  10017. else if (dataType === 1) {
  10018. return false;
  10019. }
  10020. }
  10021. if (dataType & 2) {
  10022. // Check header width and height since there is no "TGA" magic number
  10023. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  10024. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  10025. return true;
  10026. }
  10027. else if (dataType === 2) {
  10028. return false;
  10029. }
  10030. }
  10031. if (dataType & 4) {
  10032. // Check for the "DDS" magic number
  10033. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  10034. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  10035. return true;
  10036. }
  10037. else {
  10038. return false;
  10039. }
  10040. }
  10041. }
  10042. catch (e) {
  10043. // Global protection
  10044. }
  10045. return false;
  10046. };
  10047. /**
  10048. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  10049. * Be aware Math.random() could cause collisions, but:
  10050. * "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"
  10051. * @returns a pseudo random id
  10052. */
  10053. Tools.RandomId = function () {
  10054. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  10055. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  10056. return v.toString(16);
  10057. });
  10058. };
  10059. /**
  10060. * Test if the given uri is a base64 string
  10061. * @param uri The uri to test
  10062. * @return True if the uri is a base64 string or false otherwise
  10063. */
  10064. Tools.IsBase64 = function (uri) {
  10065. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  10066. };
  10067. /**
  10068. * Decode the given base64 uri.
  10069. * @param uri The uri to decode
  10070. * @return The decoded base64 data.
  10071. */
  10072. Tools.DecodeBase64 = function (uri) {
  10073. var decodedString = atob(uri.split(",")[1]);
  10074. var bufferLength = decodedString.length;
  10075. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  10076. for (var i = 0; i < bufferLength; i++) {
  10077. bufferView[i] = decodedString.charCodeAt(i);
  10078. }
  10079. return bufferView.buffer;
  10080. };
  10081. Tools._AddLogEntry = function (entry) {
  10082. Tools._LogCache = entry + Tools._LogCache;
  10083. if (Tools.OnNewCacheEntry) {
  10084. Tools.OnNewCacheEntry(entry);
  10085. }
  10086. };
  10087. Tools._FormatMessage = function (message) {
  10088. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  10089. var date = new Date();
  10090. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  10091. };
  10092. Tools._LogDisabled = function (message) {
  10093. // nothing to do
  10094. };
  10095. Tools._LogEnabled = function (message) {
  10096. var formattedMessage = Tools._FormatMessage(message);
  10097. console.log("BJS - " + formattedMessage);
  10098. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  10099. Tools._AddLogEntry(entry);
  10100. };
  10101. Tools._WarnDisabled = function (message) {
  10102. // nothing to do
  10103. };
  10104. Tools._WarnEnabled = function (message) {
  10105. var formattedMessage = Tools._FormatMessage(message);
  10106. console.warn("BJS - " + formattedMessage);
  10107. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  10108. Tools._AddLogEntry(entry);
  10109. };
  10110. Tools._ErrorDisabled = function (message) {
  10111. // nothing to do
  10112. };
  10113. Tools._ErrorEnabled = function (message) {
  10114. Tools.errorsCount++;
  10115. var formattedMessage = Tools._FormatMessage(message);
  10116. console.error("BJS - " + formattedMessage);
  10117. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  10118. Tools._AddLogEntry(entry);
  10119. };
  10120. Object.defineProperty(Tools, "LogCache", {
  10121. /**
  10122. * Gets current log cache (list of logs)
  10123. */
  10124. get: function () {
  10125. return Tools._LogCache;
  10126. },
  10127. enumerable: true,
  10128. configurable: true
  10129. });
  10130. /**
  10131. * Clears the log cache
  10132. */
  10133. Tools.ClearLogCache = function () {
  10134. Tools._LogCache = "";
  10135. Tools.errorsCount = 0;
  10136. };
  10137. Object.defineProperty(Tools, "LogLevels", {
  10138. /**
  10139. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  10140. */
  10141. set: function (level) {
  10142. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  10143. Tools.Log = Tools._LogEnabled;
  10144. }
  10145. else {
  10146. Tools.Log = Tools._LogDisabled;
  10147. }
  10148. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  10149. Tools.Warn = Tools._WarnEnabled;
  10150. }
  10151. else {
  10152. Tools.Warn = Tools._WarnDisabled;
  10153. }
  10154. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  10155. Tools.Error = Tools._ErrorEnabled;
  10156. }
  10157. else {
  10158. Tools.Error = Tools._ErrorDisabled;
  10159. }
  10160. },
  10161. enumerable: true,
  10162. configurable: true
  10163. });
  10164. /**
  10165. * Checks if the loaded document was accessed via `file:`-Protocol.
  10166. * @returns boolean
  10167. */
  10168. Tools.IsFileURL = function () {
  10169. return location.protocol === "file:";
  10170. };
  10171. /**
  10172. * Checks if the window object exists
  10173. * @returns true if the window object exists
  10174. */
  10175. Tools.IsWindowObjectExist = function () {
  10176. return (typeof window) !== "undefined";
  10177. };
  10178. Object.defineProperty(Tools, "PerformanceLogLevel", {
  10179. /**
  10180. * Sets the current performance log level
  10181. */
  10182. set: function (level) {
  10183. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  10184. Tools.StartPerformanceCounter = Tools._StartUserMark;
  10185. Tools.EndPerformanceCounter = Tools._EndUserMark;
  10186. return;
  10187. }
  10188. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  10189. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  10190. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  10191. return;
  10192. }
  10193. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10194. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10195. },
  10196. enumerable: true,
  10197. configurable: true
  10198. });
  10199. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10200. };
  10201. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10202. };
  10203. Tools._StartUserMark = function (counterName, condition) {
  10204. if (condition === void 0) { condition = true; }
  10205. if (!Tools._performance) {
  10206. if (!Tools.IsWindowObjectExist()) {
  10207. return;
  10208. }
  10209. Tools._performance = window.performance;
  10210. }
  10211. if (!condition || !Tools._performance.mark) {
  10212. return;
  10213. }
  10214. Tools._performance.mark(counterName + "-Begin");
  10215. };
  10216. Tools._EndUserMark = function (counterName, condition) {
  10217. if (condition === void 0) { condition = true; }
  10218. if (!condition || !Tools._performance.mark) {
  10219. return;
  10220. }
  10221. Tools._performance.mark(counterName + "-End");
  10222. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10223. };
  10224. Tools._StartPerformanceConsole = function (counterName, condition) {
  10225. if (condition === void 0) { condition = true; }
  10226. if (!condition) {
  10227. return;
  10228. }
  10229. Tools._StartUserMark(counterName, condition);
  10230. if (console.time) {
  10231. console.time(counterName);
  10232. }
  10233. };
  10234. Tools._EndPerformanceConsole = function (counterName, condition) {
  10235. if (condition === void 0) { condition = true; }
  10236. if (!condition) {
  10237. return;
  10238. }
  10239. Tools._EndUserMark(counterName, condition);
  10240. if (console.time) {
  10241. console.timeEnd(counterName);
  10242. }
  10243. };
  10244. Object.defineProperty(Tools, "Now", {
  10245. /**
  10246. * Gets either window.performance.now() if supported or Date.now() else
  10247. */
  10248. get: function () {
  10249. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10250. return window.performance.now();
  10251. }
  10252. return Date.now();
  10253. },
  10254. enumerable: true,
  10255. configurable: true
  10256. });
  10257. /**
  10258. * This method will return the name of the class used to create the instance of the given object.
  10259. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10260. * @param object the object to get the class name from
  10261. * @param isType defines if the object is actually a type
  10262. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  10263. */
  10264. Tools.GetClassName = function (object, isType) {
  10265. if (isType === void 0) { isType = false; }
  10266. var name = null;
  10267. if (!isType && object.getClassName) {
  10268. name = object.getClassName();
  10269. }
  10270. else {
  10271. if (object instanceof Object) {
  10272. var classObj = isType ? object : Object.getPrototypeOf(object);
  10273. name = classObj.constructor["__bjsclassName__"];
  10274. }
  10275. if (!name) {
  10276. name = typeof object;
  10277. }
  10278. }
  10279. return name;
  10280. };
  10281. /**
  10282. * Gets the first element of an array satisfying a given predicate
  10283. * @param array defines the array to browse
  10284. * @param predicate defines the predicate to use
  10285. * @returns null if not found or the element
  10286. */
  10287. Tools.First = function (array, predicate) {
  10288. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10289. var el = array_1[_i];
  10290. if (predicate(el)) {
  10291. return el;
  10292. }
  10293. }
  10294. return null;
  10295. };
  10296. /**
  10297. * This method will return the name of the full name of the class, including its owning module (if any).
  10298. * 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).
  10299. * @param object the object to get the class name from
  10300. * @param isType defines if the object is actually a type
  10301. * @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.
  10302. * @ignorenaming
  10303. */
  10304. Tools.getFullClassName = function (object, isType) {
  10305. if (isType === void 0) { isType = false; }
  10306. var className = null;
  10307. var moduleName = null;
  10308. if (!isType && object.getClassName) {
  10309. className = object.getClassName();
  10310. }
  10311. else {
  10312. if (object instanceof Object) {
  10313. var classObj = isType ? object : Object.getPrototypeOf(object);
  10314. className = classObj.constructor["__bjsclassName__"];
  10315. moduleName = classObj.constructor["__bjsmoduleName__"];
  10316. }
  10317. if (!className) {
  10318. className = typeof object;
  10319. }
  10320. }
  10321. if (!className) {
  10322. return null;
  10323. }
  10324. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10325. };
  10326. /**
  10327. * Returns a promise that resolves after the given amount of time.
  10328. * @param delay Number of milliseconds to delay
  10329. * @returns Promise that resolves after the given amount of time
  10330. */
  10331. Tools.DelayAsync = function (delay) {
  10332. return new Promise(function (resolve) {
  10333. setTimeout(function () {
  10334. resolve();
  10335. }, delay);
  10336. });
  10337. };
  10338. /**
  10339. * Gets the current gradient from an array of IValueGradient
  10340. * @param ratio defines the current ratio to get
  10341. * @param gradients defines the array of IValueGradient
  10342. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10343. */
  10344. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10345. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10346. var currentGradient = gradients[gradientIndex];
  10347. var nextGradient = gradients[gradientIndex + 1];
  10348. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10349. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10350. updateFunc(currentGradient, nextGradient, scale);
  10351. return;
  10352. }
  10353. }
  10354. // Use last index if over
  10355. var lastIndex = gradients.length - 1;
  10356. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10357. };
  10358. /**
  10359. * Gets or sets the base URL to use to load assets
  10360. */
  10361. Tools.BaseUrl = "";
  10362. /**
  10363. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  10364. */
  10365. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10366. /**
  10367. * Default behaviour for cors in the application.
  10368. * It can be a string if the expected behavior is identical in the entire app.
  10369. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10370. */
  10371. Tools.CorsBehavior = "anonymous";
  10372. /**
  10373. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  10374. * @ignorenaming
  10375. */
  10376. Tools.UseFallbackTexture = true;
  10377. /**
  10378. * Use this object to register external classes like custom textures or material
  10379. * to allow the laoders to instantiate them
  10380. */
  10381. Tools.RegisteredExternalClasses = {};
  10382. /**
  10383. * Texture content used if a texture cannot loaded
  10384. * @ignorenaming
  10385. */
  10386. 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";
  10387. Tools._tmpFloatArray = new Float32Array(1);
  10388. /**
  10389. * Gets or sets a function used to pre-process url before using them to load assets
  10390. */
  10391. Tools.PreprocessUrl = function (url) {
  10392. return url;
  10393. };
  10394. // Logs
  10395. /**
  10396. * No log
  10397. */
  10398. Tools.NoneLogLevel = 0;
  10399. /**
  10400. * Only message logs
  10401. */
  10402. Tools.MessageLogLevel = 1;
  10403. /**
  10404. * Only warning logs
  10405. */
  10406. Tools.WarningLogLevel = 2;
  10407. /**
  10408. * Only error logs
  10409. */
  10410. Tools.ErrorLogLevel = 4;
  10411. /**
  10412. * All logs
  10413. */
  10414. Tools.AllLogLevel = 7;
  10415. Tools._LogCache = "";
  10416. /**
  10417. * Gets a value indicating the number of loading errors
  10418. * @ignorenaming
  10419. */
  10420. Tools.errorsCount = 0;
  10421. /**
  10422. * Log a message to the console
  10423. */
  10424. Tools.Log = Tools._LogEnabled;
  10425. /**
  10426. * Write a warning message to the console
  10427. */
  10428. Tools.Warn = Tools._WarnEnabled;
  10429. /**
  10430. * Write an error message to the console
  10431. */
  10432. Tools.Error = Tools._ErrorEnabled;
  10433. // Performances
  10434. /**
  10435. * No performance log
  10436. */
  10437. Tools.PerformanceNoneLogLevel = 0;
  10438. /**
  10439. * Use user marks to log performance
  10440. */
  10441. Tools.PerformanceUserMarkLogLevel = 1;
  10442. /**
  10443. * Log performance to the console
  10444. */
  10445. Tools.PerformanceConsoleLogLevel = 2;
  10446. /**
  10447. * Starts a performance counter
  10448. */
  10449. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10450. /**
  10451. * Ends a specific performance coutner
  10452. */
  10453. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10454. return Tools;
  10455. }());
  10456. BABYLON.Tools = Tools;
  10457. /**
  10458. * This class is used to track a performance counter which is number based.
  10459. * The user has access to many properties which give statistics of different nature.
  10460. *
  10461. * The implementer can track two kinds of Performance Counter: time and count.
  10462. * 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.
  10463. * 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.
  10464. */
  10465. var PerfCounter = /** @class */ (function () {
  10466. /**
  10467. * Creates a new counter
  10468. */
  10469. function PerfCounter() {
  10470. this._startMonitoringTime = 0;
  10471. this._min = 0;
  10472. this._max = 0;
  10473. this._average = 0;
  10474. this._lastSecAverage = 0;
  10475. this._current = 0;
  10476. this._totalValueCount = 0;
  10477. this._totalAccumulated = 0;
  10478. this._lastSecAccumulated = 0;
  10479. this._lastSecTime = 0;
  10480. this._lastSecValueCount = 0;
  10481. }
  10482. Object.defineProperty(PerfCounter.prototype, "min", {
  10483. /**
  10484. * Returns the smallest value ever
  10485. */
  10486. get: function () {
  10487. return this._min;
  10488. },
  10489. enumerable: true,
  10490. configurable: true
  10491. });
  10492. Object.defineProperty(PerfCounter.prototype, "max", {
  10493. /**
  10494. * Returns the biggest value ever
  10495. */
  10496. get: function () {
  10497. return this._max;
  10498. },
  10499. enumerable: true,
  10500. configurable: true
  10501. });
  10502. Object.defineProperty(PerfCounter.prototype, "average", {
  10503. /**
  10504. * Returns the average value since the performance counter is running
  10505. */
  10506. get: function () {
  10507. return this._average;
  10508. },
  10509. enumerable: true,
  10510. configurable: true
  10511. });
  10512. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10513. /**
  10514. * Returns the average value of the last second the counter was monitored
  10515. */
  10516. get: function () {
  10517. return this._lastSecAverage;
  10518. },
  10519. enumerable: true,
  10520. configurable: true
  10521. });
  10522. Object.defineProperty(PerfCounter.prototype, "current", {
  10523. /**
  10524. * Returns the current value
  10525. */
  10526. get: function () {
  10527. return this._current;
  10528. },
  10529. enumerable: true,
  10530. configurable: true
  10531. });
  10532. Object.defineProperty(PerfCounter.prototype, "total", {
  10533. /**
  10534. * Gets the accumulated total
  10535. */
  10536. get: function () {
  10537. return this._totalAccumulated;
  10538. },
  10539. enumerable: true,
  10540. configurable: true
  10541. });
  10542. Object.defineProperty(PerfCounter.prototype, "count", {
  10543. /**
  10544. * Gets the total value count
  10545. */
  10546. get: function () {
  10547. return this._totalValueCount;
  10548. },
  10549. enumerable: true,
  10550. configurable: true
  10551. });
  10552. /**
  10553. * Call this method to start monitoring a new frame.
  10554. * 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.
  10555. */
  10556. PerfCounter.prototype.fetchNewFrame = function () {
  10557. this._totalValueCount++;
  10558. this._current = 0;
  10559. this._lastSecValueCount++;
  10560. };
  10561. /**
  10562. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10563. * @param newCount the count value to add to the monitored count
  10564. * @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.
  10565. */
  10566. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10567. if (!PerfCounter.Enabled) {
  10568. return;
  10569. }
  10570. this._current += newCount;
  10571. if (fetchResult) {
  10572. this._fetchResult();
  10573. }
  10574. };
  10575. /**
  10576. * Start monitoring this performance counter
  10577. */
  10578. PerfCounter.prototype.beginMonitoring = function () {
  10579. if (!PerfCounter.Enabled) {
  10580. return;
  10581. }
  10582. this._startMonitoringTime = Tools.Now;
  10583. };
  10584. /**
  10585. * Compute the time lapsed since the previous beginMonitoring() call.
  10586. * @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
  10587. */
  10588. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10589. if (newFrame === void 0) { newFrame = true; }
  10590. if (!PerfCounter.Enabled) {
  10591. return;
  10592. }
  10593. if (newFrame) {
  10594. this.fetchNewFrame();
  10595. }
  10596. var currentTime = Tools.Now;
  10597. this._current = currentTime - this._startMonitoringTime;
  10598. if (newFrame) {
  10599. this._fetchResult();
  10600. }
  10601. };
  10602. PerfCounter.prototype._fetchResult = function () {
  10603. this._totalAccumulated += this._current;
  10604. this._lastSecAccumulated += this._current;
  10605. // Min/Max update
  10606. this._min = Math.min(this._min, this._current);
  10607. this._max = Math.max(this._max, this._current);
  10608. this._average = this._totalAccumulated / this._totalValueCount;
  10609. // Reset last sec?
  10610. var now = Tools.Now;
  10611. if ((now - this._lastSecTime) > 1000) {
  10612. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10613. this._lastSecTime = now;
  10614. this._lastSecAccumulated = 0;
  10615. this._lastSecValueCount = 0;
  10616. }
  10617. };
  10618. /**
  10619. * Gets or sets a global boolean to turn on and off all the counters
  10620. */
  10621. PerfCounter.Enabled = true;
  10622. return PerfCounter;
  10623. }());
  10624. BABYLON.PerfCounter = PerfCounter;
  10625. /**
  10626. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10627. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10628. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10629. * @param name The name of the class, case should be preserved
  10630. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10631. */
  10632. function className(name, module) {
  10633. return function (target) {
  10634. target["__bjsclassName__"] = name;
  10635. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10636. };
  10637. }
  10638. BABYLON.className = className;
  10639. /**
  10640. * An implementation of a loop for asynchronous functions.
  10641. */
  10642. var AsyncLoop = /** @class */ (function () {
  10643. /**
  10644. * Constructor.
  10645. * @param iterations the number of iterations.
  10646. * @param func the function to run each iteration
  10647. * @param successCallback the callback that will be called upon succesful execution
  10648. * @param offset starting offset.
  10649. */
  10650. function AsyncLoop(
  10651. /**
  10652. * Defines the number of iterations for the loop
  10653. */
  10654. iterations, func, successCallback, offset) {
  10655. if (offset === void 0) { offset = 0; }
  10656. this.iterations = iterations;
  10657. this.index = offset - 1;
  10658. this._done = false;
  10659. this._fn = func;
  10660. this._successCallback = successCallback;
  10661. }
  10662. /**
  10663. * Execute the next iteration. Must be called after the last iteration was finished.
  10664. */
  10665. AsyncLoop.prototype.executeNext = function () {
  10666. if (!this._done) {
  10667. if (this.index + 1 < this.iterations) {
  10668. ++this.index;
  10669. this._fn(this);
  10670. }
  10671. else {
  10672. this.breakLoop();
  10673. }
  10674. }
  10675. };
  10676. /**
  10677. * Break the loop and run the success callback.
  10678. */
  10679. AsyncLoop.prototype.breakLoop = function () {
  10680. this._done = true;
  10681. this._successCallback();
  10682. };
  10683. /**
  10684. * Create and run an async loop.
  10685. * @param iterations the number of iterations.
  10686. * @param fn the function to run each iteration
  10687. * @param successCallback the callback that will be called upon succesful execution
  10688. * @param offset starting offset.
  10689. * @returns the created async loop object
  10690. */
  10691. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  10692. if (offset === void 0) { offset = 0; }
  10693. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  10694. loop.executeNext();
  10695. return loop;
  10696. };
  10697. /**
  10698. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10699. * @param iterations total number of iterations
  10700. * @param syncedIterations number of synchronous iterations in each async iteration.
  10701. * @param fn the function to call each iteration.
  10702. * @param callback a success call back that will be called when iterating stops.
  10703. * @param breakFunction a break condition (optional)
  10704. * @param timeout timeout settings for the setTimeout function. default - 0.
  10705. * @returns the created async loop object
  10706. */
  10707. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10708. if (timeout === void 0) { timeout = 0; }
  10709. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10710. if (breakFunction && breakFunction())
  10711. loop.breakLoop();
  10712. else {
  10713. setTimeout(function () {
  10714. for (var i = 0; i < syncedIterations; ++i) {
  10715. var iteration = (loop.index * syncedIterations) + i;
  10716. if (iteration >= iterations)
  10717. break;
  10718. fn(iteration);
  10719. if (breakFunction && breakFunction()) {
  10720. loop.breakLoop();
  10721. break;
  10722. }
  10723. }
  10724. loop.executeNext();
  10725. }, timeout);
  10726. }
  10727. }, callback);
  10728. };
  10729. return AsyncLoop;
  10730. }());
  10731. BABYLON.AsyncLoop = AsyncLoop;
  10732. })(BABYLON || (BABYLON = {}));
  10733. //# sourceMappingURL=babylon.tools.js.map
  10734. var BABYLON;
  10735. (function (BABYLON) {
  10736. var PromiseStates;
  10737. (function (PromiseStates) {
  10738. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10739. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10740. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10741. })(PromiseStates || (PromiseStates = {}));
  10742. var FulFillmentAgregator = /** @class */ (function () {
  10743. function FulFillmentAgregator() {
  10744. this.count = 0;
  10745. this.target = 0;
  10746. this.results = [];
  10747. }
  10748. return FulFillmentAgregator;
  10749. }());
  10750. var InternalPromise = /** @class */ (function () {
  10751. function InternalPromise(resolver) {
  10752. var _this = this;
  10753. this._state = PromiseStates.Pending;
  10754. this._children = new Array();
  10755. this._rejectWasConsumed = false;
  10756. if (!resolver) {
  10757. return;
  10758. }
  10759. try {
  10760. resolver(function (value) {
  10761. _this._resolve(value);
  10762. }, function (reason) {
  10763. _this._reject(reason);
  10764. });
  10765. }
  10766. catch (e) {
  10767. this._reject(e);
  10768. }
  10769. }
  10770. Object.defineProperty(InternalPromise.prototype, "_result", {
  10771. get: function () {
  10772. return this._resultValue;
  10773. },
  10774. set: function (value) {
  10775. this._resultValue = value;
  10776. if (this._parent && this._parent._result === undefined) {
  10777. this._parent._result = value;
  10778. }
  10779. },
  10780. enumerable: true,
  10781. configurable: true
  10782. });
  10783. InternalPromise.prototype.catch = function (onRejected) {
  10784. return this.then(undefined, onRejected);
  10785. };
  10786. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10787. var _this = this;
  10788. var newPromise = new InternalPromise();
  10789. newPromise._onFulfilled = onFulfilled;
  10790. newPromise._onRejected = onRejected;
  10791. // Composition
  10792. this._children.push(newPromise);
  10793. newPromise._parent = this;
  10794. if (this._state !== PromiseStates.Pending) {
  10795. BABYLON.Tools.SetImmediate(function () {
  10796. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10797. var returnedValue = newPromise._resolve(_this._result);
  10798. if (returnedValue !== undefined && returnedValue !== null) {
  10799. if (returnedValue._state !== undefined) {
  10800. var returnedPromise = returnedValue;
  10801. newPromise._children.push(returnedPromise);
  10802. returnedPromise._parent = newPromise;
  10803. newPromise = returnedPromise;
  10804. }
  10805. else {
  10806. newPromise._result = returnedValue;
  10807. }
  10808. }
  10809. }
  10810. else {
  10811. newPromise._reject(_this._reason);
  10812. }
  10813. });
  10814. }
  10815. return newPromise;
  10816. };
  10817. InternalPromise.prototype._moveChildren = function (children) {
  10818. var _this = this;
  10819. var _a;
  10820. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10821. this._children.forEach(function (child) {
  10822. child._parent = _this;
  10823. });
  10824. if (this._state === PromiseStates.Fulfilled) {
  10825. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10826. var child = _b[_i];
  10827. child._resolve(this._result);
  10828. }
  10829. }
  10830. else if (this._state === PromiseStates.Rejected) {
  10831. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10832. var child = _d[_c];
  10833. child._reject(this._reason);
  10834. }
  10835. }
  10836. };
  10837. InternalPromise.prototype._resolve = function (value) {
  10838. try {
  10839. this._state = PromiseStates.Fulfilled;
  10840. var returnedValue = null;
  10841. if (this._onFulfilled) {
  10842. returnedValue = this._onFulfilled(value);
  10843. }
  10844. if (returnedValue !== undefined && returnedValue !== null) {
  10845. if (returnedValue._state !== undefined) {
  10846. // Transmit children
  10847. var returnedPromise = returnedValue;
  10848. returnedPromise._parent = this;
  10849. returnedPromise._moveChildren(this._children);
  10850. value = returnedPromise._result;
  10851. }
  10852. else {
  10853. value = returnedValue;
  10854. }
  10855. }
  10856. this._result = value;
  10857. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10858. var child = _a[_i];
  10859. child._resolve(value);
  10860. }
  10861. this._children.length = 0;
  10862. delete this._onFulfilled;
  10863. delete this._onRejected;
  10864. }
  10865. catch (e) {
  10866. this._reject(e, true);
  10867. }
  10868. };
  10869. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10870. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10871. this._state = PromiseStates.Rejected;
  10872. this._reason = reason;
  10873. if (this._onRejected && !onLocalThrow) {
  10874. try {
  10875. this._onRejected(reason);
  10876. this._rejectWasConsumed = true;
  10877. }
  10878. catch (e) {
  10879. reason = e;
  10880. }
  10881. }
  10882. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10883. var child = _a[_i];
  10884. if (this._rejectWasConsumed) {
  10885. child._resolve(null);
  10886. }
  10887. else {
  10888. child._reject(reason);
  10889. }
  10890. }
  10891. this._children.length = 0;
  10892. delete this._onFulfilled;
  10893. delete this._onRejected;
  10894. };
  10895. InternalPromise.resolve = function (value) {
  10896. var newPromise = new InternalPromise();
  10897. newPromise._resolve(value);
  10898. return newPromise;
  10899. };
  10900. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10901. promise.then(function (value) {
  10902. agregator.results[index] = value;
  10903. agregator.count++;
  10904. if (agregator.count === agregator.target) {
  10905. agregator.rootPromise._resolve(agregator.results);
  10906. }
  10907. return null;
  10908. }, function (reason) {
  10909. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10910. agregator.rootPromise._reject(reason);
  10911. }
  10912. });
  10913. };
  10914. InternalPromise.all = function (promises) {
  10915. var newPromise = new InternalPromise();
  10916. var agregator = new FulFillmentAgregator();
  10917. agregator.target = promises.length;
  10918. agregator.rootPromise = newPromise;
  10919. if (promises.length) {
  10920. for (var index = 0; index < promises.length; index++) {
  10921. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10922. }
  10923. }
  10924. else {
  10925. newPromise._resolve([]);
  10926. }
  10927. return newPromise;
  10928. };
  10929. InternalPromise.race = function (promises) {
  10930. var newPromise = new InternalPromise();
  10931. if (promises.length) {
  10932. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10933. var promise = promises_1[_i];
  10934. promise.then(function (value) {
  10935. if (newPromise) {
  10936. newPromise._resolve(value);
  10937. newPromise = null;
  10938. }
  10939. return null;
  10940. }, function (reason) {
  10941. if (newPromise) {
  10942. newPromise._reject(reason);
  10943. newPromise = null;
  10944. }
  10945. });
  10946. }
  10947. }
  10948. return newPromise;
  10949. };
  10950. return InternalPromise;
  10951. }());
  10952. /**
  10953. * Helper class that provides a small promise polyfill
  10954. */
  10955. var PromisePolyfill = /** @class */ (function () {
  10956. function PromisePolyfill() {
  10957. }
  10958. /**
  10959. * Static function used to check if the polyfill is required
  10960. * If this is the case then the function will inject the polyfill to window.Promise
  10961. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10962. */
  10963. PromisePolyfill.Apply = function (force) {
  10964. if (force === void 0) { force = false; }
  10965. if (force || typeof Promise === 'undefined') {
  10966. var root = window;
  10967. root.Promise = InternalPromise;
  10968. }
  10969. };
  10970. return PromisePolyfill;
  10971. }());
  10972. BABYLON.PromisePolyfill = PromisePolyfill;
  10973. })(BABYLON || (BABYLON = {}));
  10974. //# sourceMappingURL=babylon.promise.js.map
  10975. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10976. var BABYLON;
  10977. (function (BABYLON) {
  10978. /**
  10979. * Helper class to push actions to a pool of workers.
  10980. */
  10981. var WorkerPool = /** @class */ (function () {
  10982. /**
  10983. * Constructor
  10984. * @param workers Array of workers to use for actions
  10985. */
  10986. function WorkerPool(workers) {
  10987. this._pendingActions = new Array();
  10988. this._workerInfos = workers.map(function (worker) { return ({
  10989. worker: worker,
  10990. active: false
  10991. }); });
  10992. }
  10993. /**
  10994. * Terminates all workers and clears any pending actions.
  10995. */
  10996. WorkerPool.prototype.dispose = function () {
  10997. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10998. var workerInfo = _a[_i];
  10999. workerInfo.worker.terminate();
  11000. }
  11001. delete this._workerInfos;
  11002. delete this._pendingActions;
  11003. };
  11004. /**
  11005. * Pushes an action to the worker pool. If all the workers are active, the action will be
  11006. * pended until a worker has completed its action.
  11007. * @param action The action to perform. Call onComplete when the action is complete.
  11008. */
  11009. WorkerPool.prototype.push = function (action) {
  11010. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11011. var workerInfo = _a[_i];
  11012. if (!workerInfo.active) {
  11013. this._execute(workerInfo, action);
  11014. return;
  11015. }
  11016. }
  11017. this._pendingActions.push(action);
  11018. };
  11019. WorkerPool.prototype._execute = function (workerInfo, action) {
  11020. var _this = this;
  11021. workerInfo.active = true;
  11022. action(workerInfo.worker, function () {
  11023. workerInfo.active = false;
  11024. var nextAction = _this._pendingActions.shift();
  11025. if (nextAction) {
  11026. _this._execute(workerInfo, nextAction);
  11027. }
  11028. });
  11029. };
  11030. return WorkerPool;
  11031. }());
  11032. BABYLON.WorkerPool = WorkerPool;
  11033. })(BABYLON || (BABYLON = {}));
  11034. //# sourceMappingURL=babylon.workerPool.js.map
  11035. var BABYLON;
  11036. (function (BABYLON) {
  11037. /**
  11038. * @hidden
  11039. **/
  11040. var _AlphaState = /** @class */ (function () {
  11041. /**
  11042. * Initializes the state.
  11043. */
  11044. function _AlphaState() {
  11045. this._isAlphaBlendDirty = false;
  11046. this._isBlendFunctionParametersDirty = false;
  11047. this._isBlendEquationParametersDirty = false;
  11048. this._isBlendConstantsDirty = false;
  11049. this._alphaBlend = false;
  11050. this._blendFunctionParameters = new Array(4);
  11051. this._blendEquationParameters = new Array(2);
  11052. this._blendConstants = new Array(4);
  11053. this.reset();
  11054. }
  11055. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  11056. get: function () {
  11057. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  11058. },
  11059. enumerable: true,
  11060. configurable: true
  11061. });
  11062. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  11063. get: function () {
  11064. return this._alphaBlend;
  11065. },
  11066. set: function (value) {
  11067. if (this._alphaBlend === value) {
  11068. return;
  11069. }
  11070. this._alphaBlend = value;
  11071. this._isAlphaBlendDirty = true;
  11072. },
  11073. enumerable: true,
  11074. configurable: true
  11075. });
  11076. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  11077. if (this._blendConstants[0] === r &&
  11078. this._blendConstants[1] === g &&
  11079. this._blendConstants[2] === b &&
  11080. this._blendConstants[3] === a) {
  11081. return;
  11082. }
  11083. this._blendConstants[0] = r;
  11084. this._blendConstants[1] = g;
  11085. this._blendConstants[2] = b;
  11086. this._blendConstants[3] = a;
  11087. this._isBlendConstantsDirty = true;
  11088. };
  11089. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  11090. if (this._blendFunctionParameters[0] === value0 &&
  11091. this._blendFunctionParameters[1] === value1 &&
  11092. this._blendFunctionParameters[2] === value2 &&
  11093. this._blendFunctionParameters[3] === value3) {
  11094. return;
  11095. }
  11096. this._blendFunctionParameters[0] = value0;
  11097. this._blendFunctionParameters[1] = value1;
  11098. this._blendFunctionParameters[2] = value2;
  11099. this._blendFunctionParameters[3] = value3;
  11100. this._isBlendFunctionParametersDirty = true;
  11101. };
  11102. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  11103. if (this._blendEquationParameters[0] === rgb &&
  11104. this._blendEquationParameters[1] === alpha) {
  11105. return;
  11106. }
  11107. this._blendEquationParameters[0] = rgb;
  11108. this._blendEquationParameters[1] = alpha;
  11109. this._isBlendEquationParametersDirty = true;
  11110. };
  11111. _AlphaState.prototype.reset = function () {
  11112. this._alphaBlend = false;
  11113. this._blendFunctionParameters[0] = null;
  11114. this._blendFunctionParameters[1] = null;
  11115. this._blendFunctionParameters[2] = null;
  11116. this._blendFunctionParameters[3] = null;
  11117. this._blendEquationParameters[0] = null;
  11118. this._blendEquationParameters[1] = null;
  11119. this._blendConstants[0] = null;
  11120. this._blendConstants[1] = null;
  11121. this._blendConstants[2] = null;
  11122. this._blendConstants[3] = null;
  11123. this._isAlphaBlendDirty = true;
  11124. this._isBlendFunctionParametersDirty = false;
  11125. this._isBlendEquationParametersDirty = false;
  11126. this._isBlendConstantsDirty = false;
  11127. };
  11128. _AlphaState.prototype.apply = function (gl) {
  11129. if (!this.isDirty) {
  11130. return;
  11131. }
  11132. // Alpha blend
  11133. if (this._isAlphaBlendDirty) {
  11134. if (this._alphaBlend) {
  11135. gl.enable(gl.BLEND);
  11136. }
  11137. else {
  11138. gl.disable(gl.BLEND);
  11139. }
  11140. this._isAlphaBlendDirty = false;
  11141. }
  11142. // Alpha function
  11143. if (this._isBlendFunctionParametersDirty) {
  11144. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  11145. this._isBlendFunctionParametersDirty = false;
  11146. }
  11147. // Alpha equation
  11148. if (this._isBlendEquationParametersDirty) {
  11149. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  11150. this._isBlendEquationParametersDirty = false;
  11151. }
  11152. // Constants
  11153. if (this._isBlendConstantsDirty) {
  11154. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  11155. this._isBlendConstantsDirty = false;
  11156. }
  11157. };
  11158. return _AlphaState;
  11159. }());
  11160. BABYLON._AlphaState = _AlphaState;
  11161. })(BABYLON || (BABYLON = {}));
  11162. //# sourceMappingURL=babylon.alphaCullingState.js.map
  11163. var BABYLON;
  11164. (function (BABYLON) {
  11165. /**
  11166. * @hidden
  11167. **/
  11168. var _DepthCullingState = /** @class */ (function () {
  11169. /**
  11170. * Initializes the state.
  11171. */
  11172. function _DepthCullingState() {
  11173. this._isDepthTestDirty = false;
  11174. this._isDepthMaskDirty = false;
  11175. this._isDepthFuncDirty = false;
  11176. this._isCullFaceDirty = false;
  11177. this._isCullDirty = false;
  11178. this._isZOffsetDirty = false;
  11179. this._isFrontFaceDirty = false;
  11180. this.reset();
  11181. }
  11182. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11183. get: function () {
  11184. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11185. },
  11186. enumerable: true,
  11187. configurable: true
  11188. });
  11189. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11190. get: function () {
  11191. return this._zOffset;
  11192. },
  11193. set: function (value) {
  11194. if (this._zOffset === value) {
  11195. return;
  11196. }
  11197. this._zOffset = value;
  11198. this._isZOffsetDirty = true;
  11199. },
  11200. enumerable: true,
  11201. configurable: true
  11202. });
  11203. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11204. get: function () {
  11205. return this._cullFace;
  11206. },
  11207. set: function (value) {
  11208. if (this._cullFace === value) {
  11209. return;
  11210. }
  11211. this._cullFace = value;
  11212. this._isCullFaceDirty = true;
  11213. },
  11214. enumerable: true,
  11215. configurable: true
  11216. });
  11217. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11218. get: function () {
  11219. return this._cull;
  11220. },
  11221. set: function (value) {
  11222. if (this._cull === value) {
  11223. return;
  11224. }
  11225. this._cull = value;
  11226. this._isCullDirty = true;
  11227. },
  11228. enumerable: true,
  11229. configurable: true
  11230. });
  11231. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11232. get: function () {
  11233. return this._depthFunc;
  11234. },
  11235. set: function (value) {
  11236. if (this._depthFunc === value) {
  11237. return;
  11238. }
  11239. this._depthFunc = value;
  11240. this._isDepthFuncDirty = true;
  11241. },
  11242. enumerable: true,
  11243. configurable: true
  11244. });
  11245. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11246. get: function () {
  11247. return this._depthMask;
  11248. },
  11249. set: function (value) {
  11250. if (this._depthMask === value) {
  11251. return;
  11252. }
  11253. this._depthMask = value;
  11254. this._isDepthMaskDirty = true;
  11255. },
  11256. enumerable: true,
  11257. configurable: true
  11258. });
  11259. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11260. get: function () {
  11261. return this._depthTest;
  11262. },
  11263. set: function (value) {
  11264. if (this._depthTest === value) {
  11265. return;
  11266. }
  11267. this._depthTest = value;
  11268. this._isDepthTestDirty = true;
  11269. },
  11270. enumerable: true,
  11271. configurable: true
  11272. });
  11273. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11274. get: function () {
  11275. return this._frontFace;
  11276. },
  11277. set: function (value) {
  11278. if (this._frontFace === value) {
  11279. return;
  11280. }
  11281. this._frontFace = value;
  11282. this._isFrontFaceDirty = true;
  11283. },
  11284. enumerable: true,
  11285. configurable: true
  11286. });
  11287. _DepthCullingState.prototype.reset = function () {
  11288. this._depthMask = true;
  11289. this._depthTest = true;
  11290. this._depthFunc = null;
  11291. this._cullFace = null;
  11292. this._cull = null;
  11293. this._zOffset = 0;
  11294. this._frontFace = null;
  11295. this._isDepthTestDirty = true;
  11296. this._isDepthMaskDirty = true;
  11297. this._isDepthFuncDirty = false;
  11298. this._isCullFaceDirty = false;
  11299. this._isCullDirty = false;
  11300. this._isZOffsetDirty = false;
  11301. this._isFrontFaceDirty = false;
  11302. };
  11303. _DepthCullingState.prototype.apply = function (gl) {
  11304. if (!this.isDirty) {
  11305. return;
  11306. }
  11307. // Cull
  11308. if (this._isCullDirty) {
  11309. if (this.cull) {
  11310. gl.enable(gl.CULL_FACE);
  11311. }
  11312. else {
  11313. gl.disable(gl.CULL_FACE);
  11314. }
  11315. this._isCullDirty = false;
  11316. }
  11317. // Cull face
  11318. if (this._isCullFaceDirty) {
  11319. gl.cullFace(this.cullFace);
  11320. this._isCullFaceDirty = false;
  11321. }
  11322. // Depth mask
  11323. if (this._isDepthMaskDirty) {
  11324. gl.depthMask(this.depthMask);
  11325. this._isDepthMaskDirty = false;
  11326. }
  11327. // Depth test
  11328. if (this._isDepthTestDirty) {
  11329. if (this.depthTest) {
  11330. gl.enable(gl.DEPTH_TEST);
  11331. }
  11332. else {
  11333. gl.disable(gl.DEPTH_TEST);
  11334. }
  11335. this._isDepthTestDirty = false;
  11336. }
  11337. // Depth func
  11338. if (this._isDepthFuncDirty) {
  11339. gl.depthFunc(this.depthFunc);
  11340. this._isDepthFuncDirty = false;
  11341. }
  11342. // zOffset
  11343. if (this._isZOffsetDirty) {
  11344. if (this.zOffset) {
  11345. gl.enable(gl.POLYGON_OFFSET_FILL);
  11346. gl.polygonOffset(this.zOffset, 0);
  11347. }
  11348. else {
  11349. gl.disable(gl.POLYGON_OFFSET_FILL);
  11350. }
  11351. this._isZOffsetDirty = false;
  11352. }
  11353. // Front face
  11354. if (this._isFrontFaceDirty) {
  11355. gl.frontFace(this.frontFace);
  11356. this._isFrontFaceDirty = false;
  11357. }
  11358. };
  11359. return _DepthCullingState;
  11360. }());
  11361. BABYLON._DepthCullingState = _DepthCullingState;
  11362. })(BABYLON || (BABYLON = {}));
  11363. //# sourceMappingURL=babylon.depthCullingState.js.map
  11364. var BABYLON;
  11365. (function (BABYLON) {
  11366. /**
  11367. * @hidden
  11368. **/
  11369. var _StencilState = /** @class */ (function () {
  11370. function _StencilState() {
  11371. this._isStencilTestDirty = false;
  11372. this._isStencilMaskDirty = false;
  11373. this._isStencilFuncDirty = false;
  11374. this._isStencilOpDirty = false;
  11375. this.reset();
  11376. }
  11377. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11378. get: function () {
  11379. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11380. },
  11381. enumerable: true,
  11382. configurable: true
  11383. });
  11384. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11385. get: function () {
  11386. return this._stencilFunc;
  11387. },
  11388. set: function (value) {
  11389. if (this._stencilFunc === value) {
  11390. return;
  11391. }
  11392. this._stencilFunc = value;
  11393. this._isStencilFuncDirty = true;
  11394. },
  11395. enumerable: true,
  11396. configurable: true
  11397. });
  11398. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11399. get: function () {
  11400. return this._stencilFuncRef;
  11401. },
  11402. set: function (value) {
  11403. if (this._stencilFuncRef === value) {
  11404. return;
  11405. }
  11406. this._stencilFuncRef = value;
  11407. this._isStencilFuncDirty = true;
  11408. },
  11409. enumerable: true,
  11410. configurable: true
  11411. });
  11412. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11413. get: function () {
  11414. return this._stencilFuncMask;
  11415. },
  11416. set: function (value) {
  11417. if (this._stencilFuncMask === value) {
  11418. return;
  11419. }
  11420. this._stencilFuncMask = value;
  11421. this._isStencilFuncDirty = true;
  11422. },
  11423. enumerable: true,
  11424. configurable: true
  11425. });
  11426. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11427. get: function () {
  11428. return this._stencilOpStencilFail;
  11429. },
  11430. set: function (value) {
  11431. if (this._stencilOpStencilFail === value) {
  11432. return;
  11433. }
  11434. this._stencilOpStencilFail = value;
  11435. this._isStencilOpDirty = true;
  11436. },
  11437. enumerable: true,
  11438. configurable: true
  11439. });
  11440. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11441. get: function () {
  11442. return this._stencilOpDepthFail;
  11443. },
  11444. set: function (value) {
  11445. if (this._stencilOpDepthFail === value) {
  11446. return;
  11447. }
  11448. this._stencilOpDepthFail = value;
  11449. this._isStencilOpDirty = true;
  11450. },
  11451. enumerable: true,
  11452. configurable: true
  11453. });
  11454. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11455. get: function () {
  11456. return this._stencilOpStencilDepthPass;
  11457. },
  11458. set: function (value) {
  11459. if (this._stencilOpStencilDepthPass === value) {
  11460. return;
  11461. }
  11462. this._stencilOpStencilDepthPass = value;
  11463. this._isStencilOpDirty = true;
  11464. },
  11465. enumerable: true,
  11466. configurable: true
  11467. });
  11468. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11469. get: function () {
  11470. return this._stencilMask;
  11471. },
  11472. set: function (value) {
  11473. if (this._stencilMask === value) {
  11474. return;
  11475. }
  11476. this._stencilMask = value;
  11477. this._isStencilMaskDirty = true;
  11478. },
  11479. enumerable: true,
  11480. configurable: true
  11481. });
  11482. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11483. get: function () {
  11484. return this._stencilTest;
  11485. },
  11486. set: function (value) {
  11487. if (this._stencilTest === value) {
  11488. return;
  11489. }
  11490. this._stencilTest = value;
  11491. this._isStencilTestDirty = true;
  11492. },
  11493. enumerable: true,
  11494. configurable: true
  11495. });
  11496. _StencilState.prototype.reset = function () {
  11497. this._stencilTest = false;
  11498. this._stencilMask = 0xFF;
  11499. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11500. this._stencilFuncRef = 1;
  11501. this._stencilFuncMask = 0xFF;
  11502. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11503. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11504. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11505. this._isStencilTestDirty = true;
  11506. this._isStencilMaskDirty = true;
  11507. this._isStencilFuncDirty = true;
  11508. this._isStencilOpDirty = true;
  11509. };
  11510. _StencilState.prototype.apply = function (gl) {
  11511. if (!this.isDirty) {
  11512. return;
  11513. }
  11514. // Stencil test
  11515. if (this._isStencilTestDirty) {
  11516. if (this.stencilTest) {
  11517. gl.enable(gl.STENCIL_TEST);
  11518. }
  11519. else {
  11520. gl.disable(gl.STENCIL_TEST);
  11521. }
  11522. this._isStencilTestDirty = false;
  11523. }
  11524. // Stencil mask
  11525. if (this._isStencilMaskDirty) {
  11526. gl.stencilMask(this.stencilMask);
  11527. this._isStencilMaskDirty = false;
  11528. }
  11529. // Stencil func
  11530. if (this._isStencilFuncDirty) {
  11531. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11532. this._isStencilFuncDirty = false;
  11533. }
  11534. // Stencil op
  11535. if (this._isStencilOpDirty) {
  11536. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11537. this._isStencilOpDirty = false;
  11538. }
  11539. };
  11540. return _StencilState;
  11541. }());
  11542. BABYLON._StencilState = _StencilState;
  11543. })(BABYLON || (BABYLON = {}));
  11544. //# sourceMappingURL=babylon.stencilState.js.map
  11545. var __assign = (this && this.__assign) || function () {
  11546. __assign = Object.assign || function(t) {
  11547. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11548. s = arguments[i];
  11549. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11550. t[p] = s[p];
  11551. }
  11552. return t;
  11553. };
  11554. return __assign.apply(this, arguments);
  11555. };
  11556. var BABYLON;
  11557. (function (BABYLON) {
  11558. /**
  11559. * Keeps track of all the buffer info used in engine.
  11560. */
  11561. var BufferPointer = /** @class */ (function () {
  11562. function BufferPointer() {
  11563. }
  11564. return BufferPointer;
  11565. }());
  11566. /**
  11567. * Interface for attribute information associated with buffer instanciation
  11568. */
  11569. var InstancingAttributeInfo = /** @class */ (function () {
  11570. function InstancingAttributeInfo() {
  11571. }
  11572. return InstancingAttributeInfo;
  11573. }());
  11574. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11575. /**
  11576. * Define options used to create a render target texture
  11577. */
  11578. var RenderTargetCreationOptions = /** @class */ (function () {
  11579. function RenderTargetCreationOptions() {
  11580. }
  11581. return RenderTargetCreationOptions;
  11582. }());
  11583. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11584. /**
  11585. * Define options used to create a depth texture
  11586. */
  11587. var DepthTextureCreationOptions = /** @class */ (function () {
  11588. function DepthTextureCreationOptions() {
  11589. }
  11590. return DepthTextureCreationOptions;
  11591. }());
  11592. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11593. /**
  11594. * Class used to describe the capabilities of the engine relatively to the current browser
  11595. */
  11596. var EngineCapabilities = /** @class */ (function () {
  11597. function EngineCapabilities() {
  11598. }
  11599. return EngineCapabilities;
  11600. }());
  11601. BABYLON.EngineCapabilities = EngineCapabilities;
  11602. /**
  11603. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11604. */
  11605. var Engine = /** @class */ (function () {
  11606. /**
  11607. * Creates a new engine
  11608. * @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
  11609. * @param antialias defines enable antialiasing (default: false)
  11610. * @param options defines further options to be sent to the getContext() function
  11611. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11612. */
  11613. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11614. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11615. var _this = this;
  11616. // Public members
  11617. /**
  11618. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11619. */
  11620. this.forcePOTTextures = false;
  11621. /**
  11622. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11623. */
  11624. this.isFullscreen = false;
  11625. /**
  11626. * Gets a boolean indicating if the pointer is currently locked
  11627. */
  11628. this.isPointerLock = false;
  11629. /**
  11630. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11631. */
  11632. this.cullBackFaces = true;
  11633. /**
  11634. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11635. */
  11636. this.renderEvenInBackground = true;
  11637. /**
  11638. * Gets or sets a boolean indicating that cache can be kept between frames
  11639. */
  11640. this.preventCacheWipeBetweenFrames = false;
  11641. /**
  11642. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11643. **/
  11644. this.enableOfflineSupport = false;
  11645. /**
  11646. * 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)
  11647. **/
  11648. this.disableManifestCheck = false;
  11649. /**
  11650. * Gets the list of created scenes
  11651. */
  11652. this.scenes = new Array();
  11653. /**
  11654. * Gets the list of created postprocesses
  11655. */
  11656. this.postProcesses = new Array();
  11657. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11658. this.validateShaderPrograms = false;
  11659. // Observables
  11660. /**
  11661. * Observable event triggered each time the rendering canvas is resized
  11662. */
  11663. this.onResizeObservable = new BABYLON.Observable();
  11664. /**
  11665. * Observable event triggered each time the canvas loses focus
  11666. */
  11667. this.onCanvasBlurObservable = new BABYLON.Observable();
  11668. /**
  11669. * Observable event triggered each time the canvas gains focus
  11670. */
  11671. this.onCanvasFocusObservable = new BABYLON.Observable();
  11672. /**
  11673. * Observable event triggered each time the canvas receives pointerout event
  11674. */
  11675. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11676. /**
  11677. * Observable event triggered before each texture is initialized
  11678. */
  11679. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11680. //WebVR
  11681. this._vrDisplay = undefined;
  11682. this._vrSupported = false;
  11683. this._vrExclusivePointerMode = false;
  11684. // Uniform buffers list
  11685. /**
  11686. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11687. */
  11688. this.disableUniformBuffers = false;
  11689. /** @hidden */
  11690. this._uniformBuffers = new Array();
  11691. // Observables
  11692. /**
  11693. * Observable raised when the engine begins a new frame
  11694. */
  11695. this.onBeginFrameObservable = new BABYLON.Observable();
  11696. /**
  11697. * Observable raised when the engine ends the current frame
  11698. */
  11699. this.onEndFrameObservable = new BABYLON.Observable();
  11700. /**
  11701. * Observable raised when the engine is about to compile a shader
  11702. */
  11703. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11704. /**
  11705. * Observable raised when the engine has jsut compiled a shader
  11706. */
  11707. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11708. this._windowIsBackground = false;
  11709. this._webGLVersion = 1.0;
  11710. /** @hidden */
  11711. this._badOS = false;
  11712. /** @hidden */
  11713. this._badDesktopOS = false;
  11714. /**
  11715. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11716. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11717. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11718. */
  11719. this.disableTextureBindingOptimization = false;
  11720. /**
  11721. * Observable signaled when VR display mode changes
  11722. */
  11723. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11724. /**
  11725. * Observable signaled when VR request present is complete
  11726. */
  11727. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11728. /**
  11729. * Observable signaled when VR request present starts
  11730. */
  11731. this.onVRRequestPresentStart = new BABYLON.Observable();
  11732. this._colorWrite = true;
  11733. /** @hidden */
  11734. this._drawCalls = new BABYLON.PerfCounter();
  11735. /** @hidden */
  11736. this._textureCollisions = new BABYLON.PerfCounter();
  11737. this._renderingQueueLaunched = false;
  11738. this._activeRenderLoops = new Array();
  11739. // Deterministic lockstepMaxSteps
  11740. this._deterministicLockstep = false;
  11741. this._lockstepMaxSteps = 4;
  11742. // Lost context
  11743. /**
  11744. * Observable signaled when a context lost event is raised
  11745. */
  11746. this.onContextLostObservable = new BABYLON.Observable();
  11747. /**
  11748. * Observable signaled when a context restored event is raised
  11749. */
  11750. this.onContextRestoredObservable = new BABYLON.Observable();
  11751. this._contextWasLost = false;
  11752. this._doNotHandleContextLost = false;
  11753. // FPS
  11754. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11755. this._fps = 60;
  11756. this._deltaTime = 0;
  11757. /**
  11758. * Turn this value on if you want to pause FPS computation when in background
  11759. */
  11760. this.disablePerformanceMonitorInBackground = false;
  11761. // States
  11762. /** @hidden */
  11763. this._depthCullingState = new BABYLON._DepthCullingState();
  11764. /** @hidden */
  11765. this._stencilState = new BABYLON._StencilState();
  11766. /** @hidden */
  11767. this._alphaState = new BABYLON._AlphaState();
  11768. /** @hidden */
  11769. this._alphaMode = Engine.ALPHA_DISABLE;
  11770. // Cache
  11771. this._internalTexturesCache = new Array();
  11772. /** @hidden */
  11773. this._activeChannel = 0;
  11774. this._currentTextureChannel = -1;
  11775. /** @hidden */
  11776. this._boundTexturesCache = {};
  11777. this._compiledEffects = {};
  11778. this._vertexAttribArraysEnabled = [];
  11779. this._uintIndicesCurrentlySet = false;
  11780. this._currentBoundBuffer = new Array();
  11781. /** @hidden */
  11782. this._currentFramebuffer = null;
  11783. this._currentBufferPointers = new Array();
  11784. this._currentInstanceLocations = new Array();
  11785. this._currentInstanceBuffers = new Array();
  11786. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11787. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11788. this._vaoRecordInProgress = false;
  11789. this._mustWipeVertexAttributes = false;
  11790. this._nextFreeTextureSlots = new Array();
  11791. this._maxSimultaneousTextures = 0;
  11792. this._activeRequests = new Array();
  11793. // Hardware supported Compressed Textures
  11794. this._texturesSupported = new Array();
  11795. /**
  11796. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11797. */
  11798. this.premultipliedAlpha = true;
  11799. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11800. this._onVRFullScreenTriggered = function () {
  11801. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11802. //get the old size before we change
  11803. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11804. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11805. //get the width and height, change the render size
  11806. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11807. _this.setHardwareScalingLevel(1);
  11808. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11809. }
  11810. else {
  11811. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11812. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11813. }
  11814. };
  11815. this._unpackFlipYCached = null;
  11816. /**
  11817. * In case you are sharing the context with other applications, it might
  11818. * be interested to not cache the unpack flip y state to ensure a consistent
  11819. * value would be set.
  11820. */
  11821. this.enableUnpackFlipYCached = true;
  11822. this._boundUniforms = {};
  11823. // Register promises
  11824. BABYLON.PromisePolyfill.Apply();
  11825. var canvas = null;
  11826. Engine.Instances.push(this);
  11827. if (!canvasOrContext) {
  11828. return;
  11829. }
  11830. options = options || {};
  11831. if (canvasOrContext.getContext) {
  11832. canvas = canvasOrContext;
  11833. this._renderingCanvas = canvas;
  11834. if (antialias != null) {
  11835. options.antialias = antialias;
  11836. }
  11837. if (options.deterministicLockstep === undefined) {
  11838. options.deterministicLockstep = false;
  11839. }
  11840. if (options.lockstepMaxSteps === undefined) {
  11841. options.lockstepMaxSteps = 4;
  11842. }
  11843. if (options.preserveDrawingBuffer === undefined) {
  11844. options.preserveDrawingBuffer = false;
  11845. }
  11846. if (options.audioEngine === undefined) {
  11847. options.audioEngine = true;
  11848. }
  11849. if (options.stencil === undefined) {
  11850. options.stencil = true;
  11851. }
  11852. if (options.premultipliedAlpha === false) {
  11853. this.premultipliedAlpha = false;
  11854. }
  11855. this._deterministicLockstep = options.deterministicLockstep;
  11856. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11857. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11858. // Exceptions
  11859. if (navigator && navigator.userAgent) {
  11860. var ua = navigator.userAgent;
  11861. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11862. var exception = _a[_i];
  11863. var key = exception.key;
  11864. var targets = exception.targets;
  11865. if (ua.indexOf(key) > -1) {
  11866. if (exception.capture && exception.captureConstraint) {
  11867. var capture = exception.capture;
  11868. var constraint = exception.captureConstraint;
  11869. var regex = new RegExp(capture);
  11870. var matches = regex.exec(ua);
  11871. if (matches && matches.length > 0) {
  11872. var capturedValue = parseInt(matches[matches.length - 1]);
  11873. if (capturedValue >= constraint) {
  11874. continue;
  11875. }
  11876. }
  11877. }
  11878. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11879. var target = targets_1[_b];
  11880. switch (target) {
  11881. case "uniformBuffer":
  11882. this.disableUniformBuffers = true;
  11883. break;
  11884. case "textureBindingOptimization":
  11885. this.disableTextureBindingOptimization = true;
  11886. break;
  11887. }
  11888. }
  11889. }
  11890. }
  11891. }
  11892. // GL
  11893. if (!options.disableWebGL2Support) {
  11894. try {
  11895. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11896. if (this._gl) {
  11897. this._webGLVersion = 2.0;
  11898. }
  11899. }
  11900. catch (e) {
  11901. // Do nothing
  11902. }
  11903. }
  11904. if (!this._gl) {
  11905. if (!canvas) {
  11906. throw new Error("The provided canvas is null or undefined.");
  11907. }
  11908. try {
  11909. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11910. }
  11911. catch (e) {
  11912. throw new Error("WebGL not supported");
  11913. }
  11914. }
  11915. if (!this._gl) {
  11916. throw new Error("WebGL not supported");
  11917. }
  11918. this._onCanvasFocus = function () {
  11919. _this.onCanvasFocusObservable.notifyObservers(_this);
  11920. };
  11921. this._onCanvasBlur = function () {
  11922. _this.onCanvasBlurObservable.notifyObservers(_this);
  11923. };
  11924. canvas.addEventListener("focus", this._onCanvasFocus);
  11925. canvas.addEventListener("blur", this._onCanvasBlur);
  11926. this._onBlur = function () {
  11927. if (_this.disablePerformanceMonitorInBackground) {
  11928. _this._performanceMonitor.disable();
  11929. }
  11930. _this._windowIsBackground = true;
  11931. };
  11932. this._onFocus = function () {
  11933. if (_this.disablePerformanceMonitorInBackground) {
  11934. _this._performanceMonitor.enable();
  11935. }
  11936. _this._windowIsBackground = false;
  11937. };
  11938. this._onCanvasPointerOut = function (ev) {
  11939. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11940. };
  11941. window.addEventListener("blur", this._onBlur);
  11942. window.addEventListener("focus", this._onFocus);
  11943. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11944. // Context lost
  11945. if (!this._doNotHandleContextLost) {
  11946. this._onContextLost = function (evt) {
  11947. evt.preventDefault();
  11948. _this._contextWasLost = true;
  11949. BABYLON.Tools.Warn("WebGL context lost.");
  11950. _this.onContextLostObservable.notifyObservers(_this);
  11951. };
  11952. this._onContextRestored = function (evt) {
  11953. // Adding a timeout to avoid race condition at browser level
  11954. setTimeout(function () {
  11955. // Rebuild gl context
  11956. _this._initGLContext();
  11957. // Rebuild effects
  11958. _this._rebuildEffects();
  11959. // Rebuild textures
  11960. _this._rebuildInternalTextures();
  11961. // Rebuild buffers
  11962. _this._rebuildBuffers();
  11963. // Cache
  11964. _this.wipeCaches(true);
  11965. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11966. _this.onContextRestoredObservable.notifyObservers(_this);
  11967. _this._contextWasLost = false;
  11968. }, 0);
  11969. };
  11970. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11971. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11972. }
  11973. }
  11974. else {
  11975. this._gl = canvasOrContext;
  11976. this._renderingCanvas = this._gl.canvas;
  11977. if (this._gl.renderbufferStorageMultisample) {
  11978. this._webGLVersion = 2.0;
  11979. }
  11980. options.stencil = this._gl.getContextAttributes().stencil;
  11981. }
  11982. // Viewport
  11983. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11984. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11985. this.resize();
  11986. this._isStencilEnable = options.stencil ? true : false;
  11987. this._initGLContext();
  11988. if (canvas) {
  11989. // Fullscreen
  11990. this._onFullscreenChange = function () {
  11991. if (document.fullscreen !== undefined) {
  11992. _this.isFullscreen = document.fullscreen;
  11993. }
  11994. else if (document.mozFullScreen !== undefined) {
  11995. _this.isFullscreen = document.mozFullScreen;
  11996. }
  11997. else if (document.webkitIsFullScreen !== undefined) {
  11998. _this.isFullscreen = document.webkitIsFullScreen;
  11999. }
  12000. else if (document.msIsFullScreen !== undefined) {
  12001. _this.isFullscreen = document.msIsFullScreen;
  12002. }
  12003. // Pointer lock
  12004. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  12005. canvas.requestPointerLock = canvas.requestPointerLock ||
  12006. canvas.msRequestPointerLock ||
  12007. canvas.mozRequestPointerLock ||
  12008. canvas.webkitRequestPointerLock;
  12009. if (canvas.requestPointerLock) {
  12010. canvas.requestPointerLock();
  12011. }
  12012. }
  12013. };
  12014. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  12015. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  12016. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  12017. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  12018. // Pointer lock
  12019. this._onPointerLockChange = function () {
  12020. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  12021. document.webkitPointerLockElement === canvas ||
  12022. document.msPointerLockElement === canvas ||
  12023. document.pointerLockElement === canvas);
  12024. };
  12025. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  12026. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  12027. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  12028. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  12029. this._onVRDisplayPointerRestricted = function () {
  12030. if (canvas) {
  12031. canvas.requestPointerLock();
  12032. }
  12033. };
  12034. this._onVRDisplayPointerUnrestricted = function () {
  12035. document.exitPointerLock();
  12036. };
  12037. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  12038. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  12039. }
  12040. // Create Audio Engine if needed.
  12041. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  12042. Engine.audioEngine = Engine.AudioEngineFactory(this);
  12043. }
  12044. // Prepare buffer pointers
  12045. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12046. this._currentBufferPointers[i] = new BufferPointer();
  12047. }
  12048. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  12049. // Load WebVR Devices
  12050. if (options.autoEnableWebVR) {
  12051. this.initWebVR();
  12052. }
  12053. // Detect if we are running on a faulty buggy OS.
  12054. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  12055. // Detect if we are running on a faulty buggy desktop OS.
  12056. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  12057. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  12058. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  12059. }
  12060. Object.defineProperty(Engine, "LastCreatedEngine", {
  12061. /**
  12062. * Gets the latest created engine
  12063. */
  12064. get: function () {
  12065. if (Engine.Instances.length === 0) {
  12066. return null;
  12067. }
  12068. return Engine.Instances[Engine.Instances.length - 1];
  12069. },
  12070. enumerable: true,
  12071. configurable: true
  12072. });
  12073. Object.defineProperty(Engine, "LastCreatedScene", {
  12074. /**
  12075. * Gets the latest created scene
  12076. */
  12077. get: function () {
  12078. var lastCreatedEngine = Engine.LastCreatedEngine;
  12079. if (!lastCreatedEngine) {
  12080. return null;
  12081. }
  12082. if (lastCreatedEngine.scenes.length === 0) {
  12083. return null;
  12084. }
  12085. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  12086. },
  12087. enumerable: true,
  12088. configurable: true
  12089. });
  12090. /**
  12091. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  12092. * @param flag defines which part of the materials must be marked as dirty
  12093. * @param predicate defines a predicate used to filter which materials should be affected
  12094. */
  12095. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  12096. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  12097. var engine = Engine.Instances[engineIndex];
  12098. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  12099. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  12100. }
  12101. }
  12102. };
  12103. Object.defineProperty(Engine, "Version", {
  12104. /**
  12105. * Returns the current version of the framework
  12106. */
  12107. get: function () {
  12108. return "3.3.0-rc.1";
  12109. },
  12110. enumerable: true,
  12111. configurable: true
  12112. });
  12113. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12114. /**
  12115. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12116. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12117. */
  12118. get: function () {
  12119. return this._vrExclusivePointerMode;
  12120. },
  12121. enumerable: true,
  12122. configurable: true
  12123. });
  12124. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12125. /**
  12126. * Gets a boolean indicating that the engine supports uniform buffers
  12127. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12128. */
  12129. get: function () {
  12130. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12131. },
  12132. enumerable: true,
  12133. configurable: true
  12134. });
  12135. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12136. /**
  12137. * Gets a boolean indicating that only power of 2 textures are supported
  12138. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12139. */
  12140. get: function () {
  12141. return this._webGLVersion < 2 || this.forcePOTTextures;
  12142. },
  12143. enumerable: true,
  12144. configurable: true
  12145. });
  12146. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12147. /**
  12148. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12149. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12150. */
  12151. get: function () {
  12152. return this._doNotHandleContextLost;
  12153. },
  12154. set: function (value) {
  12155. this._doNotHandleContextLost = value;
  12156. },
  12157. enumerable: true,
  12158. configurable: true
  12159. });
  12160. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12161. /**
  12162. * Gets the performance monitor attached to this engine
  12163. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12164. */
  12165. get: function () {
  12166. return this._performanceMonitor;
  12167. },
  12168. enumerable: true,
  12169. configurable: true
  12170. });
  12171. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12172. /**
  12173. * Gets the list of texture formats supported
  12174. */
  12175. get: function () {
  12176. return this._texturesSupported;
  12177. },
  12178. enumerable: true,
  12179. configurable: true
  12180. });
  12181. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12182. /**
  12183. * Gets the list of texture formats in use
  12184. */
  12185. get: function () {
  12186. return this._textureFormatInUse;
  12187. },
  12188. enumerable: true,
  12189. configurable: true
  12190. });
  12191. Object.defineProperty(Engine.prototype, "currentViewport", {
  12192. /**
  12193. * Gets the current viewport
  12194. */
  12195. get: function () {
  12196. return this._cachedViewport;
  12197. },
  12198. enumerable: true,
  12199. configurable: true
  12200. });
  12201. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12202. /**
  12203. * Gets the default empty texture
  12204. */
  12205. get: function () {
  12206. if (!this._emptyTexture) {
  12207. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12208. }
  12209. return this._emptyTexture;
  12210. },
  12211. enumerable: true,
  12212. configurable: true
  12213. });
  12214. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12215. /**
  12216. * Gets the default empty 3D texture
  12217. */
  12218. get: function () {
  12219. if (!this._emptyTexture3D) {
  12220. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12221. }
  12222. return this._emptyTexture3D;
  12223. },
  12224. enumerable: true,
  12225. configurable: true
  12226. });
  12227. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12228. /**
  12229. * Gets the default empty cube texture
  12230. */
  12231. get: function () {
  12232. if (!this._emptyCubeTexture) {
  12233. var faceData = new Uint8Array(4);
  12234. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12235. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12236. }
  12237. return this._emptyCubeTexture;
  12238. },
  12239. enumerable: true,
  12240. configurable: true
  12241. });
  12242. Engine.prototype._rebuildInternalTextures = function () {
  12243. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12244. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12245. var internalTexture = currentState_1[_i];
  12246. internalTexture._rebuild();
  12247. }
  12248. };
  12249. Engine.prototype._rebuildEffects = function () {
  12250. for (var key in this._compiledEffects) {
  12251. var effect = this._compiledEffects[key];
  12252. effect._prepareEffect();
  12253. }
  12254. BABYLON.Effect.ResetCache();
  12255. };
  12256. Engine.prototype._rebuildBuffers = function () {
  12257. // Index / Vertex
  12258. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12259. var scene = _a[_i];
  12260. scene.resetCachedMaterial();
  12261. scene._rebuildGeometries();
  12262. scene._rebuildTextures();
  12263. }
  12264. // Uniforms
  12265. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12266. var uniformBuffer = _c[_b];
  12267. uniformBuffer._rebuild();
  12268. }
  12269. };
  12270. Engine.prototype._initGLContext = function () {
  12271. // Caps
  12272. this._caps = new EngineCapabilities();
  12273. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12274. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12275. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12276. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12277. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12278. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12279. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12280. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12281. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12282. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12283. // Infos
  12284. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12285. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12286. if (rendererInfo != null) {
  12287. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12288. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12289. }
  12290. if (!this._glVendor) {
  12291. this._glVendor = "Unknown vendor";
  12292. }
  12293. if (!this._glRenderer) {
  12294. this._glRenderer = "Unknown renderer";
  12295. }
  12296. // Constants
  12297. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12298. if (this._gl.RGBA16F !== 0x881A) {
  12299. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12300. }
  12301. if (this._gl.RGBA32F !== 0x8814) {
  12302. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12303. }
  12304. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12305. this._gl.DEPTH24_STENCIL8 = 35056;
  12306. }
  12307. // Extensions
  12308. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12309. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12310. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12311. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12312. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12313. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12314. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12315. 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');
  12316. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12317. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12318. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12319. this._caps.highPrecisionShaderSupported = true;
  12320. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12321. if (this._caps.timerQuery) {
  12322. if (this._webGLVersion === 1) {
  12323. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12324. }
  12325. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12326. }
  12327. // Checks if some of the format renders first to allow the use of webgl inspector.
  12328. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12329. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12330. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12331. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12332. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12333. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12334. if (this._webGLVersion > 1) {
  12335. this._gl.HALF_FLOAT_OES = 0x140B;
  12336. }
  12337. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12338. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12339. // Draw buffers
  12340. if (this._webGLVersion > 1) {
  12341. this._caps.drawBuffersExtension = true;
  12342. }
  12343. else {
  12344. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12345. if (drawBuffersExtension !== null) {
  12346. this._caps.drawBuffersExtension = true;
  12347. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12348. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12349. for (var i = 0; i < 16; i++) {
  12350. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12351. }
  12352. }
  12353. else {
  12354. this._caps.drawBuffersExtension = false;
  12355. }
  12356. }
  12357. // Depth Texture
  12358. if (this._webGLVersion > 1) {
  12359. this._caps.depthTextureExtension = true;
  12360. }
  12361. else {
  12362. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12363. if (depthTextureExtension != null) {
  12364. this._caps.depthTextureExtension = true;
  12365. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12366. }
  12367. }
  12368. // Vertex array object
  12369. if (this._webGLVersion > 1) {
  12370. this._caps.vertexArrayObject = true;
  12371. }
  12372. else {
  12373. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12374. if (vertexArrayObjectExtension != null) {
  12375. this._caps.vertexArrayObject = true;
  12376. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12377. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12378. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12379. }
  12380. else {
  12381. this._caps.vertexArrayObject = false;
  12382. }
  12383. }
  12384. // Instances count
  12385. if (this._webGLVersion > 1) {
  12386. this._caps.instancedArrays = true;
  12387. }
  12388. else {
  12389. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12390. if (instanceExtension != null) {
  12391. this._caps.instancedArrays = true;
  12392. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12393. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12394. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12395. }
  12396. else {
  12397. this._caps.instancedArrays = false;
  12398. }
  12399. }
  12400. // Intelligently add supported compressed formats in order to check for.
  12401. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12402. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12403. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12404. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12405. if (this._caps.astc)
  12406. this.texturesSupported.push('-astc.ktx');
  12407. if (this._caps.s3tc)
  12408. this.texturesSupported.push('-dxt.ktx');
  12409. if (this._caps.pvrtc)
  12410. this.texturesSupported.push('-pvrtc.ktx');
  12411. if (this._caps.etc2)
  12412. this.texturesSupported.push('-etc2.ktx');
  12413. if (this._caps.etc1)
  12414. this.texturesSupported.push('-etc1.ktx');
  12415. if (this._gl.getShaderPrecisionFormat) {
  12416. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12417. if (highp) {
  12418. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12419. }
  12420. }
  12421. // Depth buffer
  12422. this.setDepthBuffer(true);
  12423. this.setDepthFunctionToLessOrEqual();
  12424. this.setDepthWrite(true);
  12425. // Texture maps
  12426. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12427. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12428. this._nextFreeTextureSlots.push(slot);
  12429. }
  12430. };
  12431. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12432. /**
  12433. * Gets version of the current webGL context
  12434. */
  12435. get: function () {
  12436. return this._webGLVersion;
  12437. },
  12438. enumerable: true,
  12439. configurable: true
  12440. });
  12441. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12442. /**
  12443. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12444. */
  12445. get: function () {
  12446. return this._isStencilEnable;
  12447. },
  12448. enumerable: true,
  12449. configurable: true
  12450. });
  12451. Engine.prototype._prepareWorkingCanvas = function () {
  12452. if (this._workingCanvas) {
  12453. return;
  12454. }
  12455. this._workingCanvas = document.createElement("canvas");
  12456. var context = this._workingCanvas.getContext("2d");
  12457. if (context) {
  12458. this._workingContext = context;
  12459. }
  12460. };
  12461. /**
  12462. * Reset the texture cache to empty state
  12463. */
  12464. Engine.prototype.resetTextureCache = function () {
  12465. for (var key in this._boundTexturesCache) {
  12466. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12467. continue;
  12468. }
  12469. var boundTexture = this._boundTexturesCache[key];
  12470. if (boundTexture) {
  12471. this._removeDesignatedSlot(boundTexture);
  12472. }
  12473. this._boundTexturesCache[key] = null;
  12474. }
  12475. if (!this.disableTextureBindingOptimization) {
  12476. this._nextFreeTextureSlots = [];
  12477. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12478. this._nextFreeTextureSlots.push(slot);
  12479. }
  12480. }
  12481. this._currentTextureChannel = -1;
  12482. };
  12483. /**
  12484. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12485. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12486. * @returns true if engine is in deterministic lock step mode
  12487. */
  12488. Engine.prototype.isDeterministicLockStep = function () {
  12489. return this._deterministicLockstep;
  12490. };
  12491. /**
  12492. * Gets the max steps when engine is running in deterministic lock step
  12493. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12494. * @returns the max steps
  12495. */
  12496. Engine.prototype.getLockstepMaxSteps = function () {
  12497. return this._lockstepMaxSteps;
  12498. };
  12499. /**
  12500. * Gets an object containing information about the current webGL context
  12501. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12502. */
  12503. Engine.prototype.getGlInfo = function () {
  12504. return {
  12505. vendor: this._glVendor,
  12506. renderer: this._glRenderer,
  12507. version: this._glVersion
  12508. };
  12509. };
  12510. /**
  12511. * Gets current aspect ratio
  12512. * @param camera defines the camera to use to get the aspect ratio
  12513. * @param useScreen defines if screen size must be used (or the current render target if any)
  12514. * @returns a number defining the aspect ratio
  12515. */
  12516. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12517. if (useScreen === void 0) { useScreen = false; }
  12518. var viewport = camera.viewport;
  12519. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12520. };
  12521. /**
  12522. * Gets current screen aspect ratio
  12523. * @returns a number defining the aspect ratio
  12524. */
  12525. Engine.prototype.getScreenAspectRatio = function () {
  12526. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12527. };
  12528. /**
  12529. * Gets the current render width
  12530. * @param useScreen defines if screen size must be used (or the current render target if any)
  12531. * @returns a number defining the current render width
  12532. */
  12533. Engine.prototype.getRenderWidth = function (useScreen) {
  12534. if (useScreen === void 0) { useScreen = false; }
  12535. if (!useScreen && this._currentRenderTarget) {
  12536. return this._currentRenderTarget.width;
  12537. }
  12538. return this._gl.drawingBufferWidth;
  12539. };
  12540. /**
  12541. * Gets the current render height
  12542. * @param useScreen defines if screen size must be used (or the current render target if any)
  12543. * @returns a number defining the current render height
  12544. */
  12545. Engine.prototype.getRenderHeight = function (useScreen) {
  12546. if (useScreen === void 0) { useScreen = false; }
  12547. if (!useScreen && this._currentRenderTarget) {
  12548. return this._currentRenderTarget.height;
  12549. }
  12550. return this._gl.drawingBufferHeight;
  12551. };
  12552. /**
  12553. * Gets the HTML canvas attached with the current webGL context
  12554. * @returns a HTML canvas
  12555. */
  12556. Engine.prototype.getRenderingCanvas = function () {
  12557. return this._renderingCanvas;
  12558. };
  12559. /**
  12560. * Gets the client rect of the HTML canvas attached with the current webGL context
  12561. * @returns a client rectanglee
  12562. */
  12563. Engine.prototype.getRenderingCanvasClientRect = function () {
  12564. if (!this._renderingCanvas) {
  12565. return null;
  12566. }
  12567. return this._renderingCanvas.getBoundingClientRect();
  12568. };
  12569. /**
  12570. * Defines the hardware scaling level.
  12571. * By default the hardware scaling level is computed from the window device ratio.
  12572. * 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.
  12573. * @param level defines the level to use
  12574. */
  12575. Engine.prototype.setHardwareScalingLevel = function (level) {
  12576. this._hardwareScalingLevel = level;
  12577. this.resize();
  12578. };
  12579. /**
  12580. * Gets the current hardware scaling level.
  12581. * By default the hardware scaling level is computed from the window device ratio.
  12582. * 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.
  12583. * @returns a number indicating the current hardware scaling level
  12584. */
  12585. Engine.prototype.getHardwareScalingLevel = function () {
  12586. return this._hardwareScalingLevel;
  12587. };
  12588. /**
  12589. * Gets the list of loaded textures
  12590. * @returns an array containing all loaded textures
  12591. */
  12592. Engine.prototype.getLoadedTexturesCache = function () {
  12593. return this._internalTexturesCache;
  12594. };
  12595. /**
  12596. * Gets the object containing all engine capabilities
  12597. * @returns the EngineCapabilities object
  12598. */
  12599. Engine.prototype.getCaps = function () {
  12600. return this._caps;
  12601. };
  12602. Object.defineProperty(Engine.prototype, "drawCalls", {
  12603. /** @hidden */
  12604. get: function () {
  12605. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12606. return 0;
  12607. },
  12608. enumerable: true,
  12609. configurable: true
  12610. });
  12611. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12612. /** @hidden */
  12613. get: function () {
  12614. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12615. return null;
  12616. },
  12617. enumerable: true,
  12618. configurable: true
  12619. });
  12620. /**
  12621. * Gets the current depth function
  12622. * @returns a number defining the depth function
  12623. */
  12624. Engine.prototype.getDepthFunction = function () {
  12625. return this._depthCullingState.depthFunc;
  12626. };
  12627. /**
  12628. * Sets the current depth function
  12629. * @param depthFunc defines the function to use
  12630. */
  12631. Engine.prototype.setDepthFunction = function (depthFunc) {
  12632. this._depthCullingState.depthFunc = depthFunc;
  12633. };
  12634. /**
  12635. * Sets the current depth function to GREATER
  12636. */
  12637. Engine.prototype.setDepthFunctionToGreater = function () {
  12638. this._depthCullingState.depthFunc = this._gl.GREATER;
  12639. };
  12640. /**
  12641. * Sets the current depth function to GEQUAL
  12642. */
  12643. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12644. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12645. };
  12646. /**
  12647. * Sets the current depth function to LESS
  12648. */
  12649. Engine.prototype.setDepthFunctionToLess = function () {
  12650. this._depthCullingState.depthFunc = this._gl.LESS;
  12651. };
  12652. /**
  12653. * Sets the current depth function to LEQUAL
  12654. */
  12655. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12656. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12657. };
  12658. /**
  12659. * Gets a boolean indicating if stencil buffer is enabled
  12660. * @returns the current stencil buffer state
  12661. */
  12662. Engine.prototype.getStencilBuffer = function () {
  12663. return this._stencilState.stencilTest;
  12664. };
  12665. /**
  12666. * Enable or disable the stencil buffer
  12667. * @param enable defines if the stencil buffer must be enabled or disabled
  12668. */
  12669. Engine.prototype.setStencilBuffer = function (enable) {
  12670. this._stencilState.stencilTest = enable;
  12671. };
  12672. /**
  12673. * Gets the current stencil mask
  12674. * @returns a number defining the new stencil mask to use
  12675. */
  12676. Engine.prototype.getStencilMask = function () {
  12677. return this._stencilState.stencilMask;
  12678. };
  12679. /**
  12680. * Sets the current stencil mask
  12681. * @param mask defines the new stencil mask to use
  12682. */
  12683. Engine.prototype.setStencilMask = function (mask) {
  12684. this._stencilState.stencilMask = mask;
  12685. };
  12686. /**
  12687. * Gets the current stencil function
  12688. * @returns a number defining the stencil function to use
  12689. */
  12690. Engine.prototype.getStencilFunction = function () {
  12691. return this._stencilState.stencilFunc;
  12692. };
  12693. /**
  12694. * Gets the current stencil reference value
  12695. * @returns a number defining the stencil reference value to use
  12696. */
  12697. Engine.prototype.getStencilFunctionReference = function () {
  12698. return this._stencilState.stencilFuncRef;
  12699. };
  12700. /**
  12701. * Gets the current stencil mask
  12702. * @returns a number defining the stencil mask to use
  12703. */
  12704. Engine.prototype.getStencilFunctionMask = function () {
  12705. return this._stencilState.stencilFuncMask;
  12706. };
  12707. /**
  12708. * Sets the current stencil function
  12709. * @param stencilFunc defines the new stencil function to use
  12710. */
  12711. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12712. this._stencilState.stencilFunc = stencilFunc;
  12713. };
  12714. /**
  12715. * Sets the current stencil reference
  12716. * @param reference defines the new stencil reference to use
  12717. */
  12718. Engine.prototype.setStencilFunctionReference = function (reference) {
  12719. this._stencilState.stencilFuncRef = reference;
  12720. };
  12721. /**
  12722. * Sets the current stencil mask
  12723. * @param mask defines the new stencil mask to use
  12724. */
  12725. Engine.prototype.setStencilFunctionMask = function (mask) {
  12726. this._stencilState.stencilFuncMask = mask;
  12727. };
  12728. /**
  12729. * Gets the current stencil operation when stencil fails
  12730. * @returns a number defining stencil operation to use when stencil fails
  12731. */
  12732. Engine.prototype.getStencilOperationFail = function () {
  12733. return this._stencilState.stencilOpStencilFail;
  12734. };
  12735. /**
  12736. * Gets the current stencil operation when depth fails
  12737. * @returns a number defining stencil operation to use when depth fails
  12738. */
  12739. Engine.prototype.getStencilOperationDepthFail = function () {
  12740. return this._stencilState.stencilOpDepthFail;
  12741. };
  12742. /**
  12743. * Gets the current stencil operation when stencil passes
  12744. * @returns a number defining stencil operation to use when stencil passes
  12745. */
  12746. Engine.prototype.getStencilOperationPass = function () {
  12747. return this._stencilState.stencilOpStencilDepthPass;
  12748. };
  12749. /**
  12750. * Sets the stencil operation to use when stencil fails
  12751. * @param operation defines the stencil operation to use when stencil fails
  12752. */
  12753. Engine.prototype.setStencilOperationFail = function (operation) {
  12754. this._stencilState.stencilOpStencilFail = operation;
  12755. };
  12756. /**
  12757. * Sets the stencil operation to use when depth fails
  12758. * @param operation defines the stencil operation to use when depth fails
  12759. */
  12760. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12761. this._stencilState.stencilOpDepthFail = operation;
  12762. };
  12763. /**
  12764. * Sets the stencil operation to use when stencil passes
  12765. * @param operation defines the stencil operation to use when stencil passes
  12766. */
  12767. Engine.prototype.setStencilOperationPass = function (operation) {
  12768. this._stencilState.stencilOpStencilDepthPass = operation;
  12769. };
  12770. /**
  12771. * Sets a boolean indicating if the dithering state is enabled or disabled
  12772. * @param value defines the dithering state
  12773. */
  12774. Engine.prototype.setDitheringState = function (value) {
  12775. if (value) {
  12776. this._gl.enable(this._gl.DITHER);
  12777. }
  12778. else {
  12779. this._gl.disable(this._gl.DITHER);
  12780. }
  12781. };
  12782. /**
  12783. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12784. * @param value defines the rasterizer state
  12785. */
  12786. Engine.prototype.setRasterizerState = function (value) {
  12787. if (value) {
  12788. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12789. }
  12790. else {
  12791. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12792. }
  12793. };
  12794. /**
  12795. * stop executing a render loop function and remove it from the execution array
  12796. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12797. */
  12798. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12799. if (!renderFunction) {
  12800. this._activeRenderLoops = [];
  12801. return;
  12802. }
  12803. var index = this._activeRenderLoops.indexOf(renderFunction);
  12804. if (index >= 0) {
  12805. this._activeRenderLoops.splice(index, 1);
  12806. }
  12807. };
  12808. /** @hidden */
  12809. Engine.prototype._renderLoop = function () {
  12810. if (!this._contextWasLost) {
  12811. var shouldRender = true;
  12812. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12813. shouldRender = false;
  12814. }
  12815. if (shouldRender) {
  12816. // Start new frame
  12817. this.beginFrame();
  12818. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12819. var renderFunction = this._activeRenderLoops[index];
  12820. renderFunction();
  12821. }
  12822. // Present
  12823. this.endFrame();
  12824. }
  12825. }
  12826. if (this._activeRenderLoops.length > 0) {
  12827. // Register new frame
  12828. var requester = null;
  12829. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12830. requester = this._vrDisplay;
  12831. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12832. }
  12833. else {
  12834. this._renderingQueueLaunched = false;
  12835. }
  12836. };
  12837. /**
  12838. * Register and execute a render loop. The engine can have more than one render function
  12839. * @param renderFunction defines the function to continuously execute
  12840. */
  12841. Engine.prototype.runRenderLoop = function (renderFunction) {
  12842. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12843. return;
  12844. }
  12845. this._activeRenderLoops.push(renderFunction);
  12846. if (!this._renderingQueueLaunched) {
  12847. this._renderingQueueLaunched = true;
  12848. this._bindedRenderFunction = this._renderLoop.bind(this);
  12849. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12850. }
  12851. };
  12852. /**
  12853. * Toggle full screen mode
  12854. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12855. */
  12856. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12857. if (this.isFullscreen) {
  12858. BABYLON.Tools.ExitFullscreen();
  12859. }
  12860. else {
  12861. this._pointerLockRequested = requestPointerLock;
  12862. if (this._renderingCanvas) {
  12863. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12864. }
  12865. }
  12866. };
  12867. /**
  12868. * Clear the current render buffer or the current render target (if any is set up)
  12869. * @param color defines the color to use
  12870. * @param backBuffer defines if the back buffer must be cleared
  12871. * @param depth defines if the depth buffer must be cleared
  12872. * @param stencil defines if the stencil buffer must be cleared
  12873. */
  12874. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12875. if (stencil === void 0) { stencil = false; }
  12876. this.applyStates();
  12877. var mode = 0;
  12878. if (backBuffer && color) {
  12879. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12880. mode |= this._gl.COLOR_BUFFER_BIT;
  12881. }
  12882. if (depth) {
  12883. this._gl.clearDepth(1.0);
  12884. mode |= this._gl.DEPTH_BUFFER_BIT;
  12885. }
  12886. if (stencil) {
  12887. this._gl.clearStencil(0);
  12888. mode |= this._gl.STENCIL_BUFFER_BIT;
  12889. }
  12890. this._gl.clear(mode);
  12891. };
  12892. /**
  12893. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12894. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12895. * @param y defines the y-coordinate of the corner of the clear rectangle
  12896. * @param width defines the width of the clear rectangle
  12897. * @param height defines the height of the clear rectangle
  12898. * @param clearColor defines the clear color
  12899. */
  12900. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12901. var gl = this._gl;
  12902. // Save state
  12903. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12904. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12905. // Change state
  12906. gl.enable(gl.SCISSOR_TEST);
  12907. gl.scissor(x, y, width, height);
  12908. // Clear
  12909. this.clear(clearColor, true, true, true);
  12910. // Restore state
  12911. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12912. if (curScissor === true) {
  12913. gl.enable(gl.SCISSOR_TEST);
  12914. }
  12915. else {
  12916. gl.disable(gl.SCISSOR_TEST);
  12917. }
  12918. };
  12919. /** @hidden */
  12920. Engine.prototype._viewport = function (x, y, width, height) {
  12921. if (x !== this._viewportCached.x ||
  12922. y !== this._viewportCached.y ||
  12923. width !== this._viewportCached.z ||
  12924. height !== this._viewportCached.w) {
  12925. this._viewportCached.x = x;
  12926. this._viewportCached.y = y;
  12927. this._viewportCached.z = width;
  12928. this._viewportCached.w = height;
  12929. this._gl.viewport(x, y, width, height);
  12930. }
  12931. };
  12932. /**
  12933. * Set the WebGL's viewport
  12934. * @param viewport defines the viewport element to be used
  12935. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12936. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12937. */
  12938. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12939. var width = requiredWidth || this.getRenderWidth();
  12940. var height = requiredHeight || this.getRenderHeight();
  12941. var x = viewport.x || 0;
  12942. var y = viewport.y || 0;
  12943. this._cachedViewport = viewport;
  12944. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12945. };
  12946. /**
  12947. * Directly set the WebGL Viewport
  12948. * @param x defines the x coordinate of the viewport (in screen space)
  12949. * @param y defines the y coordinate of the viewport (in screen space)
  12950. * @param width defines the width of the viewport (in screen space)
  12951. * @param height defines the height of the viewport (in screen space)
  12952. * @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
  12953. */
  12954. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12955. var currentViewport = this._cachedViewport;
  12956. this._cachedViewport = null;
  12957. this._viewport(x, y, width, height);
  12958. return currentViewport;
  12959. };
  12960. /**
  12961. * Begin a new frame
  12962. */
  12963. Engine.prototype.beginFrame = function () {
  12964. this.onBeginFrameObservable.notifyObservers(this);
  12965. this._measureFps();
  12966. };
  12967. /**
  12968. * Enf the current frame
  12969. */
  12970. Engine.prototype.endFrame = function () {
  12971. // Force a flush in case we are using a bad OS.
  12972. if (this._badOS) {
  12973. this.flushFramebuffer();
  12974. }
  12975. // Submit frame to the vr device, if enabled
  12976. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12977. // TODO: We should only submit the frame if we read frameData successfully.
  12978. this._vrDisplay.submitFrame();
  12979. }
  12980. this.onEndFrameObservable.notifyObservers(this);
  12981. };
  12982. /**
  12983. * Resize the view according to the canvas' size
  12984. */
  12985. Engine.prototype.resize = function () {
  12986. // We're not resizing the size of the canvas while in VR mode & presenting
  12987. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12988. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12989. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12990. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12991. }
  12992. };
  12993. /**
  12994. * Force a specific size of the canvas
  12995. * @param width defines the new canvas' width
  12996. * @param height defines the new canvas' height
  12997. */
  12998. Engine.prototype.setSize = function (width, height) {
  12999. if (!this._renderingCanvas) {
  13000. return;
  13001. }
  13002. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13003. return;
  13004. }
  13005. this._renderingCanvas.width = width;
  13006. this._renderingCanvas.height = height;
  13007. for (var index = 0; index < this.scenes.length; index++) {
  13008. var scene = this.scenes[index];
  13009. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13010. var cam = scene.cameras[camIndex];
  13011. cam._currentRenderId = 0;
  13012. }
  13013. }
  13014. if (this.onResizeObservable.hasObservers) {
  13015. this.onResizeObservable.notifyObservers(this);
  13016. }
  13017. };
  13018. // WebVR functions
  13019. /**
  13020. * Gets a boolean indicating if a webVR device was detected
  13021. * @returns true if a webVR device was detected
  13022. */
  13023. Engine.prototype.isVRDevicePresent = function () {
  13024. return !!this._vrDisplay;
  13025. };
  13026. /**
  13027. * Gets the current webVR device
  13028. * @returns the current webVR device (or null)
  13029. */
  13030. Engine.prototype.getVRDevice = function () {
  13031. return this._vrDisplay;
  13032. };
  13033. /**
  13034. * Initializes a webVR display and starts listening to display change events
  13035. * The onVRDisplayChangedObservable will be notified upon these changes
  13036. * @returns The onVRDisplayChangedObservable
  13037. */
  13038. Engine.prototype.initWebVR = function () {
  13039. this.initWebVRAsync();
  13040. return this.onVRDisplayChangedObservable;
  13041. };
  13042. /**
  13043. * Initializes a webVR display and starts listening to display change events
  13044. * The onVRDisplayChangedObservable will be notified upon these changes
  13045. * @returns A promise containing a VRDisplay and if vr is supported
  13046. */
  13047. Engine.prototype.initWebVRAsync = function () {
  13048. var _this = this;
  13049. var notifyObservers = function () {
  13050. var eventArgs = {
  13051. vrDisplay: _this._vrDisplay,
  13052. vrSupported: _this._vrSupported
  13053. };
  13054. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13055. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13056. };
  13057. if (!this._onVrDisplayConnect) {
  13058. this._onVrDisplayConnect = function (event) {
  13059. _this._vrDisplay = event.display;
  13060. notifyObservers();
  13061. };
  13062. this._onVrDisplayDisconnect = function () {
  13063. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13064. _this._vrDisplay = undefined;
  13065. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13066. notifyObservers();
  13067. };
  13068. this._onVrDisplayPresentChange = function () {
  13069. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13070. };
  13071. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13072. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13073. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13074. }
  13075. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13076. this._webVRInitPromise.then(notifyObservers);
  13077. return this._webVRInitPromise;
  13078. };
  13079. /**
  13080. * Call this function to switch to webVR mode
  13081. * Will do nothing if webVR is not supported or if there is no webVR device
  13082. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13083. */
  13084. Engine.prototype.enableVR = function () {
  13085. var _this = this;
  13086. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13087. var onResolved = function () {
  13088. _this.onVRRequestPresentComplete.notifyObservers(true);
  13089. _this._onVRFullScreenTriggered();
  13090. };
  13091. var onRejected = function () {
  13092. _this.onVRRequestPresentComplete.notifyObservers(false);
  13093. };
  13094. this.onVRRequestPresentStart.notifyObservers(this);
  13095. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13096. }
  13097. };
  13098. /**
  13099. * Call this function to leave webVR mode
  13100. * Will do nothing if webVR is not supported or if there is no webVR device
  13101. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13102. */
  13103. Engine.prototype.disableVR = function () {
  13104. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13105. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13106. }
  13107. };
  13108. Engine.prototype._getVRDisplaysAsync = function () {
  13109. var _this = this;
  13110. return new Promise(function (res, rej) {
  13111. if (navigator.getVRDisplays) {
  13112. navigator.getVRDisplays().then(function (devices) {
  13113. _this._vrSupported = true;
  13114. // note that devices may actually be an empty array. This is fine;
  13115. // we expect this._vrDisplay to be undefined in this case.
  13116. _this._vrDisplay = devices[0];
  13117. res({
  13118. vrDisplay: _this._vrDisplay,
  13119. vrSupported: _this._vrSupported
  13120. });
  13121. });
  13122. }
  13123. else {
  13124. _this._vrDisplay = undefined;
  13125. _this._vrSupported = false;
  13126. res({
  13127. vrDisplay: _this._vrDisplay,
  13128. vrSupported: _this._vrSupported
  13129. });
  13130. }
  13131. });
  13132. };
  13133. /**
  13134. * Binds the frame buffer to the specified texture.
  13135. * @param texture The texture to render to or null for the default canvas
  13136. * @param faceIndex The face of the texture to render to in case of cube texture
  13137. * @param requiredWidth The width of the target to render to
  13138. * @param requiredHeight The height of the target to render to
  13139. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13140. * @param depthStencilTexture The depth stencil texture to use to render
  13141. * @param lodLevel defines le lod level to bind to the frame buffer
  13142. */
  13143. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13144. if (lodLevel === void 0) { lodLevel = 0; }
  13145. if (this._currentRenderTarget) {
  13146. this.unBindFramebuffer(this._currentRenderTarget);
  13147. }
  13148. this._currentRenderTarget = texture;
  13149. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13150. var gl = this._gl;
  13151. if (texture.isCube) {
  13152. if (faceIndex === undefined) {
  13153. faceIndex = 0;
  13154. }
  13155. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13156. if (depthStencilTexture) {
  13157. if (depthStencilTexture._generateStencilBuffer) {
  13158. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13159. }
  13160. else {
  13161. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13162. }
  13163. }
  13164. }
  13165. if (this._cachedViewport && !forceFullscreenViewport) {
  13166. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13167. }
  13168. else {
  13169. if (!requiredWidth) {
  13170. requiredWidth = texture.width;
  13171. if (lodLevel) {
  13172. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13173. }
  13174. }
  13175. if (!requiredHeight) {
  13176. requiredHeight = texture.height;
  13177. if (lodLevel) {
  13178. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13179. }
  13180. }
  13181. this._viewport(0, 0, requiredWidth, requiredHeight);
  13182. }
  13183. this.wipeCaches();
  13184. };
  13185. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13186. if (this._currentFramebuffer !== framebuffer) {
  13187. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13188. this._currentFramebuffer = framebuffer;
  13189. }
  13190. };
  13191. /**
  13192. * Unbind the current render target texture from the webGL context
  13193. * @param texture defines the render target texture to unbind
  13194. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13195. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13196. */
  13197. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13198. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13199. this._currentRenderTarget = null;
  13200. // If MSAA, we need to bitblt back to main texture
  13201. var gl = this._gl;
  13202. if (texture._MSAAFramebuffer) {
  13203. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13204. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13205. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13206. }
  13207. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13208. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13209. gl.generateMipmap(gl.TEXTURE_2D);
  13210. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13211. }
  13212. if (onBeforeUnbind) {
  13213. if (texture._MSAAFramebuffer) {
  13214. // Bind the correct framebuffer
  13215. this.bindUnboundFramebuffer(texture._framebuffer);
  13216. }
  13217. onBeforeUnbind();
  13218. }
  13219. this.bindUnboundFramebuffer(null);
  13220. };
  13221. /**
  13222. * Unbind a list of render target textures from the webGL context
  13223. * This is used only when drawBuffer extension or webGL2 are active
  13224. * @param textures defines the render target textures to unbind
  13225. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13226. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13227. */
  13228. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13229. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13230. this._currentRenderTarget = null;
  13231. // If MSAA, we need to bitblt back to main texture
  13232. var gl = this._gl;
  13233. if (textures[0]._MSAAFramebuffer) {
  13234. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13235. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13236. var attachments = textures[0]._attachments;
  13237. if (!attachments) {
  13238. attachments = new Array(textures.length);
  13239. textures[0]._attachments = attachments;
  13240. }
  13241. for (var i = 0; i < textures.length; i++) {
  13242. var texture = textures[i];
  13243. for (var j = 0; j < attachments.length; j++) {
  13244. attachments[j] = gl.NONE;
  13245. }
  13246. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13247. gl.readBuffer(attachments[i]);
  13248. gl.drawBuffers(attachments);
  13249. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13250. }
  13251. for (var i = 0; i < attachments.length; i++) {
  13252. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13253. }
  13254. gl.drawBuffers(attachments);
  13255. }
  13256. for (var i = 0; i < textures.length; i++) {
  13257. var texture = textures[i];
  13258. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13259. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13260. gl.generateMipmap(gl.TEXTURE_2D);
  13261. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13262. }
  13263. }
  13264. if (onBeforeUnbind) {
  13265. if (textures[0]._MSAAFramebuffer) {
  13266. // Bind the correct framebuffer
  13267. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13268. }
  13269. onBeforeUnbind();
  13270. }
  13271. this.bindUnboundFramebuffer(null);
  13272. };
  13273. /**
  13274. * Force the mipmap generation for the given render target texture
  13275. * @param texture defines the render target texture to use
  13276. */
  13277. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13278. if (texture.generateMipMaps) {
  13279. var gl = this._gl;
  13280. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13281. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13282. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13283. }
  13284. };
  13285. /**
  13286. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13287. */
  13288. Engine.prototype.flushFramebuffer = function () {
  13289. this._gl.flush();
  13290. };
  13291. /**
  13292. * Unbind the current render target and bind the default framebuffer
  13293. */
  13294. Engine.prototype.restoreDefaultFramebuffer = function () {
  13295. if (this._currentRenderTarget) {
  13296. this.unBindFramebuffer(this._currentRenderTarget);
  13297. }
  13298. else {
  13299. this.bindUnboundFramebuffer(null);
  13300. }
  13301. if (this._cachedViewport) {
  13302. this.setViewport(this._cachedViewport);
  13303. }
  13304. this.wipeCaches();
  13305. };
  13306. // UBOs
  13307. /**
  13308. * Create an uniform buffer
  13309. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13310. * @param elements defines the content of the uniform buffer
  13311. * @returns the webGL uniform buffer
  13312. */
  13313. Engine.prototype.createUniformBuffer = function (elements) {
  13314. var ubo = this._gl.createBuffer();
  13315. if (!ubo) {
  13316. throw new Error("Unable to create uniform buffer");
  13317. }
  13318. this.bindUniformBuffer(ubo);
  13319. if (elements instanceof Float32Array) {
  13320. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13321. }
  13322. else {
  13323. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13324. }
  13325. this.bindUniformBuffer(null);
  13326. ubo.references = 1;
  13327. return ubo;
  13328. };
  13329. /**
  13330. * Create a dynamic uniform buffer
  13331. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13332. * @param elements defines the content of the uniform buffer
  13333. * @returns the webGL uniform buffer
  13334. */
  13335. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13336. var ubo = this._gl.createBuffer();
  13337. if (!ubo) {
  13338. throw new Error("Unable to create dynamic uniform buffer");
  13339. }
  13340. this.bindUniformBuffer(ubo);
  13341. if (elements instanceof Float32Array) {
  13342. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13343. }
  13344. else {
  13345. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13346. }
  13347. this.bindUniformBuffer(null);
  13348. ubo.references = 1;
  13349. return ubo;
  13350. };
  13351. /**
  13352. * Update an existing uniform buffer
  13353. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13354. * @param uniformBuffer defines the target uniform buffer
  13355. * @param elements defines the content to update
  13356. * @param offset defines the offset in the uniform buffer where update should start
  13357. * @param count defines the size of the data to update
  13358. */
  13359. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13360. this.bindUniformBuffer(uniformBuffer);
  13361. if (offset === undefined) {
  13362. offset = 0;
  13363. }
  13364. if (count === undefined) {
  13365. if (elements instanceof Float32Array) {
  13366. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13367. }
  13368. else {
  13369. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13370. }
  13371. }
  13372. else {
  13373. if (elements instanceof Float32Array) {
  13374. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13375. }
  13376. else {
  13377. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13378. }
  13379. }
  13380. this.bindUniformBuffer(null);
  13381. };
  13382. // VBOs
  13383. Engine.prototype._resetVertexBufferBinding = function () {
  13384. this.bindArrayBuffer(null);
  13385. this._cachedVertexBuffers = null;
  13386. };
  13387. /**
  13388. * Creates a vertex buffer
  13389. * @param data the data for the vertex buffer
  13390. * @returns the new WebGL static buffer
  13391. */
  13392. Engine.prototype.createVertexBuffer = function (data) {
  13393. var vbo = this._gl.createBuffer();
  13394. if (!vbo) {
  13395. throw new Error("Unable to create vertex buffer");
  13396. }
  13397. this.bindArrayBuffer(vbo);
  13398. if (data instanceof Array) {
  13399. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13400. }
  13401. else {
  13402. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13403. }
  13404. this._resetVertexBufferBinding();
  13405. vbo.references = 1;
  13406. return vbo;
  13407. };
  13408. /**
  13409. * Creates a dynamic vertex buffer
  13410. * @param data the data for the dynamic vertex buffer
  13411. * @returns the new WebGL dynamic buffer
  13412. */
  13413. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13414. var vbo = this._gl.createBuffer();
  13415. if (!vbo) {
  13416. throw new Error("Unable to create dynamic vertex buffer");
  13417. }
  13418. this.bindArrayBuffer(vbo);
  13419. if (data instanceof Array) {
  13420. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13421. }
  13422. else {
  13423. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13424. }
  13425. this._resetVertexBufferBinding();
  13426. vbo.references = 1;
  13427. return vbo;
  13428. };
  13429. /**
  13430. * Update a dynamic index buffer
  13431. * @param indexBuffer defines the target index buffer
  13432. * @param indices defines the data to update
  13433. * @param offset defines the offset in the target index buffer where update should start
  13434. */
  13435. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13436. if (offset === void 0) { offset = 0; }
  13437. // Force cache update
  13438. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13439. this.bindIndexBuffer(indexBuffer);
  13440. var arrayBuffer;
  13441. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13442. arrayBuffer = indices;
  13443. }
  13444. else {
  13445. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13446. }
  13447. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13448. this._resetIndexBufferBinding();
  13449. };
  13450. /**
  13451. * Updates a dynamic vertex buffer.
  13452. * @param vertexBuffer the vertex buffer to update
  13453. * @param data the data used to update the vertex buffer
  13454. * @param byteOffset the byte offset of the data
  13455. * @param byteLength the byte length of the data
  13456. */
  13457. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13458. this.bindArrayBuffer(vertexBuffer);
  13459. if (byteOffset === undefined) {
  13460. byteOffset = 0;
  13461. }
  13462. if (byteLength === undefined) {
  13463. if (data instanceof Array) {
  13464. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13465. }
  13466. else {
  13467. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13468. }
  13469. }
  13470. else {
  13471. if (data instanceof Array) {
  13472. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13473. }
  13474. else {
  13475. if (data instanceof ArrayBuffer) {
  13476. data = new Uint8Array(data, byteOffset, byteLength);
  13477. }
  13478. else {
  13479. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13480. }
  13481. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13482. }
  13483. }
  13484. this._resetVertexBufferBinding();
  13485. };
  13486. Engine.prototype._resetIndexBufferBinding = function () {
  13487. this.bindIndexBuffer(null);
  13488. this._cachedIndexBuffer = null;
  13489. };
  13490. /**
  13491. * Creates a new index buffer
  13492. * @param indices defines the content of the index buffer
  13493. * @param updatable defines if the index buffer must be updatable
  13494. * @returns a new webGL buffer
  13495. */
  13496. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13497. var vbo = this._gl.createBuffer();
  13498. if (!vbo) {
  13499. throw new Error("Unable to create index buffer");
  13500. }
  13501. this.bindIndexBuffer(vbo);
  13502. // Check for 32 bits indices
  13503. var arrayBuffer;
  13504. var need32Bits = false;
  13505. if (indices instanceof Uint16Array) {
  13506. arrayBuffer = indices;
  13507. }
  13508. else {
  13509. //check 32 bit support
  13510. if (this._caps.uintIndices) {
  13511. if (indices instanceof Uint32Array) {
  13512. arrayBuffer = indices;
  13513. need32Bits = true;
  13514. }
  13515. else {
  13516. //number[] or Int32Array, check if 32 bit is necessary
  13517. for (var index = 0; index < indices.length; index++) {
  13518. if (indices[index] > 65535) {
  13519. need32Bits = true;
  13520. break;
  13521. }
  13522. }
  13523. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13524. }
  13525. }
  13526. else {
  13527. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13528. arrayBuffer = new Uint16Array(indices);
  13529. }
  13530. }
  13531. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13532. this._resetIndexBufferBinding();
  13533. vbo.references = 1;
  13534. vbo.is32Bits = need32Bits;
  13535. return vbo;
  13536. };
  13537. /**
  13538. * Bind a webGL buffer to the webGL context
  13539. * @param buffer defines the buffer to bind
  13540. */
  13541. Engine.prototype.bindArrayBuffer = function (buffer) {
  13542. if (!this._vaoRecordInProgress) {
  13543. this._unbindVertexArrayObject();
  13544. }
  13545. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13546. };
  13547. /**
  13548. * Bind an uniform buffer to the current webGL context
  13549. * @param buffer defines the buffer to bind
  13550. */
  13551. Engine.prototype.bindUniformBuffer = function (buffer) {
  13552. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13553. };
  13554. /**
  13555. * Bind a buffer to the current webGL context at a given location
  13556. * @param buffer defines the buffer to bind
  13557. * @param location defines the index where to bind the buffer
  13558. */
  13559. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13560. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13561. };
  13562. /**
  13563. * Bind a specific block at a given index in a specific shader program
  13564. * @param shaderProgram defines the shader program
  13565. * @param blockName defines the block name
  13566. * @param index defines the index where to bind the block
  13567. */
  13568. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13569. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13570. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13571. };
  13572. ;
  13573. Engine.prototype.bindIndexBuffer = function (buffer) {
  13574. if (!this._vaoRecordInProgress) {
  13575. this._unbindVertexArrayObject();
  13576. }
  13577. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13578. };
  13579. Engine.prototype.bindBuffer = function (buffer, target) {
  13580. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13581. this._gl.bindBuffer(target, buffer);
  13582. this._currentBoundBuffer[target] = buffer;
  13583. }
  13584. };
  13585. /**
  13586. * update the bound buffer with the given data
  13587. * @param data defines the data to update
  13588. */
  13589. Engine.prototype.updateArrayBuffer = function (data) {
  13590. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13591. };
  13592. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13593. var pointer = this._currentBufferPointers[indx];
  13594. var changed = false;
  13595. if (!pointer.active) {
  13596. changed = true;
  13597. pointer.active = true;
  13598. pointer.index = indx;
  13599. pointer.size = size;
  13600. pointer.type = type;
  13601. pointer.normalized = normalized;
  13602. pointer.stride = stride;
  13603. pointer.offset = offset;
  13604. pointer.buffer = buffer;
  13605. }
  13606. else {
  13607. if (pointer.buffer !== buffer) {
  13608. pointer.buffer = buffer;
  13609. changed = true;
  13610. }
  13611. if (pointer.size !== size) {
  13612. pointer.size = size;
  13613. changed = true;
  13614. }
  13615. if (pointer.type !== type) {
  13616. pointer.type = type;
  13617. changed = true;
  13618. }
  13619. if (pointer.normalized !== normalized) {
  13620. pointer.normalized = normalized;
  13621. changed = true;
  13622. }
  13623. if (pointer.stride !== stride) {
  13624. pointer.stride = stride;
  13625. changed = true;
  13626. }
  13627. if (pointer.offset !== offset) {
  13628. pointer.offset = offset;
  13629. changed = true;
  13630. }
  13631. }
  13632. if (changed || this._vaoRecordInProgress) {
  13633. this.bindArrayBuffer(buffer);
  13634. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13635. }
  13636. };
  13637. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13638. if (indexBuffer == null) {
  13639. return;
  13640. }
  13641. if (this._cachedIndexBuffer !== indexBuffer) {
  13642. this._cachedIndexBuffer = indexBuffer;
  13643. this.bindIndexBuffer(indexBuffer);
  13644. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13645. }
  13646. };
  13647. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13648. var attributes = effect.getAttributesNames();
  13649. if (!this._vaoRecordInProgress) {
  13650. this._unbindVertexArrayObject();
  13651. }
  13652. this.unbindAllAttributes();
  13653. for (var index = 0; index < attributes.length; index++) {
  13654. var order = effect.getAttributeLocation(index);
  13655. if (order >= 0) {
  13656. var vertexBuffer = vertexBuffers[attributes[index]];
  13657. if (!vertexBuffer) {
  13658. continue;
  13659. }
  13660. this._gl.enableVertexAttribArray(order);
  13661. if (!this._vaoRecordInProgress) {
  13662. this._vertexAttribArraysEnabled[order] = true;
  13663. }
  13664. var buffer = vertexBuffer.getBuffer();
  13665. if (buffer) {
  13666. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13667. if (vertexBuffer.getIsInstanced()) {
  13668. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13669. if (!this._vaoRecordInProgress) {
  13670. this._currentInstanceLocations.push(order);
  13671. this._currentInstanceBuffers.push(buffer);
  13672. }
  13673. }
  13674. }
  13675. }
  13676. }
  13677. };
  13678. /**
  13679. * Records a vertex array object
  13680. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13681. * @param vertexBuffers defines the list of vertex buffers to store
  13682. * @param indexBuffer defines the index buffer to store
  13683. * @param effect defines the effect to store
  13684. * @returns the new vertex array object
  13685. */
  13686. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13687. var vao = this._gl.createVertexArray();
  13688. this._vaoRecordInProgress = true;
  13689. this._gl.bindVertexArray(vao);
  13690. this._mustWipeVertexAttributes = true;
  13691. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13692. this.bindIndexBuffer(indexBuffer);
  13693. this._vaoRecordInProgress = false;
  13694. this._gl.bindVertexArray(null);
  13695. return vao;
  13696. };
  13697. /**
  13698. * Bind a specific vertex array object
  13699. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13700. * @param vertexArrayObject defines the vertex array object to bind
  13701. * @param indexBuffer defines the index buffer to bind
  13702. */
  13703. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13704. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13705. this._cachedVertexArrayObject = vertexArrayObject;
  13706. this._gl.bindVertexArray(vertexArrayObject);
  13707. this._cachedVertexBuffers = null;
  13708. this._cachedIndexBuffer = null;
  13709. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13710. this._mustWipeVertexAttributes = true;
  13711. }
  13712. };
  13713. /**
  13714. * Bind webGl buffers directly to the webGL context
  13715. * @param vertexBuffer defines the vertex buffer to bind
  13716. * @param indexBuffer defines the index buffer to bind
  13717. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13718. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13719. * @param effect defines the effect associated with the vertex buffer
  13720. */
  13721. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13722. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13723. this._cachedVertexBuffers = vertexBuffer;
  13724. this._cachedEffectForVertexBuffers = effect;
  13725. var attributesCount = effect.getAttributesCount();
  13726. this._unbindVertexArrayObject();
  13727. this.unbindAllAttributes();
  13728. var offset = 0;
  13729. for (var index = 0; index < attributesCount; index++) {
  13730. if (index < vertexDeclaration.length) {
  13731. var order = effect.getAttributeLocation(index);
  13732. if (order >= 0) {
  13733. this._gl.enableVertexAttribArray(order);
  13734. this._vertexAttribArraysEnabled[order] = true;
  13735. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13736. }
  13737. offset += vertexDeclaration[index] * 4;
  13738. }
  13739. }
  13740. }
  13741. this._bindIndexBufferWithCache(indexBuffer);
  13742. };
  13743. Engine.prototype._unbindVertexArrayObject = function () {
  13744. if (!this._cachedVertexArrayObject) {
  13745. return;
  13746. }
  13747. this._cachedVertexArrayObject = null;
  13748. this._gl.bindVertexArray(null);
  13749. };
  13750. /**
  13751. * Bind a list of vertex buffers to the webGL context
  13752. * @param vertexBuffers defines the list of vertex buffers to bind
  13753. * @param indexBuffer defines the index buffer to bind
  13754. * @param effect defines the effect associated with the vertex buffers
  13755. */
  13756. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13757. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13758. this._cachedVertexBuffers = vertexBuffers;
  13759. this._cachedEffectForVertexBuffers = effect;
  13760. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13761. }
  13762. this._bindIndexBufferWithCache(indexBuffer);
  13763. };
  13764. /**
  13765. * Unbind all instance attributes
  13766. */
  13767. Engine.prototype.unbindInstanceAttributes = function () {
  13768. var boundBuffer;
  13769. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13770. var instancesBuffer = this._currentInstanceBuffers[i];
  13771. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13772. boundBuffer = instancesBuffer;
  13773. this.bindArrayBuffer(instancesBuffer);
  13774. }
  13775. var offsetLocation = this._currentInstanceLocations[i];
  13776. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13777. }
  13778. this._currentInstanceBuffers.length = 0;
  13779. this._currentInstanceLocations.length = 0;
  13780. };
  13781. /**
  13782. * Release and free the memory of a vertex array object
  13783. * @param vao defines the vertex array object to delete
  13784. */
  13785. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13786. this._gl.deleteVertexArray(vao);
  13787. };
  13788. /** @hidden */
  13789. Engine.prototype._releaseBuffer = function (buffer) {
  13790. buffer.references--;
  13791. if (buffer.references === 0) {
  13792. this._gl.deleteBuffer(buffer);
  13793. return true;
  13794. }
  13795. return false;
  13796. };
  13797. /**
  13798. * Creates a webGL buffer to use with instanciation
  13799. * @param capacity defines the size of the buffer
  13800. * @returns the webGL buffer
  13801. */
  13802. Engine.prototype.createInstancesBuffer = function (capacity) {
  13803. var buffer = this._gl.createBuffer();
  13804. if (!buffer) {
  13805. throw new Error("Unable to create instance buffer");
  13806. }
  13807. buffer.capacity = capacity;
  13808. this.bindArrayBuffer(buffer);
  13809. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13810. return buffer;
  13811. };
  13812. /**
  13813. * Delete a webGL buffer used with instanciation
  13814. * @param buffer defines the webGL buffer to delete
  13815. */
  13816. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13817. this._gl.deleteBuffer(buffer);
  13818. };
  13819. /**
  13820. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13821. * @param instancesBuffer defines the webGL buffer to update and bind
  13822. * @param data defines the data to store in the buffer
  13823. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13824. */
  13825. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13826. this.bindArrayBuffer(instancesBuffer);
  13827. if (data) {
  13828. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13829. }
  13830. if (offsetLocations[0].index !== undefined) {
  13831. var stride = 0;
  13832. for (var i = 0; i < offsetLocations.length; i++) {
  13833. var ai = offsetLocations[i];
  13834. stride += ai.attributeSize * 4;
  13835. }
  13836. for (var i = 0; i < offsetLocations.length; i++) {
  13837. var ai = offsetLocations[i];
  13838. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13839. this._gl.enableVertexAttribArray(ai.index);
  13840. this._vertexAttribArraysEnabled[ai.index] = true;
  13841. }
  13842. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13843. this._gl.vertexAttribDivisor(ai.index, 1);
  13844. this._currentInstanceLocations.push(ai.index);
  13845. this._currentInstanceBuffers.push(instancesBuffer);
  13846. }
  13847. }
  13848. else {
  13849. for (var index = 0; index < 4; index++) {
  13850. var offsetLocation = offsetLocations[index];
  13851. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13852. this._gl.enableVertexAttribArray(offsetLocation);
  13853. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13854. }
  13855. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13856. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13857. this._currentInstanceLocations.push(offsetLocation);
  13858. this._currentInstanceBuffers.push(instancesBuffer);
  13859. }
  13860. }
  13861. };
  13862. /**
  13863. * Apply all cached states (depth, culling, stencil and alpha)
  13864. */
  13865. Engine.prototype.applyStates = function () {
  13866. this._depthCullingState.apply(this._gl);
  13867. this._stencilState.apply(this._gl);
  13868. this._alphaState.apply(this._gl);
  13869. };
  13870. /**
  13871. * Send a draw order
  13872. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13873. * @param indexStart defines the starting index
  13874. * @param indexCount defines the number of index to draw
  13875. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13876. */
  13877. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13878. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13879. };
  13880. /**
  13881. * Draw a list of points
  13882. * @param verticesStart defines the index of first vertex to draw
  13883. * @param verticesCount defines the count of vertices to draw
  13884. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13885. */
  13886. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13887. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13888. };
  13889. /**
  13890. * Draw a list of unindexed primitives
  13891. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13892. * @param verticesStart defines the index of first vertex to draw
  13893. * @param verticesCount defines the count of vertices to draw
  13894. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13895. */
  13896. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13897. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13898. };
  13899. /**
  13900. * Draw a list of indexed primitives
  13901. * @param fillMode defines the primitive to use
  13902. * @param indexStart defines the starting index
  13903. * @param indexCount defines the number of index to draw
  13904. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13905. */
  13906. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13907. // Apply states
  13908. this.applyStates();
  13909. this._drawCalls.addCount(1, false);
  13910. // Render
  13911. var drawMode = this._drawMode(fillMode);
  13912. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13913. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13914. if (instancesCount) {
  13915. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13916. }
  13917. else {
  13918. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13919. }
  13920. };
  13921. /**
  13922. * Draw a list of unindexed primitives
  13923. * @param fillMode defines the primitive to use
  13924. * @param verticesStart defines the index of first vertex to draw
  13925. * @param verticesCount defines the count of vertices to draw
  13926. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13927. */
  13928. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13929. // Apply states
  13930. this.applyStates();
  13931. this._drawCalls.addCount(1, false);
  13932. var drawMode = this._drawMode(fillMode);
  13933. if (instancesCount) {
  13934. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13935. }
  13936. else {
  13937. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13938. }
  13939. };
  13940. Engine.prototype._drawMode = function (fillMode) {
  13941. switch (fillMode) {
  13942. // Triangle views
  13943. case BABYLON.Material.TriangleFillMode:
  13944. return this._gl.TRIANGLES;
  13945. case BABYLON.Material.PointFillMode:
  13946. return this._gl.POINTS;
  13947. case BABYLON.Material.WireFrameFillMode:
  13948. return this._gl.LINES;
  13949. // Draw modes
  13950. case BABYLON.Material.PointListDrawMode:
  13951. return this._gl.POINTS;
  13952. case BABYLON.Material.LineListDrawMode:
  13953. return this._gl.LINES;
  13954. case BABYLON.Material.LineLoopDrawMode:
  13955. return this._gl.LINE_LOOP;
  13956. case BABYLON.Material.LineStripDrawMode:
  13957. return this._gl.LINE_STRIP;
  13958. case BABYLON.Material.TriangleStripDrawMode:
  13959. return this._gl.TRIANGLE_STRIP;
  13960. case BABYLON.Material.TriangleFanDrawMode:
  13961. return this._gl.TRIANGLE_FAN;
  13962. default:
  13963. return this._gl.TRIANGLES;
  13964. }
  13965. };
  13966. // Shaders
  13967. /** @hidden */
  13968. Engine.prototype._releaseEffect = function (effect) {
  13969. if (this._compiledEffects[effect._key]) {
  13970. delete this._compiledEffects[effect._key];
  13971. this._deleteProgram(effect.getProgram());
  13972. }
  13973. };
  13974. /** @hidden */
  13975. Engine.prototype._deleteProgram = function (program) {
  13976. if (program) {
  13977. program.__SPECTOR_rebuildProgram = null;
  13978. if (program.transformFeedback) {
  13979. this.deleteTransformFeedback(program.transformFeedback);
  13980. program.transformFeedback = null;
  13981. }
  13982. this._gl.deleteProgram(program);
  13983. }
  13984. };
  13985. /**
  13986. * Create a new effect (used to store vertex/fragment shaders)
  13987. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13988. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13989. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13990. * @param samplers defines an array of string used to represent textures
  13991. * @param defines defines the string containing the defines to use to compile the shaders
  13992. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13993. * @param onCompiled defines a function to call when the effect creation is successful
  13994. * @param onError defines a function to call when the effect creation has failed
  13995. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13996. * @returns the new Effect
  13997. */
  13998. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13999. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14000. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14001. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14002. if (this._compiledEffects[name]) {
  14003. var compiledEffect = this._compiledEffects[name];
  14004. if (onCompiled && compiledEffect.isReady()) {
  14005. onCompiled(compiledEffect);
  14006. }
  14007. return compiledEffect;
  14008. }
  14009. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14010. effect._key = name;
  14011. this._compiledEffects[name] = effect;
  14012. return effect;
  14013. };
  14014. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  14015. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  14016. };
  14017. ;
  14018. Engine.prototype._compileRawShader = function (source, type) {
  14019. var gl = this._gl;
  14020. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  14021. gl.shaderSource(shader, source);
  14022. gl.compileShader(shader);
  14023. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  14024. var log = gl.getShaderInfoLog(shader);
  14025. if (log) {
  14026. throw new Error(log);
  14027. }
  14028. }
  14029. if (!shader) {
  14030. throw new Error("Something went wrong while compile the shader.");
  14031. }
  14032. return shader;
  14033. };
  14034. ;
  14035. /**
  14036. * Directly creates a webGL program
  14037. * @param vertexCode defines the vertex shader code to use
  14038. * @param fragmentCode defines the fragment shader code to use
  14039. * @param context defines the webGL context to use (if not set, the current one will be used)
  14040. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14041. * @returns the new webGL program
  14042. */
  14043. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14044. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14045. context = context || this._gl;
  14046. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  14047. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  14048. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14049. };
  14050. /**
  14051. * Creates a webGL program
  14052. * @param vertexCode defines the vertex shader code to use
  14053. * @param fragmentCode defines the fragment shader code to use
  14054. * @param defines defines the string containing the defines to use to compile the shaders
  14055. * @param context defines the webGL context to use (if not set, the current one will be used)
  14056. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14057. * @returns the new webGL program
  14058. */
  14059. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14060. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14061. context = context || this._gl;
  14062. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14063. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14064. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  14065. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  14066. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14067. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14068. return program;
  14069. };
  14070. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14071. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14072. var shaderProgram = context.createProgram();
  14073. if (!shaderProgram) {
  14074. throw new Error("Unable to create program");
  14075. }
  14076. context.attachShader(shaderProgram, vertexShader);
  14077. context.attachShader(shaderProgram, fragmentShader);
  14078. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14079. var transformFeedback = this.createTransformFeedback();
  14080. this.bindTransformFeedback(transformFeedback);
  14081. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14082. shaderProgram.transformFeedback = transformFeedback;
  14083. }
  14084. context.linkProgram(shaderProgram);
  14085. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14086. this.bindTransformFeedback(null);
  14087. }
  14088. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14089. if (!linked) {
  14090. var error = context.getProgramInfoLog(shaderProgram);
  14091. if (error) {
  14092. throw new Error(error);
  14093. }
  14094. }
  14095. if (this.validateShaderPrograms) {
  14096. context.validateProgram(shaderProgram);
  14097. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14098. if (!validated) {
  14099. var error = context.getProgramInfoLog(shaderProgram);
  14100. if (error) {
  14101. throw new Error(error);
  14102. }
  14103. }
  14104. }
  14105. context.deleteShader(vertexShader);
  14106. context.deleteShader(fragmentShader);
  14107. return shaderProgram;
  14108. };
  14109. /**
  14110. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14111. * @param shaderProgram defines the webGL program to use
  14112. * @param uniformsNames defines the list of uniform names
  14113. * @returns an array of webGL uniform locations
  14114. */
  14115. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14116. var results = new Array();
  14117. for (var index = 0; index < uniformsNames.length; index++) {
  14118. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14119. }
  14120. return results;
  14121. };
  14122. /**
  14123. * Gets the lsit of active attributes for a given webGL program
  14124. * @param shaderProgram defines the webGL program to use
  14125. * @param attributesNames defines the list of attribute names to get
  14126. * @returns an array of indices indicating the offset of each attribute
  14127. */
  14128. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14129. var results = [];
  14130. for (var index = 0; index < attributesNames.length; index++) {
  14131. try {
  14132. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14133. }
  14134. catch (e) {
  14135. results.push(-1);
  14136. }
  14137. }
  14138. return results;
  14139. };
  14140. /**
  14141. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14142. * @param effect defines the effect to activate
  14143. */
  14144. Engine.prototype.enableEffect = function (effect) {
  14145. if (!effect || effect === this._currentEffect) {
  14146. return;
  14147. }
  14148. // Use program
  14149. this.bindSamplers(effect);
  14150. this._currentEffect = effect;
  14151. if (effect.onBind) {
  14152. effect.onBind(effect);
  14153. }
  14154. if (effect._onBindObservable) {
  14155. effect._onBindObservable.notifyObservers(effect);
  14156. }
  14157. };
  14158. /**
  14159. * Set the value of an uniform to an array of int32
  14160. * @param uniform defines the webGL uniform location where to store the value
  14161. * @param array defines the array of int32 to store
  14162. */
  14163. Engine.prototype.setIntArray = function (uniform, array) {
  14164. if (!uniform)
  14165. return;
  14166. this._gl.uniform1iv(uniform, array);
  14167. };
  14168. /**
  14169. * Set the value of an uniform to an array of int32 (stored as vec2)
  14170. * @param uniform defines the webGL uniform location where to store the value
  14171. * @param array defines the array of int32 to store
  14172. */
  14173. Engine.prototype.setIntArray2 = function (uniform, array) {
  14174. if (!uniform || array.length % 2 !== 0)
  14175. return;
  14176. this._gl.uniform2iv(uniform, array);
  14177. };
  14178. /**
  14179. * Set the value of an uniform to an array of int32 (stored as vec3)
  14180. * @param uniform defines the webGL uniform location where to store the value
  14181. * @param array defines the array of int32 to store
  14182. */
  14183. Engine.prototype.setIntArray3 = function (uniform, array) {
  14184. if (!uniform || array.length % 3 !== 0)
  14185. return;
  14186. this._gl.uniform3iv(uniform, array);
  14187. };
  14188. /**
  14189. * Set the value of an uniform to an array of int32 (stored as vec4)
  14190. * @param uniform defines the webGL uniform location where to store the value
  14191. * @param array defines the array of int32 to store
  14192. */
  14193. Engine.prototype.setIntArray4 = function (uniform, array) {
  14194. if (!uniform || array.length % 4 !== 0)
  14195. return;
  14196. this._gl.uniform4iv(uniform, array);
  14197. };
  14198. /**
  14199. * Set the value of an uniform to an array of float32
  14200. * @param uniform defines the webGL uniform location where to store the value
  14201. * @param array defines the array of float32 to store
  14202. */
  14203. Engine.prototype.setFloatArray = function (uniform, array) {
  14204. if (!uniform)
  14205. return;
  14206. this._gl.uniform1fv(uniform, array);
  14207. };
  14208. /**
  14209. * Set the value of an uniform to an array of float32 (stored as vec2)
  14210. * @param uniform defines the webGL uniform location where to store the value
  14211. * @param array defines the array of float32 to store
  14212. */
  14213. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14214. if (!uniform || array.length % 2 !== 0)
  14215. return;
  14216. this._gl.uniform2fv(uniform, array);
  14217. };
  14218. /**
  14219. * Set the value of an uniform to an array of float32 (stored as vec3)
  14220. * @param uniform defines the webGL uniform location where to store the value
  14221. * @param array defines the array of float32 to store
  14222. */
  14223. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14224. if (!uniform || array.length % 3 !== 0)
  14225. return;
  14226. this._gl.uniform3fv(uniform, array);
  14227. };
  14228. /**
  14229. * Set the value of an uniform to an array of float32 (stored as vec4)
  14230. * @param uniform defines the webGL uniform location where to store the value
  14231. * @param array defines the array of float32 to store
  14232. */
  14233. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14234. if (!uniform || array.length % 4 !== 0)
  14235. return;
  14236. this._gl.uniform4fv(uniform, array);
  14237. };
  14238. /**
  14239. * Set the value of an uniform to an array of number
  14240. * @param uniform defines the webGL uniform location where to store the value
  14241. * @param array defines the array of number to store
  14242. */
  14243. Engine.prototype.setArray = function (uniform, array) {
  14244. if (!uniform)
  14245. return;
  14246. this._gl.uniform1fv(uniform, array);
  14247. };
  14248. /**
  14249. * Set the value of an uniform to an array of number (stored as vec2)
  14250. * @param uniform defines the webGL uniform location where to store the value
  14251. * @param array defines the array of number to store
  14252. */
  14253. Engine.prototype.setArray2 = function (uniform, array) {
  14254. if (!uniform || array.length % 2 !== 0)
  14255. return;
  14256. this._gl.uniform2fv(uniform, array);
  14257. };
  14258. /**
  14259. * Set the value of an uniform to an array of number (stored as vec3)
  14260. * @param uniform defines the webGL uniform location where to store the value
  14261. * @param array defines the array of number to store
  14262. */
  14263. Engine.prototype.setArray3 = function (uniform, array) {
  14264. if (!uniform || array.length % 3 !== 0)
  14265. return;
  14266. this._gl.uniform3fv(uniform, array);
  14267. };
  14268. /**
  14269. * Set the value of an uniform to an array of number (stored as vec4)
  14270. * @param uniform defines the webGL uniform location where to store the value
  14271. * @param array defines the array of number to store
  14272. */
  14273. Engine.prototype.setArray4 = function (uniform, array) {
  14274. if (!uniform || array.length % 4 !== 0)
  14275. return;
  14276. this._gl.uniform4fv(uniform, array);
  14277. };
  14278. /**
  14279. * Set the value of an uniform to an array of float32 (stored as matrices)
  14280. * @param uniform defines the webGL uniform location where to store the value
  14281. * @param matrices defines the array of float32 to store
  14282. */
  14283. Engine.prototype.setMatrices = function (uniform, matrices) {
  14284. if (!uniform)
  14285. return;
  14286. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14287. };
  14288. /**
  14289. * Set the value of an uniform to a matrix
  14290. * @param uniform defines the webGL uniform location where to store the value
  14291. * @param matrix defines the matrix to store
  14292. */
  14293. Engine.prototype.setMatrix = function (uniform, matrix) {
  14294. if (!uniform)
  14295. return;
  14296. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14297. };
  14298. /**
  14299. * Set the value of an uniform to a matrix (3x3)
  14300. * @param uniform defines the webGL uniform location where to store the value
  14301. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14302. */
  14303. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14304. if (!uniform)
  14305. return;
  14306. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14307. };
  14308. /**
  14309. * Set the value of an uniform to a matrix (2x2)
  14310. * @param uniform defines the webGL uniform location where to store the value
  14311. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14312. */
  14313. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14314. if (!uniform)
  14315. return;
  14316. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14317. };
  14318. /**
  14319. * Set the value of an uniform to a number (int)
  14320. * @param uniform defines the webGL uniform location where to store the value
  14321. * @param value defines the int number to store
  14322. */
  14323. Engine.prototype.setInt = function (uniform, value) {
  14324. if (!uniform)
  14325. return;
  14326. this._gl.uniform1i(uniform, value);
  14327. };
  14328. /**
  14329. * Set the value of an uniform to a number (float)
  14330. * @param uniform defines the webGL uniform location where to store the value
  14331. * @param value defines the float number to store
  14332. */
  14333. Engine.prototype.setFloat = function (uniform, value) {
  14334. if (!uniform)
  14335. return;
  14336. this._gl.uniform1f(uniform, value);
  14337. };
  14338. /**
  14339. * Set the value of an uniform to a vec2
  14340. * @param uniform defines the webGL uniform location where to store the value
  14341. * @param x defines the 1st component of the value
  14342. * @param y defines the 2nd component of the value
  14343. */
  14344. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14345. if (!uniform)
  14346. return;
  14347. this._gl.uniform2f(uniform, x, y);
  14348. };
  14349. /**
  14350. * Set the value of an uniform to a vec3
  14351. * @param uniform defines the webGL uniform location where to store the value
  14352. * @param x defines the 1st component of the value
  14353. * @param y defines the 2nd component of the value
  14354. * @param z defines the 3rd component of the value
  14355. */
  14356. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14357. if (!uniform)
  14358. return;
  14359. this._gl.uniform3f(uniform, x, y, z);
  14360. };
  14361. /**
  14362. * Set the value of an uniform to a boolean
  14363. * @param uniform defines the webGL uniform location where to store the value
  14364. * @param bool defines the boolean to store
  14365. */
  14366. Engine.prototype.setBool = function (uniform, bool) {
  14367. if (!uniform)
  14368. return;
  14369. this._gl.uniform1i(uniform, bool);
  14370. };
  14371. /**
  14372. * Set the value of an uniform to a vec4
  14373. * @param uniform defines the webGL uniform location where to store the value
  14374. * @param x defines the 1st component of the value
  14375. * @param y defines the 2nd component of the value
  14376. * @param z defines the 3rd component of the value
  14377. * @param w defines the 4th component of the value
  14378. */
  14379. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14380. if (!uniform)
  14381. return;
  14382. this._gl.uniform4f(uniform, x, y, z, w);
  14383. };
  14384. /**
  14385. * Set the value of an uniform to a Color3
  14386. * @param uniform defines the webGL uniform location where to store the value
  14387. * @param color3 defines the color to store
  14388. */
  14389. Engine.prototype.setColor3 = function (uniform, color3) {
  14390. if (!uniform)
  14391. return;
  14392. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14393. };
  14394. /**
  14395. * Set the value of an uniform to a Color3 and an alpha value
  14396. * @param uniform defines the webGL uniform location where to store the value
  14397. * @param color3 defines the color to store
  14398. * @param alpha defines the alpha component to store
  14399. */
  14400. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14401. if (!uniform)
  14402. return;
  14403. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14404. };
  14405. /**
  14406. * Sets a Color4 on a uniform variable
  14407. * @param uniform defines the uniform location
  14408. * @param color4 defines the value to be set
  14409. */
  14410. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14411. if (!uniform)
  14412. return;
  14413. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14414. };
  14415. // States
  14416. /**
  14417. * Set various states to the webGL context
  14418. * @param culling defines backface culling state
  14419. * @param zOffset defines the value to apply to zOffset (0 by default)
  14420. * @param force defines if states must be applied even if cache is up to date
  14421. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14422. */
  14423. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14424. if (zOffset === void 0) { zOffset = 0; }
  14425. if (reverseSide === void 0) { reverseSide = false; }
  14426. // Culling
  14427. if (this._depthCullingState.cull !== culling || force) {
  14428. this._depthCullingState.cull = culling;
  14429. }
  14430. // Cull face
  14431. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14432. if (this._depthCullingState.cullFace !== cullFace || force) {
  14433. this._depthCullingState.cullFace = cullFace;
  14434. }
  14435. // Z offset
  14436. this.setZOffset(zOffset);
  14437. // Front face
  14438. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14439. if (this._depthCullingState.frontFace !== frontFace || force) {
  14440. this._depthCullingState.frontFace = frontFace;
  14441. }
  14442. };
  14443. /**
  14444. * Set the z offset to apply to current rendering
  14445. * @param value defines the offset to apply
  14446. */
  14447. Engine.prototype.setZOffset = function (value) {
  14448. this._depthCullingState.zOffset = value;
  14449. };
  14450. /**
  14451. * Gets the current value of the zOffset
  14452. * @returns the current zOffset state
  14453. */
  14454. Engine.prototype.getZOffset = function () {
  14455. return this._depthCullingState.zOffset;
  14456. };
  14457. /**
  14458. * Enable or disable depth buffering
  14459. * @param enable defines the state to set
  14460. */
  14461. Engine.prototype.setDepthBuffer = function (enable) {
  14462. this._depthCullingState.depthTest = enable;
  14463. };
  14464. /**
  14465. * Gets a boolean indicating if depth writing is enabled
  14466. * @returns the current depth writing state
  14467. */
  14468. Engine.prototype.getDepthWrite = function () {
  14469. return this._depthCullingState.depthMask;
  14470. };
  14471. /**
  14472. * Enable or disable depth writing
  14473. * @param enable defines the state to set
  14474. */
  14475. Engine.prototype.setDepthWrite = function (enable) {
  14476. this._depthCullingState.depthMask = enable;
  14477. };
  14478. /**
  14479. * Enable or disable color writing
  14480. * @param enable defines the state to set
  14481. */
  14482. Engine.prototype.setColorWrite = function (enable) {
  14483. this._gl.colorMask(enable, enable, enable, enable);
  14484. this._colorWrite = enable;
  14485. };
  14486. /**
  14487. * Gets a boolean indicating if color writing is enabled
  14488. * @returns the current color writing state
  14489. */
  14490. Engine.prototype.getColorWrite = function () {
  14491. return this._colorWrite;
  14492. };
  14493. /**
  14494. * Sets alpha constants used by some alpha blending modes
  14495. * @param r defines the red component
  14496. * @param g defines the green component
  14497. * @param b defines the blue component
  14498. * @param a defines the alpha component
  14499. */
  14500. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14501. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14502. };
  14503. /**
  14504. * Sets the current alpha mode
  14505. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14506. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14507. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14508. */
  14509. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14510. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14511. if (this._alphaMode === mode) {
  14512. return;
  14513. }
  14514. switch (mode) {
  14515. case Engine.ALPHA_DISABLE:
  14516. this._alphaState.alphaBlend = false;
  14517. break;
  14518. case Engine.ALPHA_PREMULTIPLIED:
  14519. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14520. this._alphaState.alphaBlend = true;
  14521. break;
  14522. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14523. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14524. this._alphaState.alphaBlend = true;
  14525. break;
  14526. case Engine.ALPHA_COMBINE:
  14527. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14528. this._alphaState.alphaBlend = true;
  14529. break;
  14530. case Engine.ALPHA_ONEONE:
  14531. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14532. this._alphaState.alphaBlend = true;
  14533. break;
  14534. case Engine.ALPHA_ADD:
  14535. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14536. this._alphaState.alphaBlend = true;
  14537. break;
  14538. case Engine.ALPHA_SUBTRACT:
  14539. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14540. this._alphaState.alphaBlend = true;
  14541. break;
  14542. case Engine.ALPHA_MULTIPLY:
  14543. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14544. this._alphaState.alphaBlend = true;
  14545. break;
  14546. case Engine.ALPHA_MAXIMIZED:
  14547. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14548. this._alphaState.alphaBlend = true;
  14549. break;
  14550. case Engine.ALPHA_INTERPOLATE:
  14551. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14552. this._alphaState.alphaBlend = true;
  14553. break;
  14554. case Engine.ALPHA_SCREENMODE:
  14555. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14556. this._alphaState.alphaBlend = true;
  14557. break;
  14558. }
  14559. if (!noDepthWriteChange) {
  14560. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14561. }
  14562. this._alphaMode = mode;
  14563. };
  14564. /**
  14565. * Gets the current alpha mode
  14566. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14567. * @returns the current alpha mode
  14568. */
  14569. Engine.prototype.getAlphaMode = function () {
  14570. return this._alphaMode;
  14571. };
  14572. // Textures
  14573. /**
  14574. * Clears the list of texture accessible through engine.
  14575. * This can help preventing texture load conflict due to name collision.
  14576. */
  14577. Engine.prototype.clearInternalTexturesCache = function () {
  14578. this._internalTexturesCache = [];
  14579. };
  14580. /**
  14581. * Force the entire cache to be cleared
  14582. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14583. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14584. */
  14585. Engine.prototype.wipeCaches = function (bruteForce) {
  14586. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14587. return;
  14588. }
  14589. this._currentEffect = null;
  14590. this._viewportCached.x = 0;
  14591. this._viewportCached.y = 0;
  14592. this._viewportCached.z = 0;
  14593. this._viewportCached.w = 0;
  14594. if (bruteForce) {
  14595. this.resetTextureCache();
  14596. this._currentProgram = null;
  14597. this._stencilState.reset();
  14598. this._depthCullingState.reset();
  14599. this.setDepthFunctionToLessOrEqual();
  14600. this._alphaState.reset();
  14601. this._unpackFlipYCached = null;
  14602. }
  14603. this._resetVertexBufferBinding();
  14604. this._cachedIndexBuffer = null;
  14605. this._cachedEffectForVertexBuffers = null;
  14606. this._unbindVertexArrayObject();
  14607. this.bindIndexBuffer(null);
  14608. };
  14609. /**
  14610. * Set the compressed texture format to use, based on the formats you have, and the formats
  14611. * supported by the hardware / browser.
  14612. *
  14613. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14614. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14615. * to API arguments needed to compressed textures. This puts the burden on the container
  14616. * generator to house the arcane code for determining these for current & future formats.
  14617. *
  14618. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14619. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14620. *
  14621. * Note: The result of this call is not taken into account when a texture is base64.
  14622. *
  14623. * @param formatsAvailable defines the list of those format families you have created
  14624. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14625. *
  14626. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14627. * @returns The extension selected.
  14628. */
  14629. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14630. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14631. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14632. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14633. return this._textureFormatInUse = this._texturesSupported[i];
  14634. }
  14635. }
  14636. }
  14637. // actively set format to nothing, to allow this to be called more than once
  14638. // and possibly fail the 2nd time
  14639. this._textureFormatInUse = null;
  14640. return null;
  14641. };
  14642. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14643. var gl = this._gl;
  14644. var magFilter = gl.NEAREST;
  14645. var minFilter = gl.NEAREST;
  14646. switch (samplingMode) {
  14647. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14648. magFilter = gl.LINEAR;
  14649. if (generateMipMaps) {
  14650. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14651. }
  14652. else {
  14653. minFilter = gl.LINEAR;
  14654. }
  14655. break;
  14656. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14657. magFilter = gl.LINEAR;
  14658. if (generateMipMaps) {
  14659. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14660. }
  14661. else {
  14662. minFilter = gl.LINEAR;
  14663. }
  14664. break;
  14665. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14666. magFilter = gl.NEAREST;
  14667. if (generateMipMaps) {
  14668. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14669. }
  14670. else {
  14671. minFilter = gl.NEAREST;
  14672. }
  14673. break;
  14674. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14675. magFilter = gl.NEAREST;
  14676. if (generateMipMaps) {
  14677. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14678. }
  14679. else {
  14680. minFilter = gl.NEAREST;
  14681. }
  14682. break;
  14683. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14684. magFilter = gl.NEAREST;
  14685. if (generateMipMaps) {
  14686. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14687. }
  14688. else {
  14689. minFilter = gl.LINEAR;
  14690. }
  14691. break;
  14692. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14693. magFilter = gl.NEAREST;
  14694. if (generateMipMaps) {
  14695. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14696. }
  14697. else {
  14698. minFilter = gl.LINEAR;
  14699. }
  14700. break;
  14701. case Engine.TEXTURE_NEAREST_LINEAR:
  14702. magFilter = gl.NEAREST;
  14703. minFilter = gl.LINEAR;
  14704. break;
  14705. case Engine.TEXTURE_NEAREST_NEAREST:
  14706. magFilter = gl.NEAREST;
  14707. minFilter = gl.NEAREST;
  14708. break;
  14709. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14710. magFilter = gl.LINEAR;
  14711. if (generateMipMaps) {
  14712. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14713. }
  14714. else {
  14715. minFilter = gl.NEAREST;
  14716. }
  14717. break;
  14718. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14719. magFilter = gl.LINEAR;
  14720. if (generateMipMaps) {
  14721. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14722. }
  14723. else {
  14724. minFilter = gl.NEAREST;
  14725. }
  14726. break;
  14727. case Engine.TEXTURE_LINEAR_LINEAR:
  14728. magFilter = gl.LINEAR;
  14729. minFilter = gl.LINEAR;
  14730. break;
  14731. case Engine.TEXTURE_LINEAR_NEAREST:
  14732. magFilter = gl.LINEAR;
  14733. minFilter = gl.NEAREST;
  14734. break;
  14735. }
  14736. return {
  14737. min: minFilter,
  14738. mag: magFilter
  14739. };
  14740. };
  14741. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14742. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14743. var img;
  14744. var onload = function () {
  14745. loadedImages[index] = img;
  14746. loadedImages._internalCount++;
  14747. if (scene) {
  14748. scene._removePendingData(img);
  14749. }
  14750. if (loadedImages._internalCount === 6) {
  14751. onfinish(loadedImages);
  14752. }
  14753. };
  14754. var onerror = function (message, exception) {
  14755. if (scene) {
  14756. scene._removePendingData(img);
  14757. }
  14758. if (onErrorCallBack) {
  14759. onErrorCallBack(message, exception);
  14760. }
  14761. };
  14762. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14763. if (scene) {
  14764. scene._addPendingData(img);
  14765. }
  14766. };
  14767. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14768. if (onError === void 0) { onError = null; }
  14769. var loadedImages = [];
  14770. loadedImages._internalCount = 0;
  14771. for (var index = 0; index < 6; index++) {
  14772. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14773. }
  14774. };
  14775. ;
  14776. /** @hidden */
  14777. Engine.prototype._createTexture = function () {
  14778. var texture = this._gl.createTexture();
  14779. if (!texture) {
  14780. throw new Error("Unable to create texture");
  14781. }
  14782. return texture;
  14783. };
  14784. /**
  14785. * Usually called from BABYLON.Texture.ts.
  14786. * Passed information to create a WebGLTexture
  14787. * @param urlArg defines a value which contains one of the following:
  14788. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14789. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14790. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14791. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14792. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14793. * @param scene needed for loading to the correct scene
  14794. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14795. * @param onLoad optional callback to be called upon successful completion
  14796. * @param onError optional callback to be called upon failure
  14797. * @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
  14798. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14799. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14800. * @param forcedExtension defines the extension to use to pick the right loader
  14801. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14802. */
  14803. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14804. var _this = this;
  14805. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14806. if (onLoad === void 0) { onLoad = null; }
  14807. if (onError === void 0) { onError = null; }
  14808. if (buffer === void 0) { buffer = null; }
  14809. if (fallback === void 0) { fallback = null; }
  14810. if (format === void 0) { format = null; }
  14811. if (forcedExtension === void 0) { forcedExtension = null; }
  14812. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14813. var fromData = url.substr(0, 5) === "data:";
  14814. var fromBlob = url.substr(0, 5) === "blob:";
  14815. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  14816. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14817. // establish the file extension, if possible
  14818. var lastDot = url.lastIndexOf('.');
  14819. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14820. var loader = null;
  14821. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14822. var availableLoader = _a[_i];
  14823. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14824. loader = availableLoader;
  14825. break;
  14826. }
  14827. }
  14828. if (loader) {
  14829. url = loader.transformUrl(url, this._textureFormatInUse);
  14830. }
  14831. if (scene) {
  14832. scene._addPendingData(texture);
  14833. }
  14834. texture.url = url;
  14835. texture.generateMipMaps = !noMipmap;
  14836. texture.samplingMode = samplingMode;
  14837. texture.invertY = invertY;
  14838. if (!this._doNotHandleContextLost) {
  14839. // Keep a link to the buffer only if we plan to handle context lost
  14840. texture._buffer = buffer;
  14841. }
  14842. var onLoadObserver = null;
  14843. if (onLoad && !fallback) {
  14844. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14845. }
  14846. if (!fallback)
  14847. this._internalTexturesCache.push(texture);
  14848. var onInternalError = function (message, exception) {
  14849. if (scene) {
  14850. scene._removePendingData(texture);
  14851. }
  14852. var customFallback = false;
  14853. if (loader) {
  14854. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14855. if (fallbackUrl) {
  14856. // Add Back
  14857. customFallback = true;
  14858. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14859. }
  14860. }
  14861. if (!customFallback) {
  14862. if (onLoadObserver) {
  14863. texture.onLoadedObservable.remove(onLoadObserver);
  14864. }
  14865. if (BABYLON.Tools.UseFallbackTexture) {
  14866. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14867. }
  14868. }
  14869. if (onError) {
  14870. onError(message || "Unknown error", exception);
  14871. }
  14872. };
  14873. // processing for non-image formats
  14874. if (loader) {
  14875. var callback = function (data) {
  14876. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14877. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14878. done();
  14879. return false;
  14880. }, samplingMode);
  14881. });
  14882. };
  14883. if (!buffer) {
  14884. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14885. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14886. });
  14887. }
  14888. else {
  14889. callback(buffer);
  14890. }
  14891. }
  14892. else {
  14893. var onload = function (img) {
  14894. if (fromBlob && !_this._doNotHandleContextLost) {
  14895. // We need to store the image if we need to rebuild the texture
  14896. // in case of a webgl context lost
  14897. texture._buffer = img;
  14898. }
  14899. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14900. var gl = _this._gl;
  14901. var isPot = (img.width === potWidth && img.height === potHeight);
  14902. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14903. if (isPot) {
  14904. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14905. return false;
  14906. }
  14907. var maxTextureSize = _this._caps.maxTextureSize;
  14908. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14909. _this._prepareWorkingCanvas();
  14910. if (!_this._workingCanvas || !_this._workingContext) {
  14911. return false;
  14912. }
  14913. _this._workingCanvas.width = potWidth;
  14914. _this._workingCanvas.height = potHeight;
  14915. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14916. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14917. texture.width = potWidth;
  14918. texture.height = potHeight;
  14919. return false;
  14920. }
  14921. else {
  14922. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14923. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14924. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14925. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14926. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14927. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14928. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14929. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14930. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14931. _this._releaseTexture(source_1);
  14932. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14933. continuationCallback();
  14934. });
  14935. }
  14936. return true;
  14937. }, samplingMode);
  14938. };
  14939. if (!fromData || isBase64) {
  14940. if (buffer instanceof HTMLImageElement) {
  14941. onload(buffer);
  14942. }
  14943. else {
  14944. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14945. }
  14946. }
  14947. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14948. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14949. }
  14950. else {
  14951. onload(buffer);
  14952. }
  14953. }
  14954. return texture;
  14955. };
  14956. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14957. var _this = this;
  14958. var rtt = this.createRenderTargetTexture({
  14959. width: destination.width,
  14960. height: destination.height,
  14961. }, {
  14962. generateMipMaps: false,
  14963. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14964. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14965. generateDepthBuffer: false,
  14966. generateStencilBuffer: false
  14967. });
  14968. if (!this._rescalePostProcess) {
  14969. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14970. }
  14971. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14972. _this._rescalePostProcess.onApply = function (effect) {
  14973. effect._bindTexture("textureSampler", source);
  14974. };
  14975. var hostingScene = scene;
  14976. if (!hostingScene) {
  14977. hostingScene = _this.scenes[_this.scenes.length - 1];
  14978. }
  14979. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14980. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14981. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14982. _this.unBindFramebuffer(rtt);
  14983. _this._releaseTexture(rtt);
  14984. if (onComplete) {
  14985. onComplete();
  14986. }
  14987. });
  14988. };
  14989. /**
  14990. * Update a raw texture
  14991. * @param texture defines the texture to update
  14992. * @param data defines the data to store in the texture
  14993. * @param format defines the format of the data
  14994. * @param invertY defines if data must be stored with Y axis inverted
  14995. * @param compression defines the compression used (null by default)
  14996. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14997. */
  14998. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14999. if (compression === void 0) { compression = null; }
  15000. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15001. if (!texture) {
  15002. return;
  15003. }
  15004. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  15005. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  15006. // babylon's internalFormat but gl's texImage2D format
  15007. var internalFormat = this._getInternalFormat(format);
  15008. var textureType = this._getWebGLTextureType(type);
  15009. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15010. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15011. if (!this._doNotHandleContextLost) {
  15012. texture._bufferView = data;
  15013. texture.format = format;
  15014. texture.type = type;
  15015. texture.invertY = invertY;
  15016. texture._compression = compression;
  15017. }
  15018. if (texture.width % 4 !== 0) {
  15019. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15020. }
  15021. if (compression && data) {
  15022. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15023. }
  15024. else {
  15025. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15026. }
  15027. if (texture.generateMipMaps) {
  15028. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15029. }
  15030. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15031. // this.resetTextureCache();
  15032. texture.isReady = true;
  15033. };
  15034. /**
  15035. * Creates a raw texture
  15036. * @param data defines the data to store in the texture
  15037. * @param width defines the width of the texture
  15038. * @param height defines the height of the texture
  15039. * @param format defines the format of the data
  15040. * @param generateMipMaps defines if the engine should generate the mip levels
  15041. * @param invertY defines if data must be stored with Y axis inverted
  15042. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15043. * @param compression defines the compression used (null by default)
  15044. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15045. * @returns the raw texture inside an InternalTexture
  15046. */
  15047. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15048. if (compression === void 0) { compression = null; }
  15049. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15050. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15051. texture.baseWidth = width;
  15052. texture.baseHeight = height;
  15053. texture.width = width;
  15054. texture.height = height;
  15055. texture.format = format;
  15056. texture.generateMipMaps = generateMipMaps;
  15057. texture.samplingMode = samplingMode;
  15058. texture.invertY = invertY;
  15059. texture._compression = compression;
  15060. texture.type = type;
  15061. if (!this._doNotHandleContextLost) {
  15062. texture._bufferView = data;
  15063. }
  15064. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15065. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15066. // Filters
  15067. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15068. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15069. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15070. if (generateMipMaps) {
  15071. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15072. }
  15073. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15074. this._internalTexturesCache.push(texture);
  15075. return texture;
  15076. };
  15077. /** @hidden */
  15078. Engine.prototype._unpackFlipY = function (value) {
  15079. if (this._unpackFlipYCached !== value) {
  15080. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15081. if (this.enableUnpackFlipYCached) {
  15082. this._unpackFlipYCached = value;
  15083. }
  15084. }
  15085. };
  15086. /** @hidden */
  15087. Engine.prototype._getUnpackAlignement = function () {
  15088. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  15089. };
  15090. /**
  15091. * Creates a dynamic texture
  15092. * @param width defines the width of the texture
  15093. * @param height defines the height of the texture
  15094. * @param generateMipMaps defines if the engine should generate the mip levels
  15095. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15096. * @returns the dynamic texture inside an InternalTexture
  15097. */
  15098. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15099. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15100. texture.baseWidth = width;
  15101. texture.baseHeight = height;
  15102. if (generateMipMaps) {
  15103. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15104. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15105. }
  15106. // this.resetTextureCache();
  15107. texture.width = width;
  15108. texture.height = height;
  15109. texture.isReady = false;
  15110. texture.generateMipMaps = generateMipMaps;
  15111. texture.samplingMode = samplingMode;
  15112. this.updateTextureSamplingMode(samplingMode, texture);
  15113. this._internalTexturesCache.push(texture);
  15114. return texture;
  15115. };
  15116. /**
  15117. * Update the sampling mode of a given texture
  15118. * @param samplingMode defines the required sampling mode
  15119. * @param texture defines the texture to update
  15120. */
  15121. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15122. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  15123. if (texture.isCube) {
  15124. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15125. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15126. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15127. }
  15128. else if (texture.is3D) {
  15129. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15130. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15131. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15132. }
  15133. else {
  15134. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15135. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15136. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15137. }
  15138. texture.samplingMode = samplingMode;
  15139. };
  15140. /**
  15141. * Update the content of a dynamic texture
  15142. * @param texture defines the texture to update
  15143. * @param canvas defines the canvas containing the source
  15144. * @param invertY defines if data must be stored with Y axis inverted
  15145. * @param premulAlpha defines if alpha is stored as premultiplied
  15146. * @param format defines the format of the data
  15147. */
  15148. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15149. if (premulAlpha === void 0) { premulAlpha = false; }
  15150. if (!texture) {
  15151. return;
  15152. }
  15153. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15154. this._unpackFlipY(invertY);
  15155. if (premulAlpha) {
  15156. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15157. }
  15158. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15159. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15160. if (texture.generateMipMaps) {
  15161. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15162. }
  15163. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15164. if (premulAlpha) {
  15165. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15166. }
  15167. texture.isReady = true;
  15168. };
  15169. /**
  15170. * Update a video texture
  15171. * @param texture defines the texture to update
  15172. * @param video defines the video element to use
  15173. * @param invertY defines if data must be stored with Y axis inverted
  15174. */
  15175. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15176. if (!texture || texture._isDisabled) {
  15177. return;
  15178. }
  15179. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15180. this._unpackFlipY(!invertY); // Video are upside down by default
  15181. try {
  15182. // Testing video texture support
  15183. if (this._videoTextureSupported === undefined) {
  15184. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15185. if (this._gl.getError() !== 0) {
  15186. this._videoTextureSupported = false;
  15187. }
  15188. else {
  15189. this._videoTextureSupported = true;
  15190. }
  15191. }
  15192. // Copy video through the current working canvas if video texture is not supported
  15193. if (!this._videoTextureSupported) {
  15194. if (!texture._workingCanvas) {
  15195. texture._workingCanvas = document.createElement("canvas");
  15196. var context = texture._workingCanvas.getContext("2d");
  15197. if (!context) {
  15198. throw new Error("Unable to get 2d context");
  15199. }
  15200. texture._workingContext = context;
  15201. texture._workingCanvas.width = texture.width;
  15202. texture._workingCanvas.height = texture.height;
  15203. }
  15204. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15205. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15206. }
  15207. else {
  15208. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15209. }
  15210. if (texture.generateMipMaps) {
  15211. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15212. }
  15213. if (!wasPreviouslyBound) {
  15214. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15215. }
  15216. // this.resetTextureCache();
  15217. texture.isReady = true;
  15218. }
  15219. catch (ex) {
  15220. // Something unexpected
  15221. // Let's disable the texture
  15222. texture._isDisabled = true;
  15223. }
  15224. };
  15225. /**
  15226. * Updates a depth texture Comparison Mode and Function.
  15227. * If the comparison Function is equal to 0, the mode will be set to none.
  15228. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15229. * @param texture The texture to set the comparison function for
  15230. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15231. */
  15232. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15233. if (this.webGLVersion === 1) {
  15234. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15235. return;
  15236. }
  15237. var gl = this._gl;
  15238. if (texture.isCube) {
  15239. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15240. if (comparisonFunction === 0) {
  15241. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15242. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15243. }
  15244. else {
  15245. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15246. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15247. }
  15248. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15249. }
  15250. else {
  15251. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15252. if (comparisonFunction === 0) {
  15253. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15254. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15255. }
  15256. else {
  15257. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15258. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15259. }
  15260. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15261. }
  15262. texture._comparisonFunction = comparisonFunction;
  15263. };
  15264. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15265. var width = size.width || size;
  15266. var height = size.height || size;
  15267. internalTexture.baseWidth = width;
  15268. internalTexture.baseHeight = height;
  15269. internalTexture.width = width;
  15270. internalTexture.height = height;
  15271. internalTexture.isReady = true;
  15272. internalTexture.samples = 1;
  15273. internalTexture.generateMipMaps = false;
  15274. internalTexture._generateDepthBuffer = true;
  15275. internalTexture._generateStencilBuffer = generateStencil;
  15276. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15277. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15278. internalTexture._comparisonFunction = comparisonFunction;
  15279. var gl = this._gl;
  15280. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15281. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15282. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15283. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15284. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15285. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15286. if (comparisonFunction === 0) {
  15287. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15288. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15289. }
  15290. else {
  15291. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15292. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15293. }
  15294. };
  15295. /**
  15296. * Creates a depth stencil texture.
  15297. * This is only available in WebGL 2 or with the depth texture extension available.
  15298. * @param size The size of face edge in the texture.
  15299. * @param options The options defining the texture.
  15300. * @returns The texture
  15301. */
  15302. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15303. if (options.isCube) {
  15304. var width = size.width || size;
  15305. return this._createDepthStencilCubeTexture(width, options);
  15306. }
  15307. else {
  15308. return this._createDepthStencilTexture(size, options);
  15309. }
  15310. };
  15311. /**
  15312. * Creates a depth stencil texture.
  15313. * This is only available in WebGL 2 or with the depth texture extension available.
  15314. * @param size The size of face edge in the texture.
  15315. * @param options The options defining the texture.
  15316. * @returns The texture
  15317. */
  15318. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15319. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15320. if (!this._caps.depthTextureExtension) {
  15321. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15322. return internalTexture;
  15323. }
  15324. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15325. var gl = this._gl;
  15326. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15327. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15328. if (this.webGLVersion > 1) {
  15329. if (internalOptions.generateStencil) {
  15330. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15331. }
  15332. else {
  15333. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15334. }
  15335. }
  15336. else {
  15337. if (internalOptions.generateStencil) {
  15338. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15339. }
  15340. else {
  15341. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15342. }
  15343. }
  15344. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15345. return internalTexture;
  15346. };
  15347. /**
  15348. * Creates a depth stencil cube texture.
  15349. * This is only available in WebGL 2.
  15350. * @param size The size of face edge in the cube texture.
  15351. * @param options The options defining the cube texture.
  15352. * @returns The cube texture
  15353. */
  15354. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15355. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15356. internalTexture.isCube = true;
  15357. if (this.webGLVersion === 1) {
  15358. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15359. return internalTexture;
  15360. }
  15361. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15362. var gl = this._gl;
  15363. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15364. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15365. // Create the depth/stencil buffer
  15366. for (var face = 0; face < 6; face++) {
  15367. if (internalOptions.generateStencil) {
  15368. 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);
  15369. }
  15370. else {
  15371. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15372. }
  15373. }
  15374. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15375. return internalTexture;
  15376. };
  15377. /**
  15378. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15379. * @param renderTarget The render target to set the frame buffer for
  15380. */
  15381. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15382. // Create the framebuffer
  15383. var internalTexture = renderTarget.getInternalTexture();
  15384. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15385. return;
  15386. }
  15387. var gl = this._gl;
  15388. var depthStencilTexture = renderTarget.depthStencilTexture;
  15389. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15390. if (depthStencilTexture.isCube) {
  15391. if (depthStencilTexture._generateStencilBuffer) {
  15392. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15393. }
  15394. else {
  15395. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15396. }
  15397. }
  15398. else {
  15399. if (depthStencilTexture._generateStencilBuffer) {
  15400. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15401. }
  15402. else {
  15403. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15404. }
  15405. }
  15406. this.bindUnboundFramebuffer(null);
  15407. };
  15408. /**
  15409. * Creates a new render target texture
  15410. * @param size defines the size of the texture
  15411. * @param options defines the options used to create the texture
  15412. * @returns a new render target texture stored in an InternalTexture
  15413. */
  15414. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15415. var fullOptions = new RenderTargetCreationOptions();
  15416. if (options !== undefined && typeof options === "object") {
  15417. fullOptions.generateMipMaps = options.generateMipMaps;
  15418. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15419. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15420. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15421. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15422. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15423. }
  15424. else {
  15425. fullOptions.generateMipMaps = options;
  15426. fullOptions.generateDepthBuffer = true;
  15427. fullOptions.generateStencilBuffer = false;
  15428. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15429. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15430. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15431. }
  15432. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15433. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15434. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15435. }
  15436. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15437. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15438. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15439. }
  15440. var gl = this._gl;
  15441. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15442. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15443. var width = size.width || size;
  15444. var height = size.height || size;
  15445. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15446. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15447. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15448. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15449. }
  15450. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15451. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15452. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15453. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15454. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15455. // Create the framebuffer
  15456. var currentFrameBuffer = this._currentFramebuffer;
  15457. var framebuffer = gl.createFramebuffer();
  15458. this.bindUnboundFramebuffer(framebuffer);
  15459. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15460. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15461. if (fullOptions.generateMipMaps) {
  15462. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15463. }
  15464. // Unbind
  15465. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15466. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15467. this.bindUnboundFramebuffer(currentFrameBuffer);
  15468. texture._framebuffer = framebuffer;
  15469. texture.baseWidth = width;
  15470. texture.baseHeight = height;
  15471. texture.width = width;
  15472. texture.height = height;
  15473. texture.isReady = true;
  15474. texture.samples = 1;
  15475. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15476. texture.samplingMode = fullOptions.samplingMode;
  15477. texture.type = fullOptions.type;
  15478. texture.format = fullOptions.format;
  15479. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15480. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15481. // this.resetTextureCache();
  15482. this._internalTexturesCache.push(texture);
  15483. return texture;
  15484. };
  15485. /**
  15486. * Create a multi render target texture
  15487. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15488. * @param size defines the size of the texture
  15489. * @param options defines the creation options
  15490. * @returns the cube texture as an InternalTexture
  15491. */
  15492. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15493. var generateMipMaps = false;
  15494. var generateDepthBuffer = true;
  15495. var generateStencilBuffer = false;
  15496. var generateDepthTexture = false;
  15497. var textureCount = 1;
  15498. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15499. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15500. var types = new Array();
  15501. var samplingModes = new Array();
  15502. if (options !== undefined) {
  15503. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15504. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15505. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15506. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15507. textureCount = options.textureCount || 1;
  15508. if (options.types) {
  15509. types = options.types;
  15510. }
  15511. if (options.samplingModes) {
  15512. samplingModes = options.samplingModes;
  15513. }
  15514. }
  15515. var gl = this._gl;
  15516. // Create the framebuffer
  15517. var framebuffer = gl.createFramebuffer();
  15518. this.bindUnboundFramebuffer(framebuffer);
  15519. var width = size.width || size;
  15520. var height = size.height || size;
  15521. var textures = [];
  15522. var attachments = [];
  15523. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15524. for (var i = 0; i < textureCount; i++) {
  15525. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15526. var type = types[i] || defaultType;
  15527. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15528. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15529. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15530. }
  15531. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15532. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15533. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15534. }
  15535. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15536. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15537. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15538. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15539. }
  15540. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15541. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15542. textures.push(texture);
  15543. attachments.push(attachment);
  15544. gl.activeTexture(gl["TEXTURE" + i]);
  15545. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15546. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15547. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15548. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15549. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15550. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15551. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15552. if (generateMipMaps) {
  15553. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15554. }
  15555. // Unbind
  15556. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15557. texture._framebuffer = framebuffer;
  15558. texture._depthStencilBuffer = depthStencilBuffer;
  15559. texture.baseWidth = width;
  15560. texture.baseHeight = height;
  15561. texture.width = width;
  15562. texture.height = height;
  15563. texture.isReady = true;
  15564. texture.samples = 1;
  15565. texture.generateMipMaps = generateMipMaps;
  15566. texture.samplingMode = samplingMode;
  15567. texture.type = type;
  15568. texture._generateDepthBuffer = generateDepthBuffer;
  15569. texture._generateStencilBuffer = generateStencilBuffer;
  15570. texture._attachments = attachments;
  15571. this._internalTexturesCache.push(texture);
  15572. }
  15573. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15574. // Depth texture
  15575. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15576. gl.activeTexture(gl.TEXTURE0);
  15577. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15578. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15579. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15580. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15581. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15582. 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);
  15583. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15584. depthTexture._framebuffer = framebuffer;
  15585. depthTexture.baseWidth = width;
  15586. depthTexture.baseHeight = height;
  15587. depthTexture.width = width;
  15588. depthTexture.height = height;
  15589. depthTexture.isReady = true;
  15590. depthTexture.samples = 1;
  15591. depthTexture.generateMipMaps = generateMipMaps;
  15592. depthTexture.samplingMode = gl.NEAREST;
  15593. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15594. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15595. textures.push(depthTexture);
  15596. this._internalTexturesCache.push(depthTexture);
  15597. }
  15598. gl.drawBuffers(attachments);
  15599. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15600. this.bindUnboundFramebuffer(null);
  15601. this.resetTextureCache();
  15602. return textures;
  15603. };
  15604. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15605. if (samples === void 0) { samples = 1; }
  15606. var depthStencilBuffer = null;
  15607. var gl = this._gl;
  15608. // Create the depth/stencil buffer
  15609. if (generateStencilBuffer) {
  15610. depthStencilBuffer = gl.createRenderbuffer();
  15611. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15612. if (samples > 1) {
  15613. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15614. }
  15615. else {
  15616. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15617. }
  15618. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15619. }
  15620. else if (generateDepthBuffer) {
  15621. depthStencilBuffer = gl.createRenderbuffer();
  15622. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15623. if (samples > 1) {
  15624. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15625. }
  15626. else {
  15627. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15628. }
  15629. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15630. }
  15631. return depthStencilBuffer;
  15632. };
  15633. /**
  15634. * Updates the sample count of a render target texture
  15635. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15636. * @param texture defines the texture to update
  15637. * @param samples defines the sample count to set
  15638. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15639. */
  15640. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15641. if (this.webGLVersion < 2 || !texture) {
  15642. return 1;
  15643. }
  15644. if (texture.samples === samples) {
  15645. return samples;
  15646. }
  15647. var gl = this._gl;
  15648. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15649. // Dispose previous render buffers
  15650. if (texture._depthStencilBuffer) {
  15651. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15652. texture._depthStencilBuffer = null;
  15653. }
  15654. if (texture._MSAAFramebuffer) {
  15655. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15656. texture._MSAAFramebuffer = null;
  15657. }
  15658. if (texture._MSAARenderBuffer) {
  15659. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15660. texture._MSAARenderBuffer = null;
  15661. }
  15662. if (samples > 1) {
  15663. var framebuffer = gl.createFramebuffer();
  15664. if (!framebuffer) {
  15665. throw new Error("Unable to create multi sampled framebuffer");
  15666. }
  15667. texture._MSAAFramebuffer = framebuffer;
  15668. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15669. var colorRenderbuffer = gl.createRenderbuffer();
  15670. if (!colorRenderbuffer) {
  15671. throw new Error("Unable to create multi sampled framebuffer");
  15672. }
  15673. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15674. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15675. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15676. texture._MSAARenderBuffer = colorRenderbuffer;
  15677. }
  15678. else {
  15679. this.bindUnboundFramebuffer(texture._framebuffer);
  15680. }
  15681. texture.samples = samples;
  15682. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15683. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15684. this.bindUnboundFramebuffer(null);
  15685. return samples;
  15686. };
  15687. /**
  15688. * Update the sample count for a given multiple render target texture
  15689. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15690. * @param textures defines the textures to update
  15691. * @param samples defines the sample count to set
  15692. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15693. */
  15694. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15695. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15696. return 1;
  15697. }
  15698. if (textures[0].samples === samples) {
  15699. return samples;
  15700. }
  15701. var gl = this._gl;
  15702. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15703. // Dispose previous render buffers
  15704. if (textures[0]._depthStencilBuffer) {
  15705. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15706. textures[0]._depthStencilBuffer = null;
  15707. }
  15708. if (textures[0]._MSAAFramebuffer) {
  15709. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15710. textures[0]._MSAAFramebuffer = null;
  15711. }
  15712. for (var i = 0; i < textures.length; i++) {
  15713. if (textures[i]._MSAARenderBuffer) {
  15714. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15715. textures[i]._MSAARenderBuffer = null;
  15716. }
  15717. }
  15718. if (samples > 1) {
  15719. var framebuffer = gl.createFramebuffer();
  15720. if (!framebuffer) {
  15721. throw new Error("Unable to create multi sampled framebuffer");
  15722. }
  15723. this.bindUnboundFramebuffer(framebuffer);
  15724. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15725. var attachments = [];
  15726. for (var i = 0; i < textures.length; i++) {
  15727. var texture = textures[i];
  15728. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15729. var colorRenderbuffer = gl.createRenderbuffer();
  15730. if (!colorRenderbuffer) {
  15731. throw new Error("Unable to create multi sampled framebuffer");
  15732. }
  15733. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15734. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15735. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15736. texture._MSAAFramebuffer = framebuffer;
  15737. texture._MSAARenderBuffer = colorRenderbuffer;
  15738. texture.samples = samples;
  15739. texture._depthStencilBuffer = depthStencilBuffer;
  15740. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15741. attachments.push(attachment);
  15742. }
  15743. gl.drawBuffers(attachments);
  15744. }
  15745. else {
  15746. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15747. }
  15748. this.bindUnboundFramebuffer(null);
  15749. return samples;
  15750. };
  15751. /** @hidden */
  15752. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15753. if (faceIndex === void 0) { faceIndex = 0; }
  15754. if (lod === void 0) { lod = 0; }
  15755. var gl = this._gl;
  15756. var target = gl.TEXTURE_2D;
  15757. if (texture.isCube) {
  15758. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15759. }
  15760. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15761. };
  15762. /** @hidden */
  15763. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15764. if (faceIndex === void 0) { faceIndex = 0; }
  15765. if (lod === void 0) { lod = 0; }
  15766. var gl = this._gl;
  15767. var textureType = this._getWebGLTextureType(texture.type);
  15768. var format = this._getInternalFormat(texture.format);
  15769. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15770. this._unpackFlipY(texture.invertY);
  15771. var target = gl.TEXTURE_2D;
  15772. if (texture.isCube) {
  15773. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15774. }
  15775. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15776. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15777. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15778. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15779. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15780. };
  15781. /** @hidden */
  15782. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15783. if (faceIndex === void 0) { faceIndex = 0; }
  15784. if (lod === void 0) { lod = 0; }
  15785. var gl = this._gl;
  15786. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15787. this._bindTextureDirectly(bindTarget, texture, true);
  15788. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15789. this._bindTextureDirectly(bindTarget, null, true);
  15790. };
  15791. /** @hidden */
  15792. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15793. if (faceIndex === void 0) { faceIndex = 0; }
  15794. if (lod === void 0) { lod = 0; }
  15795. var gl = this._gl;
  15796. var textureType = this._getWebGLTextureType(texture.type);
  15797. var format = this._getInternalFormat(texture.format);
  15798. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15799. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15800. this._bindTextureDirectly(bindTarget, texture, true);
  15801. this._unpackFlipY(texture.invertY);
  15802. var target = gl.TEXTURE_2D;
  15803. if (texture.isCube) {
  15804. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15805. }
  15806. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15807. this._bindTextureDirectly(bindTarget, null, true);
  15808. };
  15809. /**
  15810. * Creates a new render target cube texture
  15811. * @param size defines the size of the texture
  15812. * @param options defines the options used to create the texture
  15813. * @returns a new render target cube texture stored in an InternalTexture
  15814. */
  15815. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15816. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15817. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15818. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15819. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15820. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15821. }
  15822. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15823. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15824. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15825. }
  15826. var gl = this._gl;
  15827. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15828. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15829. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15830. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15831. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15832. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15833. }
  15834. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15835. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15836. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15837. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15838. for (var face = 0; face < 6; face++) {
  15839. 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);
  15840. }
  15841. // Create the framebuffer
  15842. var framebuffer = gl.createFramebuffer();
  15843. this.bindUnboundFramebuffer(framebuffer);
  15844. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15845. // MipMaps
  15846. if (fullOptions.generateMipMaps) {
  15847. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15848. }
  15849. // Unbind
  15850. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15851. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15852. this.bindUnboundFramebuffer(null);
  15853. texture._framebuffer = framebuffer;
  15854. texture.width = size;
  15855. texture.height = size;
  15856. texture.isReady = true;
  15857. texture.isCube = true;
  15858. texture.samples = 1;
  15859. texture.generateMipMaps = fullOptions.generateMipMaps;
  15860. texture.samplingMode = fullOptions.samplingMode;
  15861. texture.type = fullOptions.type;
  15862. texture.format = fullOptions.format;
  15863. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15864. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15865. this._internalTexturesCache.push(texture);
  15866. return texture;
  15867. };
  15868. /**
  15869. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15870. * @param rootUrl defines the url where the file to load is located
  15871. * @param scene defines the current scene
  15872. * @param lodScale defines scale to apply to the mip map selection
  15873. * @param lodOffset defines offset to apply to the mip map selection
  15874. * @param onLoad defines an optional callback raised when the texture is loaded
  15875. * @param onError defines an optional callback raised if there is an issue to load the texture
  15876. * @param format defines the format of the data
  15877. * @param forcedExtension defines the extension to use to pick the right loader
  15878. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15879. * @returns the cube texture as an InternalTexture
  15880. */
  15881. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15882. var _this = this;
  15883. if (onLoad === void 0) { onLoad = null; }
  15884. if (onError === void 0) { onError = null; }
  15885. if (forcedExtension === void 0) { forcedExtension = null; }
  15886. if (createPolynomials === void 0) { createPolynomials = true; }
  15887. var callback = function (loadData) {
  15888. if (!loadData) {
  15889. if (onLoad) {
  15890. onLoad(null);
  15891. }
  15892. return;
  15893. }
  15894. var texture = loadData.texture;
  15895. if (!createPolynomials) {
  15896. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15897. }
  15898. else if (loadData.info.sphericalPolynomial) {
  15899. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15900. }
  15901. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15902. if (_this._caps.textureLOD) {
  15903. // Do not add extra process if texture lod is supported.
  15904. if (onLoad) {
  15905. onLoad(texture);
  15906. }
  15907. return;
  15908. }
  15909. var mipSlices = 3;
  15910. var gl = _this._gl;
  15911. var width = loadData.width;
  15912. if (!width) {
  15913. return;
  15914. }
  15915. var textures = [];
  15916. for (var i = 0; i < mipSlices; i++) {
  15917. //compute LOD from even spacing in smoothness (matching shader calculation)
  15918. var smoothness = i / (mipSlices - 1);
  15919. var roughness = 1 - smoothness;
  15920. var minLODIndex = lodOffset; // roughness = 0
  15921. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15922. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15923. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15924. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15925. glTextureFromLod.type = texture.type;
  15926. glTextureFromLod.format = texture.format;
  15927. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15928. glTextureFromLod.height = glTextureFromLod.width;
  15929. glTextureFromLod.isCube = true;
  15930. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15931. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15932. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15933. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15934. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15935. if (loadData.isDDS) {
  15936. var info = loadData.info;
  15937. var data = loadData.data;
  15938. _this._unpackFlipY(info.isCompressed);
  15939. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15940. }
  15941. else {
  15942. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15943. }
  15944. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15945. // Wrap in a base texture for easy binding.
  15946. var lodTexture = new BABYLON.BaseTexture(scene);
  15947. lodTexture.isCube = true;
  15948. lodTexture._texture = glTextureFromLod;
  15949. glTextureFromLod.isReady = true;
  15950. textures.push(lodTexture);
  15951. }
  15952. texture._lodTextureHigh = textures[2];
  15953. texture._lodTextureMid = textures[1];
  15954. texture._lodTextureLow = textures[0];
  15955. if (onLoad) {
  15956. onLoad(texture);
  15957. }
  15958. };
  15959. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15960. };
  15961. /**
  15962. * Creates a cube texture
  15963. * @param rootUrl defines the url where the files to load is located
  15964. * @param scene defines the current scene
  15965. * @param files defines the list of files to load (1 per face)
  15966. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15967. * @param onLoad defines an optional callback raised when the texture is loaded
  15968. * @param onError defines an optional callback raised if there is an issue to load the texture
  15969. * @param format defines the format of the data
  15970. * @param forcedExtension defines the extension to use to pick the right loader
  15971. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15972. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15973. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15974. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15975. * @returns the cube texture as an InternalTexture
  15976. */
  15977. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15978. var _this = this;
  15979. if (onLoad === void 0) { onLoad = null; }
  15980. if (onError === void 0) { onError = null; }
  15981. if (forcedExtension === void 0) { forcedExtension = null; }
  15982. if (createPolynomials === void 0) { createPolynomials = false; }
  15983. if (lodScale === void 0) { lodScale = 0; }
  15984. if (lodOffset === void 0) { lodOffset = 0; }
  15985. if (fallback === void 0) { fallback = null; }
  15986. var gl = this._gl;
  15987. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15988. texture.isCube = true;
  15989. texture.url = rootUrl;
  15990. texture.generateMipMaps = !noMipmap;
  15991. texture._lodGenerationScale = lodScale;
  15992. texture._lodGenerationOffset = lodOffset;
  15993. if (!this._doNotHandleContextLost) {
  15994. texture._extension = forcedExtension;
  15995. texture._files = files;
  15996. }
  15997. var lastDot = rootUrl.lastIndexOf('.');
  15998. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15999. var loader = null;
  16000. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  16001. var availableLoader = _a[_i];
  16002. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  16003. loader = availableLoader;
  16004. break;
  16005. }
  16006. }
  16007. var onInternalError = function (request, exception) {
  16008. if (loader) {
  16009. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  16010. if (fallbackUrl) {
  16011. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  16012. }
  16013. }
  16014. if (onError && request) {
  16015. onError(request.status + " " + request.statusText, exception);
  16016. }
  16017. };
  16018. if (loader) {
  16019. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  16020. var onloaddata = function (data) {
  16021. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16022. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  16023. };
  16024. if (files && files.length === 6) {
  16025. if (loader.supportCascades) {
  16026. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  16027. }
  16028. else if (onError) {
  16029. onError("Textures type does not support cascades.");
  16030. }
  16031. }
  16032. else {
  16033. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  16034. }
  16035. }
  16036. else {
  16037. if (!files) {
  16038. throw new Error("Cannot load cubemap because files were not defined");
  16039. }
  16040. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16041. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16042. var height = width;
  16043. _this._prepareWorkingCanvas();
  16044. if (!_this._workingCanvas || !_this._workingContext) {
  16045. return;
  16046. }
  16047. _this._workingCanvas.width = width;
  16048. _this._workingCanvas.height = height;
  16049. var faces = [
  16050. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16051. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16052. ];
  16053. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16054. _this._unpackFlipY(false);
  16055. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16056. for (var index = 0; index < faces.length; index++) {
  16057. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16058. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16059. }
  16060. if (!noMipmap) {
  16061. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16062. }
  16063. _this._setCubeMapTextureParams(!noMipmap);
  16064. texture.width = width;
  16065. texture.height = height;
  16066. texture.isReady = true;
  16067. if (format) {
  16068. texture.format = format;
  16069. }
  16070. texture.onLoadedObservable.notifyObservers(texture);
  16071. texture.onLoadedObservable.clear();
  16072. if (onLoad) {
  16073. onLoad();
  16074. }
  16075. }, files, onError);
  16076. }
  16077. this._internalTexturesCache.push(texture);
  16078. return texture;
  16079. };
  16080. /**
  16081. * @hidden
  16082. */
  16083. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  16084. var gl = this._gl;
  16085. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16086. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16087. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16088. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16089. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16090. // this.resetTextureCache();
  16091. };
  16092. /**
  16093. * Update a raw cube texture
  16094. * @param texture defines the texture to udpdate
  16095. * @param data defines the data to store
  16096. * @param format defines the data format
  16097. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16098. * @param invertY defines if data must be stored with Y axis inverted
  16099. * @param compression defines the compression used (null by default)
  16100. * @param level defines which level of the texture to update
  16101. */
  16102. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16103. if (compression === void 0) { compression = null; }
  16104. if (level === void 0) { level = 0; }
  16105. texture._bufferViewArray = data;
  16106. texture.format = format;
  16107. texture.type = type;
  16108. texture.invertY = invertY;
  16109. texture._compression = compression;
  16110. var gl = this._gl;
  16111. var textureType = this._getWebGLTextureType(type);
  16112. var internalFormat = this._getInternalFormat(format);
  16113. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16114. var needConversion = false;
  16115. if (internalFormat === gl.RGB) {
  16116. internalFormat = gl.RGBA;
  16117. needConversion = true;
  16118. }
  16119. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16120. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16121. if (texture.width % 4 !== 0) {
  16122. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16123. }
  16124. // Data are known to be in +X +Y +Z -X -Y -Z
  16125. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16126. var faceData = data[faceIndex];
  16127. if (compression) {
  16128. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16129. }
  16130. else {
  16131. if (needConversion) {
  16132. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16133. }
  16134. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16135. }
  16136. }
  16137. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16138. if (isPot && texture.generateMipMaps && level === 0) {
  16139. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16140. }
  16141. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16142. // this.resetTextureCache();
  16143. texture.isReady = true;
  16144. };
  16145. /**
  16146. * Creates a new raw cube texture
  16147. * @param data defines the array of data to use to create each face
  16148. * @param size defines the size of the textures
  16149. * @param format defines the format of the data
  16150. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16151. * @param generateMipMaps defines if the engine should generate the mip levels
  16152. * @param invertY defines if data must be stored with Y axis inverted
  16153. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16154. * @param compression defines the compression used (null by default)
  16155. * @returns the cube texture as an InternalTexture
  16156. */
  16157. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16158. if (compression === void 0) { compression = null; }
  16159. var gl = this._gl;
  16160. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16161. texture.isCube = true;
  16162. texture.format = format;
  16163. texture.type = type;
  16164. if (!this._doNotHandleContextLost) {
  16165. texture._bufferViewArray = data;
  16166. }
  16167. var textureType = this._getWebGLTextureType(type);
  16168. var internalFormat = this._getInternalFormat(format);
  16169. if (internalFormat === gl.RGB) {
  16170. internalFormat = gl.RGBA;
  16171. }
  16172. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16173. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16174. generateMipMaps = false;
  16175. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16176. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16177. }
  16178. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16179. generateMipMaps = false;
  16180. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16181. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16182. }
  16183. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16184. generateMipMaps = false;
  16185. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16186. }
  16187. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16188. generateMipMaps = false;
  16189. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16190. }
  16191. var width = size;
  16192. var height = width;
  16193. texture.width = width;
  16194. texture.height = height;
  16195. // Double check on POT to generate Mips.
  16196. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16197. if (!isPot) {
  16198. generateMipMaps = false;
  16199. }
  16200. // Upload data if needed. The texture won't be ready until then.
  16201. if (data) {
  16202. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16203. }
  16204. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16205. // Filters
  16206. if (data && generateMipMaps) {
  16207. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16208. }
  16209. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16210. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16211. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16212. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16213. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16214. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16215. texture.generateMipMaps = generateMipMaps;
  16216. return texture;
  16217. };
  16218. /**
  16219. * Creates a new raw cube texture from a specified url
  16220. * @param url defines the url where the data is located
  16221. * @param scene defines the current scene
  16222. * @param size defines the size of the textures
  16223. * @param format defines the format of the data
  16224. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16225. * @param noMipmap defines if the engine should avoid generating the mip levels
  16226. * @param callback defines a callback used to extract texture data from loaded data
  16227. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16228. * @param onLoad defines a callback called when texture is loaded
  16229. * @param onError defines a callback called if there is an error
  16230. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16231. * @param invertY defines if data must be stored with Y axis inverted
  16232. * @returns the cube texture as an InternalTexture
  16233. */
  16234. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16235. var _this = this;
  16236. if (onLoad === void 0) { onLoad = null; }
  16237. if (onError === void 0) { onError = null; }
  16238. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16239. if (invertY === void 0) { invertY = false; }
  16240. var gl = this._gl;
  16241. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16242. scene._addPendingData(texture);
  16243. texture.url = url;
  16244. this._internalTexturesCache.push(texture);
  16245. var onerror = function (request, exception) {
  16246. scene._removePendingData(texture);
  16247. if (onError && request) {
  16248. onError(request.status + " " + request.statusText, exception);
  16249. }
  16250. };
  16251. var internalCallback = function (data) {
  16252. var width = texture.width;
  16253. var faceDataArrays = callback(data);
  16254. if (!faceDataArrays) {
  16255. return;
  16256. }
  16257. if (mipmapGenerator) {
  16258. var textureType = _this._getWebGLTextureType(type);
  16259. var internalFormat = _this._getInternalFormat(format);
  16260. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16261. var needConversion = false;
  16262. if (internalFormat === gl.RGB) {
  16263. internalFormat = gl.RGBA;
  16264. needConversion = true;
  16265. }
  16266. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16267. _this._unpackFlipY(false);
  16268. var mipData = mipmapGenerator(faceDataArrays);
  16269. for (var level = 0; level < mipData.length; level++) {
  16270. var mipSize = width >> level;
  16271. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16272. var mipFaceData = mipData[level][faceIndex];
  16273. if (needConversion) {
  16274. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16275. }
  16276. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16277. }
  16278. }
  16279. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16280. }
  16281. else {
  16282. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16283. }
  16284. texture.isReady = true;
  16285. // this.resetTextureCache();
  16286. scene._removePendingData(texture);
  16287. if (onLoad) {
  16288. onLoad();
  16289. }
  16290. };
  16291. this._loadFile(url, function (data) {
  16292. internalCallback(data);
  16293. }, undefined, scene.database, true, onerror);
  16294. return texture;
  16295. };
  16296. ;
  16297. /**
  16298. * Update a raw 3D texture
  16299. * @param texture defines the texture to update
  16300. * @param data defines the data to store
  16301. * @param format defines the data format
  16302. * @param invertY defines if data must be stored with Y axis inverted
  16303. * @param compression defines the used compression (can be null)
  16304. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16305. */
  16306. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16307. if (compression === void 0) { compression = null; }
  16308. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16309. var internalType = this._getWebGLTextureType(textureType);
  16310. var internalFormat = this._getInternalFormat(format);
  16311. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16312. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16313. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16314. if (!this._doNotHandleContextLost) {
  16315. texture._bufferView = data;
  16316. texture.format = format;
  16317. texture.invertY = invertY;
  16318. texture._compression = compression;
  16319. }
  16320. if (texture.width % 4 !== 0) {
  16321. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16322. }
  16323. if (compression && data) {
  16324. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16325. }
  16326. else {
  16327. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16328. }
  16329. if (texture.generateMipMaps) {
  16330. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16331. }
  16332. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16333. // this.resetTextureCache();
  16334. texture.isReady = true;
  16335. };
  16336. /**
  16337. * Creates a new raw 3D texture
  16338. * @param data defines the data used to create the texture
  16339. * @param width defines the width of the texture
  16340. * @param height defines the height of the texture
  16341. * @param depth defines the depth of the texture
  16342. * @param format defines the format of the texture
  16343. * @param generateMipMaps defines if the engine must generate mip levels
  16344. * @param invertY defines if data must be stored with Y axis inverted
  16345. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16346. * @param compression defines the compressed used (can be null)
  16347. * @param textureType defines the compressed used (can be null)
  16348. * @returns a new raw 3D texture (stored in an InternalTexture)
  16349. */
  16350. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16351. if (compression === void 0) { compression = null; }
  16352. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16353. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16354. texture.baseWidth = width;
  16355. texture.baseHeight = height;
  16356. texture.baseDepth = depth;
  16357. texture.width = width;
  16358. texture.height = height;
  16359. texture.depth = depth;
  16360. texture.format = format;
  16361. texture.type = textureType;
  16362. texture.generateMipMaps = generateMipMaps;
  16363. texture.samplingMode = samplingMode;
  16364. texture.is3D = true;
  16365. if (!this._doNotHandleContextLost) {
  16366. texture._bufferView = data;
  16367. }
  16368. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16369. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16370. // Filters
  16371. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16372. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16373. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16374. if (generateMipMaps) {
  16375. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16376. }
  16377. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16378. this._internalTexturesCache.push(texture);
  16379. return texture;
  16380. };
  16381. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16382. var gl = this._gl;
  16383. if (!gl) {
  16384. return;
  16385. }
  16386. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16387. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16388. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16389. if (!noMipmap && !isCompressed) {
  16390. gl.generateMipmap(gl.TEXTURE_2D);
  16391. }
  16392. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16393. // this.resetTextureCache();
  16394. if (scene) {
  16395. scene._removePendingData(texture);
  16396. }
  16397. texture.onLoadedObservable.notifyObservers(texture);
  16398. texture.onLoadedObservable.clear();
  16399. };
  16400. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16401. var _this = this;
  16402. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16403. var maxTextureSize = this.getCaps().maxTextureSize;
  16404. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16405. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16406. var gl = this._gl;
  16407. if (!gl) {
  16408. return;
  16409. }
  16410. if (!texture._webGLTexture) {
  16411. // this.resetTextureCache();
  16412. if (scene) {
  16413. scene._removePendingData(texture);
  16414. }
  16415. return;
  16416. }
  16417. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16418. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16419. texture.baseWidth = width;
  16420. texture.baseHeight = height;
  16421. texture.width = potWidth;
  16422. texture.height = potHeight;
  16423. texture.isReady = true;
  16424. if (processFunction(potWidth, potHeight, function () {
  16425. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16426. })) {
  16427. // Returning as texture needs extra async steps
  16428. return;
  16429. }
  16430. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16431. };
  16432. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16433. // Create new RGBA data container.
  16434. var rgbaData;
  16435. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16436. rgbaData = new Float32Array(width * height * 4);
  16437. }
  16438. else {
  16439. rgbaData = new Uint32Array(width * height * 4);
  16440. }
  16441. // Convert each pixel.
  16442. for (var x = 0; x < width; x++) {
  16443. for (var y = 0; y < height; y++) {
  16444. var index = (y * width + x) * 3;
  16445. var newIndex = (y * width + x) * 4;
  16446. // Map Old Value to new value.
  16447. rgbaData[newIndex + 0] = rgbData[index + 0];
  16448. rgbaData[newIndex + 1] = rgbData[index + 1];
  16449. rgbaData[newIndex + 2] = rgbData[index + 2];
  16450. // Add fully opaque alpha channel.
  16451. rgbaData[newIndex + 3] = 1;
  16452. }
  16453. }
  16454. return rgbaData;
  16455. };
  16456. /** @hidden */
  16457. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16458. var gl = this._gl;
  16459. if (texture._framebuffer) {
  16460. gl.deleteFramebuffer(texture._framebuffer);
  16461. texture._framebuffer = null;
  16462. }
  16463. if (texture._depthStencilBuffer) {
  16464. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16465. texture._depthStencilBuffer = null;
  16466. }
  16467. if (texture._MSAAFramebuffer) {
  16468. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16469. texture._MSAAFramebuffer = null;
  16470. }
  16471. if (texture._MSAARenderBuffer) {
  16472. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16473. texture._MSAARenderBuffer = null;
  16474. }
  16475. };
  16476. /** @hidden */
  16477. Engine.prototype._releaseTexture = function (texture) {
  16478. var gl = this._gl;
  16479. this._releaseFramebufferObjects(texture);
  16480. gl.deleteTexture(texture._webGLTexture);
  16481. // Unbind channels
  16482. this.unbindAllTextures();
  16483. var index = this._internalTexturesCache.indexOf(texture);
  16484. if (index !== -1) {
  16485. this._internalTexturesCache.splice(index, 1);
  16486. }
  16487. // Integrated fixed lod samplers.
  16488. if (texture._lodTextureHigh) {
  16489. texture._lodTextureHigh.dispose();
  16490. }
  16491. if (texture._lodTextureMid) {
  16492. texture._lodTextureMid.dispose();
  16493. }
  16494. if (texture._lodTextureLow) {
  16495. texture._lodTextureLow.dispose();
  16496. }
  16497. // Set output texture of post process to null if the texture has been released/disposed
  16498. this.scenes.forEach(function (scene) {
  16499. scene.postProcesses.forEach(function (postProcess) {
  16500. if (postProcess._outputTexture == texture) {
  16501. postProcess._outputTexture = null;
  16502. }
  16503. });
  16504. scene.cameras.forEach(function (camera) {
  16505. camera._postProcesses.forEach(function (postProcess) {
  16506. if (postProcess) {
  16507. if (postProcess._outputTexture == texture) {
  16508. postProcess._outputTexture = null;
  16509. }
  16510. }
  16511. });
  16512. });
  16513. });
  16514. };
  16515. Engine.prototype.setProgram = function (program) {
  16516. if (this._currentProgram !== program) {
  16517. this._gl.useProgram(program);
  16518. this._currentProgram = program;
  16519. }
  16520. };
  16521. /**
  16522. * Binds an effect to the webGL context
  16523. * @param effect defines the effect to bind
  16524. */
  16525. Engine.prototype.bindSamplers = function (effect) {
  16526. this.setProgram(effect.getProgram());
  16527. var samplers = effect.getSamplers();
  16528. for (var index = 0; index < samplers.length; index++) {
  16529. var uniform = effect.getUniform(samplers[index]);
  16530. if (uniform) {
  16531. this._boundUniforms[index] = uniform;
  16532. }
  16533. }
  16534. this._currentEffect = null;
  16535. };
  16536. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16537. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16538. return;
  16539. }
  16540. // Remove
  16541. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16542. // Bind last to it
  16543. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16544. // Bind to dummy
  16545. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16546. };
  16547. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16548. if (!internalTexture) {
  16549. return -1;
  16550. }
  16551. internalTexture._initialSlot = channel;
  16552. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16553. if (channel !== internalTexture._designatedSlot) {
  16554. this._textureCollisions.addCount(1, false);
  16555. }
  16556. }
  16557. else {
  16558. if (channel !== internalTexture._designatedSlot) {
  16559. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16560. return internalTexture._designatedSlot;
  16561. }
  16562. else {
  16563. // No slot for this texture, let's pick a new one (if we find a free slot)
  16564. if (this._nextFreeTextureSlots.length) {
  16565. return this._nextFreeTextureSlots[0];
  16566. }
  16567. // We need to recycle the oldest bound texture, sorry.
  16568. this._textureCollisions.addCount(1, false);
  16569. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16570. }
  16571. }
  16572. }
  16573. return channel;
  16574. };
  16575. Engine.prototype._linkTrackers = function (previous, next) {
  16576. previous.next = next;
  16577. next.previous = previous;
  16578. };
  16579. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16580. var currentSlot = internalTexture._designatedSlot;
  16581. if (currentSlot === -1) {
  16582. return -1;
  16583. }
  16584. internalTexture._designatedSlot = -1;
  16585. if (this.disableTextureBindingOptimization) {
  16586. return -1;
  16587. }
  16588. // Remove from bound list
  16589. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16590. // Free the slot
  16591. this._boundTexturesCache[currentSlot] = null;
  16592. this._nextFreeTextureSlots.push(currentSlot);
  16593. return currentSlot;
  16594. };
  16595. Engine.prototype._activateCurrentTexture = function () {
  16596. if (this._currentTextureChannel !== this._activeChannel) {
  16597. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16598. this._currentTextureChannel = this._activeChannel;
  16599. }
  16600. };
  16601. /** @hidden */
  16602. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16603. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16604. if (force === void 0) { force = false; }
  16605. var wasPreviouslyBound = false;
  16606. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16607. this._activeChannel = texture._designatedSlot;
  16608. }
  16609. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16610. var isTextureForRendering = texture && texture._initialSlot > -1;
  16611. if (currentTextureBound !== texture || force) {
  16612. if (currentTextureBound) {
  16613. this._removeDesignatedSlot(currentTextureBound);
  16614. }
  16615. this._activateCurrentTexture();
  16616. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16617. this._boundTexturesCache[this._activeChannel] = texture;
  16618. if (texture) {
  16619. if (!this.disableTextureBindingOptimization) {
  16620. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16621. if (slotIndex > -1) {
  16622. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16623. }
  16624. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16625. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16626. }
  16627. texture._designatedSlot = this._activeChannel;
  16628. }
  16629. }
  16630. else if (forTextureDataUpdate) {
  16631. wasPreviouslyBound = true;
  16632. this._activateCurrentTexture();
  16633. }
  16634. if (isTextureForRendering && !forTextureDataUpdate) {
  16635. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16636. }
  16637. return wasPreviouslyBound;
  16638. };
  16639. /** @hidden */
  16640. Engine.prototype._bindTexture = function (channel, texture) {
  16641. if (channel < 0) {
  16642. return;
  16643. }
  16644. if (texture) {
  16645. channel = this._getCorrectTextureChannel(channel, texture);
  16646. }
  16647. this._activeChannel = channel;
  16648. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16649. };
  16650. /**
  16651. * Sets a texture to the webGL context from a postprocess
  16652. * @param channel defines the channel to use
  16653. * @param postProcess defines the source postprocess
  16654. */
  16655. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16656. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16657. };
  16658. /**
  16659. * Binds the output of the passed in post process to the texture channel specified
  16660. * @param channel The channel the texture should be bound to
  16661. * @param postProcess The post process which's output should be bound
  16662. */
  16663. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16664. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16665. };
  16666. /**
  16667. * Unbind all textures from the webGL context
  16668. */
  16669. Engine.prototype.unbindAllTextures = function () {
  16670. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16671. this._activeChannel = channel;
  16672. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16673. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16674. if (this.webGLVersion > 1) {
  16675. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16676. }
  16677. }
  16678. };
  16679. /**
  16680. * Sets a texture to the according uniform.
  16681. * @param channel The texture channel
  16682. * @param uniform The uniform to set
  16683. * @param texture The texture to apply
  16684. */
  16685. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16686. if (channel < 0) {
  16687. return;
  16688. }
  16689. if (uniform) {
  16690. this._boundUniforms[channel] = uniform;
  16691. }
  16692. this._setTexture(channel, texture);
  16693. };
  16694. /**
  16695. * Sets a depth stencil texture from a render target to the according uniform.
  16696. * @param channel The texture channel
  16697. * @param uniform The uniform to set
  16698. * @param texture The render target texture containing the depth stencil texture to apply
  16699. */
  16700. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16701. if (channel < 0) {
  16702. return;
  16703. }
  16704. if (uniform) {
  16705. this._boundUniforms[channel] = uniform;
  16706. }
  16707. if (!texture || !texture.depthStencilTexture) {
  16708. this._setTexture(channel, null);
  16709. }
  16710. else {
  16711. this._setTexture(channel, texture, false, true);
  16712. }
  16713. };
  16714. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16715. var uniform = this._boundUniforms[sourceSlot];
  16716. if (uniform._currentState === destination) {
  16717. return;
  16718. }
  16719. this._gl.uniform1i(uniform, destination);
  16720. uniform._currentState = destination;
  16721. };
  16722. Engine.prototype._getTextureWrapMode = function (mode) {
  16723. switch (mode) {
  16724. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16725. return this._gl.REPEAT;
  16726. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16727. return this._gl.CLAMP_TO_EDGE;
  16728. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16729. return this._gl.MIRRORED_REPEAT;
  16730. }
  16731. return this._gl.REPEAT;
  16732. };
  16733. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16734. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16735. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16736. // Not ready?
  16737. if (!texture) {
  16738. if (this._boundTexturesCache[channel] != null) {
  16739. this._activeChannel = channel;
  16740. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16741. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16742. if (this.webGLVersion > 1) {
  16743. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16744. }
  16745. }
  16746. return false;
  16747. }
  16748. // Video
  16749. if (texture.video) {
  16750. this._activeChannel = channel;
  16751. texture.update();
  16752. }
  16753. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16754. texture.delayLoad();
  16755. return false;
  16756. }
  16757. var internalTexture;
  16758. if (depthStencilTexture) {
  16759. internalTexture = texture.depthStencilTexture;
  16760. }
  16761. else if (texture.isReady()) {
  16762. internalTexture = texture.getInternalTexture();
  16763. }
  16764. else if (texture.isCube) {
  16765. internalTexture = this.emptyCubeTexture;
  16766. }
  16767. else if (texture.is3D) {
  16768. internalTexture = this.emptyTexture3D;
  16769. }
  16770. else {
  16771. internalTexture = this.emptyTexture;
  16772. }
  16773. if (!isPartOfTextureArray) {
  16774. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16775. }
  16776. var needToBind = true;
  16777. if (this._boundTexturesCache[channel] === internalTexture) {
  16778. this._moveBoundTextureOnTop(internalTexture);
  16779. if (!isPartOfTextureArray) {
  16780. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16781. }
  16782. needToBind = false;
  16783. }
  16784. this._activeChannel = channel;
  16785. if (internalTexture && internalTexture.is3D) {
  16786. if (needToBind) {
  16787. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16788. }
  16789. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16790. internalTexture._cachedWrapU = texture.wrapU;
  16791. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16792. }
  16793. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16794. internalTexture._cachedWrapV = texture.wrapV;
  16795. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16796. }
  16797. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16798. internalTexture._cachedWrapR = texture.wrapR;
  16799. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16800. }
  16801. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16802. }
  16803. else if (internalTexture && internalTexture.isCube) {
  16804. if (needToBind) {
  16805. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16806. }
  16807. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16808. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16809. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16810. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16811. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16812. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16813. }
  16814. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16815. }
  16816. else {
  16817. if (needToBind) {
  16818. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16819. }
  16820. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16821. internalTexture._cachedWrapU = texture.wrapU;
  16822. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16823. }
  16824. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16825. internalTexture._cachedWrapV = texture.wrapV;
  16826. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16827. }
  16828. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16829. }
  16830. return true;
  16831. };
  16832. /**
  16833. * Sets an array of texture to the webGL context
  16834. * @param channel defines the channel where the texture array must be set
  16835. * @param uniform defines the associated uniform location
  16836. * @param textures defines the array of textures to bind
  16837. */
  16838. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16839. if (channel < 0 || !uniform) {
  16840. return;
  16841. }
  16842. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16843. this._textureUnits = new Int32Array(textures.length);
  16844. }
  16845. for (var i = 0; i < textures.length; i++) {
  16846. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16847. }
  16848. this._gl.uniform1iv(uniform, this._textureUnits);
  16849. for (var index = 0; index < textures.length; index++) {
  16850. this._setTexture(this._textureUnits[index], textures[index], true);
  16851. }
  16852. };
  16853. /** @hidden */
  16854. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16855. var internalTexture = texture.getInternalTexture();
  16856. if (!internalTexture) {
  16857. return;
  16858. }
  16859. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16860. var value = texture.anisotropicFilteringLevel;
  16861. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16862. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16863. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16864. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16865. }
  16866. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16867. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16868. internalTexture._cachedAnisotropicFilteringLevel = value;
  16869. }
  16870. };
  16871. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16872. this._bindTextureDirectly(target, texture, true, true);
  16873. this._gl.texParameterf(target, parameter, value);
  16874. };
  16875. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16876. if (texture) {
  16877. this._bindTextureDirectly(target, texture, true, true);
  16878. }
  16879. this._gl.texParameteri(target, parameter, value);
  16880. };
  16881. /**
  16882. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16883. * @param x defines the x coordinate of the rectangle where pixels must be read
  16884. * @param y defines the y coordinate of the rectangle where pixels must be read
  16885. * @param width defines the width of the rectangle where pixels must be read
  16886. * @param height defines the height of the rectangle where pixels must be read
  16887. * @returns a Uint8Array containing RGBA colors
  16888. */
  16889. Engine.prototype.readPixels = function (x, y, width, height) {
  16890. var data = new Uint8Array(height * width * 4);
  16891. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16892. return data;
  16893. };
  16894. /**
  16895. * Add an externaly attached data from its key.
  16896. * This method call will fail and return false, if such key already exists.
  16897. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16898. * @param key the unique key that identifies the data
  16899. * @param data the data object to associate to the key for this Engine instance
  16900. * @return true if no such key were already present and the data was added successfully, false otherwise
  16901. */
  16902. Engine.prototype.addExternalData = function (key, data) {
  16903. if (!this._externalData) {
  16904. this._externalData = new BABYLON.StringDictionary();
  16905. }
  16906. return this._externalData.add(key, data);
  16907. };
  16908. /**
  16909. * Get an externaly attached data from its key
  16910. * @param key the unique key that identifies the data
  16911. * @return the associated data, if present (can be null), or undefined if not present
  16912. */
  16913. Engine.prototype.getExternalData = function (key) {
  16914. if (!this._externalData) {
  16915. this._externalData = new BABYLON.StringDictionary();
  16916. }
  16917. return this._externalData.get(key);
  16918. };
  16919. /**
  16920. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16921. * @param key the unique key that identifies the data
  16922. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16923. * @return the associated data, can be null if the factory returned null.
  16924. */
  16925. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16926. if (!this._externalData) {
  16927. this._externalData = new BABYLON.StringDictionary();
  16928. }
  16929. return this._externalData.getOrAddWithFactory(key, factory);
  16930. };
  16931. /**
  16932. * Remove an externaly attached data from the Engine instance
  16933. * @param key the unique key that identifies the data
  16934. * @return true if the data was successfully removed, false if it doesn't exist
  16935. */
  16936. Engine.prototype.removeExternalData = function (key) {
  16937. if (!this._externalData) {
  16938. this._externalData = new BABYLON.StringDictionary();
  16939. }
  16940. return this._externalData.remove(key);
  16941. };
  16942. /**
  16943. * Unbind all vertex attributes from the webGL context
  16944. */
  16945. Engine.prototype.unbindAllAttributes = function () {
  16946. if (this._mustWipeVertexAttributes) {
  16947. this._mustWipeVertexAttributes = false;
  16948. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16949. this._gl.disableVertexAttribArray(i);
  16950. this._vertexAttribArraysEnabled[i] = false;
  16951. this._currentBufferPointers[i].active = false;
  16952. }
  16953. return;
  16954. }
  16955. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16956. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16957. continue;
  16958. }
  16959. this._gl.disableVertexAttribArray(i);
  16960. this._vertexAttribArraysEnabled[i] = false;
  16961. this._currentBufferPointers[i].active = false;
  16962. }
  16963. };
  16964. /**
  16965. * 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
  16966. */
  16967. Engine.prototype.releaseEffects = function () {
  16968. for (var name in this._compiledEffects) {
  16969. this._deleteProgram(this._compiledEffects[name]._program);
  16970. }
  16971. this._compiledEffects = {};
  16972. };
  16973. /**
  16974. * Dispose and release all associated resources
  16975. */
  16976. Engine.prototype.dispose = function () {
  16977. this.hideLoadingUI();
  16978. this.stopRenderLoop();
  16979. // Release postProcesses
  16980. while (this.postProcesses.length) {
  16981. this.postProcesses[0].dispose();
  16982. }
  16983. // Empty texture
  16984. if (this._emptyTexture) {
  16985. this._releaseTexture(this._emptyTexture);
  16986. this._emptyTexture = null;
  16987. }
  16988. if (this._emptyCubeTexture) {
  16989. this._releaseTexture(this._emptyCubeTexture);
  16990. this._emptyCubeTexture = null;
  16991. }
  16992. // Rescale PP
  16993. if (this._rescalePostProcess) {
  16994. this._rescalePostProcess.dispose();
  16995. }
  16996. // Release scenes
  16997. while (this.scenes.length) {
  16998. this.scenes[0].dispose();
  16999. }
  17000. // Release audio engine
  17001. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  17002. Engine.audioEngine.dispose();
  17003. }
  17004. // Release effects
  17005. this.releaseEffects();
  17006. // Unbind
  17007. this.unbindAllAttributes();
  17008. this._boundUniforms = [];
  17009. if (this._dummyFramebuffer) {
  17010. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17011. }
  17012. //WebVR
  17013. this.disableVR();
  17014. // Events
  17015. if (BABYLON.Tools.IsWindowObjectExist()) {
  17016. window.removeEventListener("blur", this._onBlur);
  17017. window.removeEventListener("focus", this._onFocus);
  17018. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17019. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17020. if (this._renderingCanvas) {
  17021. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17022. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17023. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17024. if (!this._doNotHandleContextLost) {
  17025. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17026. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17027. }
  17028. }
  17029. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17030. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17031. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17032. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17033. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17034. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17035. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17036. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17037. if (this._onVrDisplayConnect) {
  17038. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17039. if (this._onVrDisplayDisconnect) {
  17040. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17041. }
  17042. if (this._onVrDisplayPresentChange) {
  17043. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17044. }
  17045. this._onVrDisplayConnect = null;
  17046. this._onVrDisplayDisconnect = null;
  17047. }
  17048. }
  17049. // Remove from Instances
  17050. var index = Engine.Instances.indexOf(this);
  17051. if (index >= 0) {
  17052. Engine.Instances.splice(index, 1);
  17053. }
  17054. this._workingCanvas = null;
  17055. this._workingContext = null;
  17056. this._currentBufferPointers = [];
  17057. this._renderingCanvas = null;
  17058. this._currentProgram = null;
  17059. this._bindedRenderFunction = null;
  17060. this.onResizeObservable.clear();
  17061. this.onCanvasBlurObservable.clear();
  17062. this.onCanvasFocusObservable.clear();
  17063. this.onCanvasPointerOutObservable.clear();
  17064. this.onBeginFrameObservable.clear();
  17065. this.onEndFrameObservable.clear();
  17066. BABYLON.Effect.ResetCache();
  17067. // Abort active requests
  17068. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17069. var request = _a[_i];
  17070. request.abort();
  17071. }
  17072. };
  17073. // Loading screen
  17074. /**
  17075. * Display the loading screen
  17076. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17077. */
  17078. Engine.prototype.displayLoadingUI = function () {
  17079. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17080. return;
  17081. }
  17082. var loadingScreen = this.loadingScreen;
  17083. if (loadingScreen) {
  17084. loadingScreen.displayLoadingUI();
  17085. }
  17086. };
  17087. /**
  17088. * Hide the loading screen
  17089. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17090. */
  17091. Engine.prototype.hideLoadingUI = function () {
  17092. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17093. return;
  17094. }
  17095. var loadingScreen = this.loadingScreen;
  17096. if (loadingScreen) {
  17097. loadingScreen.hideLoadingUI();
  17098. }
  17099. };
  17100. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17101. /**
  17102. * Gets the current loading screen object
  17103. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17104. */
  17105. get: function () {
  17106. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  17107. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17108. return this._loadingScreen;
  17109. },
  17110. /**
  17111. * Sets the current loading screen object
  17112. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17113. */
  17114. set: function (loadingScreen) {
  17115. this._loadingScreen = loadingScreen;
  17116. },
  17117. enumerable: true,
  17118. configurable: true
  17119. });
  17120. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17121. /**
  17122. * Sets the current loading screen text
  17123. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17124. */
  17125. set: function (text) {
  17126. this.loadingScreen.loadingUIText = text;
  17127. },
  17128. enumerable: true,
  17129. configurable: true
  17130. });
  17131. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17132. /**
  17133. * Sets the current loading screen background color
  17134. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17135. */
  17136. set: function (color) {
  17137. this.loadingScreen.loadingUIBackgroundColor = color;
  17138. },
  17139. enumerable: true,
  17140. configurable: true
  17141. });
  17142. /**
  17143. * Attach a new callback raised when context lost event is fired
  17144. * @param callback defines the callback to call
  17145. */
  17146. Engine.prototype.attachContextLostEvent = function (callback) {
  17147. if (this._renderingCanvas) {
  17148. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17149. }
  17150. };
  17151. /**
  17152. * Attach a new callback raised when context restored event is fired
  17153. * @param callback defines the callback to call
  17154. */
  17155. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17156. if (this._renderingCanvas) {
  17157. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17158. }
  17159. };
  17160. /**
  17161. * Gets the source code of the vertex shader associated with a specific webGL program
  17162. * @param program defines the program to use
  17163. * @returns a string containing the source code of the vertex shader associated with the program
  17164. */
  17165. Engine.prototype.getVertexShaderSource = function (program) {
  17166. var shaders = this._gl.getAttachedShaders(program);
  17167. if (!shaders) {
  17168. return null;
  17169. }
  17170. return this._gl.getShaderSource(shaders[0]);
  17171. };
  17172. /**
  17173. * Gets the source code of the fragment shader associated with a specific webGL program
  17174. * @param program defines the program to use
  17175. * @returns a string containing the source code of the fragment shader associated with the program
  17176. */
  17177. Engine.prototype.getFragmentShaderSource = function (program) {
  17178. var shaders = this._gl.getAttachedShaders(program);
  17179. if (!shaders) {
  17180. return null;
  17181. }
  17182. return this._gl.getShaderSource(shaders[1]);
  17183. };
  17184. /**
  17185. * Get the current error code of the webGL context
  17186. * @returns the error code
  17187. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17188. */
  17189. Engine.prototype.getError = function () {
  17190. return this._gl.getError();
  17191. };
  17192. // FPS
  17193. /**
  17194. * Gets the current framerate
  17195. * @returns a number representing the framerate
  17196. */
  17197. Engine.prototype.getFps = function () {
  17198. return this._fps;
  17199. };
  17200. /**
  17201. * Gets the time spent between current and previous frame
  17202. * @returns a number representing the delta time in ms
  17203. */
  17204. Engine.prototype.getDeltaTime = function () {
  17205. return this._deltaTime;
  17206. };
  17207. Engine.prototype._measureFps = function () {
  17208. this._performanceMonitor.sampleFrame();
  17209. this._fps = this._performanceMonitor.averageFPS;
  17210. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17211. };
  17212. /** @hidden */
  17213. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17214. if (faceIndex === void 0) { faceIndex = -1; }
  17215. if (level === void 0) { level = 0; }
  17216. if (buffer === void 0) { buffer = null; }
  17217. var gl = this._gl;
  17218. if (!this._dummyFramebuffer) {
  17219. var dummy = gl.createFramebuffer();
  17220. if (!dummy) {
  17221. throw new Error("Unable to create dummy framebuffer");
  17222. }
  17223. this._dummyFramebuffer = dummy;
  17224. }
  17225. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17226. if (faceIndex > -1) {
  17227. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17228. }
  17229. else {
  17230. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17231. }
  17232. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17233. switch (readType) {
  17234. case gl.UNSIGNED_BYTE:
  17235. if (!buffer) {
  17236. buffer = new Uint8Array(4 * width * height);
  17237. }
  17238. readType = gl.UNSIGNED_BYTE;
  17239. break;
  17240. default:
  17241. if (!buffer) {
  17242. buffer = new Float32Array(4 * width * height);
  17243. }
  17244. readType = gl.FLOAT;
  17245. break;
  17246. }
  17247. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17248. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17249. return buffer;
  17250. };
  17251. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17252. if (this._webGLVersion > 1) {
  17253. return this._caps.colorBufferFloat;
  17254. }
  17255. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17256. };
  17257. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17258. if (this._webGLVersion > 1) {
  17259. return this._caps.colorBufferFloat;
  17260. }
  17261. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17262. };
  17263. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17264. Engine.prototype._canRenderToFramebuffer = function (type) {
  17265. var gl = this._gl;
  17266. //clear existing errors
  17267. while (gl.getError() !== gl.NO_ERROR) { }
  17268. var successful = true;
  17269. var texture = gl.createTexture();
  17270. gl.bindTexture(gl.TEXTURE_2D, texture);
  17271. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17272. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17273. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17274. var fb = gl.createFramebuffer();
  17275. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17276. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17277. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17278. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17279. successful = successful && (gl.getError() === gl.NO_ERROR);
  17280. //try render by clearing frame buffer's color buffer
  17281. if (successful) {
  17282. gl.clear(gl.COLOR_BUFFER_BIT);
  17283. successful = successful && (gl.getError() === gl.NO_ERROR);
  17284. }
  17285. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17286. if (successful) {
  17287. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17288. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17289. var readFormat = gl.RGBA;
  17290. var readType = gl.UNSIGNED_BYTE;
  17291. var buffer = new Uint8Array(4);
  17292. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17293. successful = successful && (gl.getError() === gl.NO_ERROR);
  17294. }
  17295. //clean up
  17296. gl.deleteTexture(texture);
  17297. gl.deleteFramebuffer(fb);
  17298. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17299. //clear accumulated errors
  17300. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17301. return successful;
  17302. };
  17303. /** @hidden */
  17304. Engine.prototype._getWebGLTextureType = function (type) {
  17305. if (this._webGLVersion === 1) {
  17306. switch (type) {
  17307. case Engine.TEXTURETYPE_FLOAT:
  17308. return this._gl.FLOAT;
  17309. case Engine.TEXTURETYPE_HALF_FLOAT:
  17310. return this._gl.HALF_FLOAT_OES;
  17311. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17312. return this._gl.UNSIGNED_BYTE;
  17313. }
  17314. return this._gl.UNSIGNED_BYTE;
  17315. }
  17316. switch (type) {
  17317. case Engine.TEXTURETYPE_BYTE:
  17318. return this._gl.BYTE;
  17319. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17320. return this._gl.UNSIGNED_BYTE;
  17321. case Engine.TEXTURETYPE_SHORT:
  17322. return this._gl.SHORT;
  17323. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17324. return this._gl.UNSIGNED_SHORT;
  17325. case Engine.TEXTURETYPE_INT:
  17326. return this._gl.INT;
  17327. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17328. return this._gl.UNSIGNED_INT;
  17329. case Engine.TEXTURETYPE_FLOAT:
  17330. return this._gl.FLOAT;
  17331. case Engine.TEXTURETYPE_HALF_FLOAT:
  17332. return this._gl.HALF_FLOAT;
  17333. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17334. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17335. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17336. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17337. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17338. return this._gl.UNSIGNED_SHORT_5_6_5;
  17339. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17340. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17341. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17342. return this._gl.UNSIGNED_INT_24_8;
  17343. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17344. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17345. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17346. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17347. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17348. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17349. }
  17350. return this._gl.UNSIGNED_BYTE;
  17351. };
  17352. ;
  17353. Engine.prototype._getInternalFormat = function (format) {
  17354. var internalFormat = this._gl.RGBA;
  17355. switch (format) {
  17356. case Engine.TEXTUREFORMAT_ALPHA:
  17357. internalFormat = this._gl.ALPHA;
  17358. break;
  17359. case Engine.TEXTUREFORMAT_LUMINANCE:
  17360. internalFormat = this._gl.LUMINANCE;
  17361. break;
  17362. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17363. internalFormat = this._gl.LUMINANCE_ALPHA;
  17364. break;
  17365. case Engine.TEXTUREFORMAT_RED:
  17366. internalFormat = this._gl.RED;
  17367. break;
  17368. case Engine.TEXTUREFORMAT_RG:
  17369. internalFormat = this._gl.RG;
  17370. break;
  17371. case Engine.TEXTUREFORMAT_RGB:
  17372. internalFormat = this._gl.RGB;
  17373. break;
  17374. case Engine.TEXTUREFORMAT_RGBA:
  17375. internalFormat = this._gl.RGBA;
  17376. break;
  17377. }
  17378. if (this._webGLVersion > 1) {
  17379. switch (format) {
  17380. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17381. internalFormat = this._gl.RED_INTEGER;
  17382. break;
  17383. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17384. internalFormat = this._gl.RG_INTEGER;
  17385. break;
  17386. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17387. internalFormat = this._gl.RGB_INTEGER;
  17388. break;
  17389. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17390. internalFormat = this._gl.RGBA_INTEGER;
  17391. break;
  17392. }
  17393. }
  17394. return internalFormat;
  17395. };
  17396. /** @hidden */
  17397. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17398. if (this._webGLVersion === 1) {
  17399. if (format !== undefined) {
  17400. switch (format) {
  17401. case Engine.TEXTUREFORMAT_ALPHA:
  17402. return this._gl.ALPHA;
  17403. case Engine.TEXTUREFORMAT_LUMINANCE:
  17404. return this._gl.LUMINANCE;
  17405. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17406. return this._gl.LUMINANCE_ALPHA;
  17407. }
  17408. }
  17409. return this._gl.RGBA;
  17410. }
  17411. switch (type) {
  17412. case Engine.TEXTURETYPE_BYTE:
  17413. switch (format) {
  17414. case Engine.TEXTUREFORMAT_RED:
  17415. return this._gl.R8_SNORM;
  17416. case Engine.TEXTUREFORMAT_RG:
  17417. return this._gl.RG8_SNORM;
  17418. case Engine.TEXTUREFORMAT_RGB:
  17419. return this._gl.RGB8_SNORM;
  17420. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17421. return this._gl.R8I;
  17422. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17423. return this._gl.RG8I;
  17424. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17425. return this._gl.RGB8I;
  17426. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17427. return this._gl.RGBA8I;
  17428. default:
  17429. return this._gl.RGBA8_SNORM;
  17430. }
  17431. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17432. switch (format) {
  17433. case Engine.TEXTUREFORMAT_RED:
  17434. return this._gl.R8;
  17435. case Engine.TEXTUREFORMAT_RG:
  17436. return this._gl.RG8;
  17437. case Engine.TEXTUREFORMAT_RGB:
  17438. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17439. case Engine.TEXTUREFORMAT_RGBA:
  17440. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17441. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17442. return this._gl.R8UI;
  17443. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17444. return this._gl.RG8UI;
  17445. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17446. return this._gl.RGB8UI;
  17447. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17448. return this._gl.RGBA8UI;
  17449. default:
  17450. return this._gl.RGBA8;
  17451. }
  17452. case Engine.TEXTURETYPE_SHORT:
  17453. switch (format) {
  17454. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17455. return this._gl.R16I;
  17456. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17457. return this._gl.RG16I;
  17458. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17459. return this._gl.RGB16I;
  17460. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17461. return this._gl.RGBA16I;
  17462. default:
  17463. return this._gl.RGBA16I;
  17464. }
  17465. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17466. switch (format) {
  17467. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17468. return this._gl.R16UI;
  17469. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17470. return this._gl.RG16UI;
  17471. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17472. return this._gl.RGB16UI;
  17473. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17474. return this._gl.RGBA16UI;
  17475. default:
  17476. return this._gl.RGBA16UI;
  17477. }
  17478. case Engine.TEXTURETYPE_INT:
  17479. switch (format) {
  17480. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17481. return this._gl.R32I;
  17482. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17483. return this._gl.RG32I;
  17484. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17485. return this._gl.RGB32I;
  17486. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17487. return this._gl.RGBA32I;
  17488. default:
  17489. return this._gl.RGBA32I;
  17490. }
  17491. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17492. switch (format) {
  17493. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17494. return this._gl.R32UI;
  17495. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17496. return this._gl.RG32UI;
  17497. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17498. return this._gl.RGB32UI;
  17499. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17500. return this._gl.RGBA32UI;
  17501. default:
  17502. return this._gl.RGBA32UI;
  17503. }
  17504. case Engine.TEXTURETYPE_FLOAT:
  17505. switch (format) {
  17506. case Engine.TEXTUREFORMAT_RED:
  17507. return this._gl.R32F; // By default. Other possibility is R16F.
  17508. case Engine.TEXTUREFORMAT_RG:
  17509. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17510. case Engine.TEXTUREFORMAT_RGB:
  17511. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17512. case Engine.TEXTUREFORMAT_RGBA:
  17513. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17514. default:
  17515. return this._gl.RGBA32F;
  17516. }
  17517. case Engine.TEXTURETYPE_HALF_FLOAT:
  17518. switch (format) {
  17519. case Engine.TEXTUREFORMAT_RED:
  17520. return this._gl.R16F;
  17521. case Engine.TEXTUREFORMAT_RG:
  17522. return this._gl.RG16F;
  17523. case Engine.TEXTUREFORMAT_RGB:
  17524. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17525. case Engine.TEXTUREFORMAT_RGBA:
  17526. return this._gl.RGBA16F;
  17527. default:
  17528. return this._gl.RGBA16F;
  17529. }
  17530. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17531. return this._gl.RGB565;
  17532. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17533. return this._gl.R11F_G11F_B10F;
  17534. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17535. return this._gl.RGB9_E5;
  17536. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17537. return this._gl.RGBA4;
  17538. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17539. return this._gl.RGB5_A1;
  17540. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17541. switch (format) {
  17542. case Engine.TEXTUREFORMAT_RGBA:
  17543. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17544. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17545. return this._gl.RGB10_A2UI;
  17546. default:
  17547. return this._gl.RGB10_A2;
  17548. }
  17549. }
  17550. return this._gl.RGBA8;
  17551. };
  17552. ;
  17553. /** @hidden */
  17554. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17555. if (type === Engine.TEXTURETYPE_FLOAT) {
  17556. return this._gl.RGBA32F;
  17557. }
  17558. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17559. return this._gl.RGBA16F;
  17560. }
  17561. return this._gl.RGBA8;
  17562. };
  17563. ;
  17564. /** @hidden */
  17565. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17566. var _this = this;
  17567. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17568. this._activeRequests.push(request);
  17569. request.onCompleteObservable.add(function (request) {
  17570. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17571. });
  17572. return request;
  17573. };
  17574. /** @hidden */
  17575. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17576. var _this = this;
  17577. return new Promise(function (resolve, reject) {
  17578. _this._loadFile(url, function (data) {
  17579. resolve(data);
  17580. }, undefined, database, useArrayBuffer, function (request, exception) {
  17581. reject(exception);
  17582. });
  17583. });
  17584. };
  17585. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17586. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17587. var onload = function (data) {
  17588. loadedFiles[index] = data;
  17589. loadedFiles._internalCount++;
  17590. if (loadedFiles._internalCount === 6) {
  17591. onfinish(loadedFiles);
  17592. }
  17593. };
  17594. var onerror = function (request, exception) {
  17595. if (onErrorCallBack && request) {
  17596. onErrorCallBack(request.status + " " + request.statusText, exception);
  17597. }
  17598. };
  17599. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17600. };
  17601. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17602. if (onError === void 0) { onError = null; }
  17603. var loadedFiles = [];
  17604. loadedFiles._internalCount = 0;
  17605. for (var index = 0; index < 6; index++) {
  17606. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17607. }
  17608. };
  17609. // Statics
  17610. /**
  17611. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17612. * @returns true if the engine can be created
  17613. * @ignorenaming
  17614. */
  17615. Engine.isSupported = function () {
  17616. try {
  17617. var tempcanvas = document.createElement("canvas");
  17618. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17619. return gl != null && !!window.WebGLRenderingContext;
  17620. }
  17621. catch (e) {
  17622. return false;
  17623. }
  17624. };
  17625. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17626. Engine.ExceptionList = [
  17627. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17628. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17629. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17630. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17631. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17632. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17633. ];
  17634. /** Gets the list of created engines */
  17635. Engine.Instances = new Array();
  17636. /**
  17637. * Hidden
  17638. */
  17639. Engine._TextureLoaders = [];
  17640. // Const statics
  17641. /** Defines that alpha blending is disabled */
  17642. Engine.ALPHA_DISABLE = 0;
  17643. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17644. Engine.ALPHA_ADD = 1;
  17645. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17646. Engine.ALPHA_COMBINE = 2;
  17647. /** Defines that alpha blending to DEST - SRC * DEST */
  17648. Engine.ALPHA_SUBTRACT = 3;
  17649. /** Defines that alpha blending to SRC * DEST */
  17650. Engine.ALPHA_MULTIPLY = 4;
  17651. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17652. Engine.ALPHA_MAXIMIZED = 5;
  17653. /** Defines that alpha blending to SRC + DEST */
  17654. Engine.ALPHA_ONEONE = 6;
  17655. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17656. Engine.ALPHA_PREMULTIPLIED = 7;
  17657. /**
  17658. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17659. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17660. */
  17661. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17662. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17663. Engine.ALPHA_INTERPOLATE = 9;
  17664. /**
  17665. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17666. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17667. */
  17668. Engine.ALPHA_SCREENMODE = 10;
  17669. /** Defines that the ressource is not delayed*/
  17670. Engine.DELAYLOADSTATE_NONE = 0;
  17671. /** Defines that the ressource was successfully delay loaded */
  17672. Engine.DELAYLOADSTATE_LOADED = 1;
  17673. /** Defines that the ressource is currently delay loading */
  17674. Engine.DELAYLOADSTATE_LOADING = 2;
  17675. /** Defines that the ressource is delayed and has not started loading */
  17676. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17677. // Depht or Stencil test Constants.
  17678. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17679. Engine.NEVER = 0x0200;
  17680. /** 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 */
  17681. Engine.ALWAYS = 0x0207;
  17682. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17683. Engine.LESS = 0x0201;
  17684. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17685. Engine.EQUAL = 0x0202;
  17686. /** 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 */
  17687. Engine.LEQUAL = 0x0203;
  17688. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17689. Engine.GREATER = 0x0204;
  17690. /** 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 */
  17691. Engine.GEQUAL = 0x0206;
  17692. /** 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 */
  17693. Engine.NOTEQUAL = 0x0205;
  17694. // Stencil Actions Constants.
  17695. /** Passed to stencilOperation to specify that stencil value must be kept */
  17696. Engine.KEEP = 0x1E00;
  17697. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17698. Engine.REPLACE = 0x1E01;
  17699. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17700. Engine.INCR = 0x1E02;
  17701. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17702. Engine.DECR = 0x1E03;
  17703. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17704. Engine.INVERT = 0x150A;
  17705. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17706. Engine.INCR_WRAP = 0x8507;
  17707. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17708. Engine.DECR_WRAP = 0x8508;
  17709. /** Texture is not repeating outside of 0..1 UVs */
  17710. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17711. /** Texture is repeating outside of 0..1 UVs */
  17712. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17713. /** Texture is repeating and mirrored */
  17714. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17715. /** ALPHA */
  17716. Engine.TEXTUREFORMAT_ALPHA = 0;
  17717. /** LUMINANCE */
  17718. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17719. /** LUMINANCE_ALPHA */
  17720. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17721. /** RGB */
  17722. Engine.TEXTUREFORMAT_RGB = 4;
  17723. /** RGBA */
  17724. Engine.TEXTUREFORMAT_RGBA = 5;
  17725. /** RED */
  17726. Engine.TEXTUREFORMAT_RED = 6;
  17727. /** RED (2nd reference) */
  17728. Engine.TEXTUREFORMAT_R = 6;
  17729. /** RG */
  17730. Engine.TEXTUREFORMAT_RG = 7;
  17731. /** RED_INTEGER */
  17732. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17733. /** RED_INTEGER (2nd reference) */
  17734. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17735. /** RG_INTEGER */
  17736. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17737. /** RGB_INTEGER */
  17738. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17739. /** RGBA_INTEGER */
  17740. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17741. /** UNSIGNED_BYTE */
  17742. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17743. /** UNSIGNED_BYTE (2nd reference) */
  17744. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17745. /** FLOAT */
  17746. Engine.TEXTURETYPE_FLOAT = 1;
  17747. /** HALF_FLOAT */
  17748. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17749. /** BYTE */
  17750. Engine.TEXTURETYPE_BYTE = 3;
  17751. /** SHORT */
  17752. Engine.TEXTURETYPE_SHORT = 4;
  17753. /** UNSIGNED_SHORT */
  17754. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17755. /** INT */
  17756. Engine.TEXTURETYPE_INT = 6;
  17757. /** UNSIGNED_INT */
  17758. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17759. /** UNSIGNED_SHORT_4_4_4_4 */
  17760. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17761. /** UNSIGNED_SHORT_5_5_5_1 */
  17762. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17763. /** UNSIGNED_SHORT_5_6_5 */
  17764. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17765. /** UNSIGNED_INT_2_10_10_10_REV */
  17766. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17767. /** UNSIGNED_INT_24_8 */
  17768. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17769. /** UNSIGNED_INT_10F_11F_11F_REV */
  17770. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17771. /** UNSIGNED_INT_5_9_9_9_REV */
  17772. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17773. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17774. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17775. /** nearest is mag = nearest and min = nearest and mip = linear */
  17776. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17777. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17778. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17779. /** Trilinear is mag = linear and min = linear and mip = linear */
  17780. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17781. /** nearest is mag = nearest and min = nearest and mip = linear */
  17782. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17783. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17784. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17785. /** Trilinear is mag = linear and min = linear and mip = linear */
  17786. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17787. /** mag = nearest and min = nearest and mip = nearest */
  17788. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17789. /** mag = nearest and min = linear and mip = nearest */
  17790. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17791. /** mag = nearest and min = linear and mip = linear */
  17792. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17793. /** mag = nearest and min = linear and mip = none */
  17794. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17795. /** mag = nearest and min = nearest and mip = none */
  17796. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17797. /** mag = linear and min = nearest and mip = nearest */
  17798. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17799. /** mag = linear and min = nearest and mip = linear */
  17800. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17801. /** mag = linear and min = linear and mip = none */
  17802. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17803. /** mag = linear and min = nearest and mip = none */
  17804. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17805. /** Explicit coordinates mode */
  17806. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17807. /** Spherical coordinates mode */
  17808. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17809. /** Planar coordinates mode */
  17810. Engine.TEXTURE_PLANAR_MODE = 2;
  17811. /** Cubic coordinates mode */
  17812. Engine.TEXTURE_CUBIC_MODE = 3;
  17813. /** Projection coordinates mode */
  17814. Engine.TEXTURE_PROJECTION_MODE = 4;
  17815. /** Skybox coordinates mode */
  17816. Engine.TEXTURE_SKYBOX_MODE = 5;
  17817. /** Inverse Cubic coordinates mode */
  17818. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17819. /** Equirectangular coordinates mode */
  17820. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17821. /** Equirectangular Fixed coordinates mode */
  17822. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17823. /** Equirectangular Fixed Mirrored coordinates mode */
  17824. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17825. // Texture rescaling mode
  17826. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17827. Engine.SCALEMODE_FLOOR = 1;
  17828. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17829. Engine.SCALEMODE_NEAREST = 2;
  17830. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17831. Engine.SCALEMODE_CEILING = 3;
  17832. // Updatable statics so stick with vars here
  17833. /**
  17834. * Gets or sets the epsilon value used by collision engine
  17835. */
  17836. Engine.CollisionsEpsilon = 0.001;
  17837. /**
  17838. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17839. */
  17840. Engine.CodeRepository = "src/";
  17841. /**
  17842. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17843. */
  17844. Engine.ShadersRepository = "src/Shaders/";
  17845. return Engine;
  17846. }());
  17847. BABYLON.Engine = Engine;
  17848. })(BABYLON || (BABYLON = {}));
  17849. //# sourceMappingURL=babylon.engine.js.map
  17850. var BABYLON;
  17851. (function (BABYLON) {
  17852. /**
  17853. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17854. */
  17855. var Node = /** @class */ (function () {
  17856. /**
  17857. * Creates a new Node
  17858. * @param {string} name - the name and id to be given to this node
  17859. * @param {BABYLON.Scene} the scene this node will be added to
  17860. */
  17861. function Node(name, scene) {
  17862. if (scene === void 0) { scene = null; }
  17863. /**
  17864. * Gets or sets a string used to store user defined state for the node
  17865. */
  17866. this.state = "";
  17867. /**
  17868. * Gets or sets an object used to store user defined information for the node
  17869. */
  17870. this.metadata = null;
  17871. /**
  17872. * Gets or sets a boolean used to define if the node must be serialized
  17873. */
  17874. this.doNotSerialize = false;
  17875. /** @hidden */
  17876. this._isDisposed = false;
  17877. /**
  17878. * Gets a list of Animations associated with the node
  17879. */
  17880. this.animations = new Array();
  17881. this._ranges = {};
  17882. this._isEnabled = true;
  17883. this._isParentEnabled = true;
  17884. this._isReady = true;
  17885. /** @hidden */
  17886. this._currentRenderId = -1;
  17887. this._parentRenderId = -1;
  17888. this._childRenderId = -1;
  17889. /** @hidden */
  17890. this._worldMatrix = BABYLON.Matrix.Identity();
  17891. /** @hidden */
  17892. this._worldMatrixDeterminant = 0;
  17893. this._animationPropertiesOverride = null;
  17894. /**
  17895. * An event triggered when the mesh is disposed
  17896. */
  17897. this.onDisposeObservable = new BABYLON.Observable();
  17898. // Behaviors
  17899. this._behaviors = new Array();
  17900. this.name = name;
  17901. this.id = name;
  17902. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17903. this.uniqueId = this._scene.getUniqueId();
  17904. this._initCache();
  17905. this._scene.rootNodes.push(this);
  17906. }
  17907. /**
  17908. * Add a new node constructor
  17909. * @param type defines the type name of the node to construct
  17910. * @param constructorFunc defines the constructor function
  17911. */
  17912. Node.AddNodeConstructor = function (type, constructorFunc) {
  17913. this._NodeConstructors[type] = constructorFunc;
  17914. };
  17915. /**
  17916. * Returns a node constructor based on type name
  17917. * @param type defines the type name
  17918. * @param name defines the new node name
  17919. * @param scene defines the hosting scene
  17920. * @param options defines optional options to transmit to constructors
  17921. * @returns the new constructor or null
  17922. */
  17923. Node.Construct = function (type, name, scene, options) {
  17924. var constructorFunc = this._NodeConstructors[type];
  17925. if (!constructorFunc) {
  17926. return null;
  17927. }
  17928. return constructorFunc(name, scene, options);
  17929. };
  17930. /**
  17931. * Gets a boolean indicating if the node has been disposed
  17932. * @returns true if the node was disposed
  17933. */
  17934. Node.prototype.isDisposed = function () {
  17935. return this._isDisposed;
  17936. };
  17937. Object.defineProperty(Node.prototype, "parent", {
  17938. get: function () {
  17939. return this._parentNode;
  17940. },
  17941. /**
  17942. * Gets or sets the parent of the node
  17943. */
  17944. set: function (parent) {
  17945. if (this._parentNode === parent) {
  17946. return;
  17947. }
  17948. var previousParentNode = this._parentNode;
  17949. // Remove self from list of children of parent
  17950. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17951. var index = this._parentNode._children.indexOf(this);
  17952. if (index !== -1) {
  17953. this._parentNode._children.splice(index, 1);
  17954. }
  17955. if (!parent) {
  17956. // Need to add this node to the rootNodes
  17957. this._scene.rootNodes.push(this);
  17958. }
  17959. }
  17960. // Store new parent
  17961. this._parentNode = parent;
  17962. // Add as child to new parent
  17963. if (this._parentNode) {
  17964. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17965. this._parentNode._children = new Array();
  17966. }
  17967. this._parentNode._children.push(this);
  17968. if (!previousParentNode) {
  17969. // Need to remove from rootNodes
  17970. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  17971. if (rootNodeIndex > -1) {
  17972. this._scene.rootNodes.splice(rootNodeIndex, 1);
  17973. }
  17974. }
  17975. }
  17976. // Enabled state
  17977. this._syncParentEnabledState();
  17978. },
  17979. enumerable: true,
  17980. configurable: true
  17981. });
  17982. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17983. /**
  17984. * Gets or sets the animation properties override
  17985. */
  17986. get: function () {
  17987. if (!this._animationPropertiesOverride) {
  17988. return this._scene.animationPropertiesOverride;
  17989. }
  17990. return this._animationPropertiesOverride;
  17991. },
  17992. set: function (value) {
  17993. this._animationPropertiesOverride = value;
  17994. },
  17995. enumerable: true,
  17996. configurable: true
  17997. });
  17998. /**
  17999. * Gets a string idenfifying the name of the class
  18000. * @returns "Node" string
  18001. */
  18002. Node.prototype.getClassName = function () {
  18003. return "Node";
  18004. };
  18005. Object.defineProperty(Node.prototype, "onDispose", {
  18006. /**
  18007. * Sets a callback that will be raised when the node will be disposed
  18008. */
  18009. set: function (callback) {
  18010. if (this._onDisposeObserver) {
  18011. this.onDisposeObservable.remove(this._onDisposeObserver);
  18012. }
  18013. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18014. },
  18015. enumerable: true,
  18016. configurable: true
  18017. });
  18018. /**
  18019. * Gets the scene of the node
  18020. * @returns a {BABYLON.Scene}
  18021. */
  18022. Node.prototype.getScene = function () {
  18023. return this._scene;
  18024. };
  18025. /**
  18026. * Gets the engine of the node
  18027. * @returns a {BABYLON.Engine}
  18028. */
  18029. Node.prototype.getEngine = function () {
  18030. return this._scene.getEngine();
  18031. };
  18032. /**
  18033. * Attach a behavior to the node
  18034. * @see http://doc.babylonjs.com/features/behaviour
  18035. * @param behavior defines the behavior to attach
  18036. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  18037. * @returns the current Node
  18038. */
  18039. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  18040. var _this = this;
  18041. if (attachImmediately === void 0) { attachImmediately = false; }
  18042. var index = this._behaviors.indexOf(behavior);
  18043. if (index !== -1) {
  18044. return this;
  18045. }
  18046. behavior.init();
  18047. if (this._scene.isLoading && !attachImmediately) {
  18048. // We defer the attach when the scene will be loaded
  18049. this._scene.onDataLoadedObservable.addOnce(function () {
  18050. behavior.attach(_this);
  18051. });
  18052. }
  18053. else {
  18054. behavior.attach(this);
  18055. }
  18056. this._behaviors.push(behavior);
  18057. return this;
  18058. };
  18059. /**
  18060. * Remove an attached behavior
  18061. * @see http://doc.babylonjs.com/features/behaviour
  18062. * @param behavior defines the behavior to attach
  18063. * @returns the current Node
  18064. */
  18065. Node.prototype.removeBehavior = function (behavior) {
  18066. var index = this._behaviors.indexOf(behavior);
  18067. if (index === -1) {
  18068. return this;
  18069. }
  18070. this._behaviors[index].detach();
  18071. this._behaviors.splice(index, 1);
  18072. return this;
  18073. };
  18074. Object.defineProperty(Node.prototype, "behaviors", {
  18075. /**
  18076. * Gets the list of attached behaviors
  18077. * @see http://doc.babylonjs.com/features/behaviour
  18078. */
  18079. get: function () {
  18080. return this._behaviors;
  18081. },
  18082. enumerable: true,
  18083. configurable: true
  18084. });
  18085. /**
  18086. * Gets an attached behavior by name
  18087. * @param name defines the name of the behavior to look for
  18088. * @see http://doc.babylonjs.com/features/behaviour
  18089. * @returns null if behavior was not found else the requested behavior
  18090. */
  18091. Node.prototype.getBehaviorByName = function (name) {
  18092. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  18093. var behavior = _a[_i];
  18094. if (behavior.name === name) {
  18095. return behavior;
  18096. }
  18097. }
  18098. return null;
  18099. };
  18100. /**
  18101. * Returns the latest update of the World matrix
  18102. * @returns a Matrix
  18103. */
  18104. Node.prototype.getWorldMatrix = function () {
  18105. if (this._currentRenderId !== this._scene.getRenderId()) {
  18106. this.computeWorldMatrix();
  18107. }
  18108. return this._worldMatrix;
  18109. };
  18110. /** @hidden */
  18111. Node.prototype._getWorldMatrixDeterminant = function () {
  18112. return this._worldMatrixDeterminant;
  18113. };
  18114. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  18115. /**
  18116. * Returns directly the latest state of the mesh World matrix.
  18117. * A Matrix is returned.
  18118. */
  18119. get: function () {
  18120. return this._worldMatrix;
  18121. },
  18122. enumerable: true,
  18123. configurable: true
  18124. });
  18125. // override it in derived class if you add new variables to the cache
  18126. // and call the parent class method
  18127. /** @hidden */
  18128. Node.prototype._initCache = function () {
  18129. this._cache = {};
  18130. this._cache.parent = undefined;
  18131. };
  18132. /** @hidden */
  18133. Node.prototype.updateCache = function (force) {
  18134. if (!force && this.isSynchronized())
  18135. return;
  18136. this._cache.parent = this.parent;
  18137. this._updateCache();
  18138. };
  18139. // override it in derived class if you add new variables to the cache
  18140. // and call the parent class method if !ignoreParentClass
  18141. /** @hidden */
  18142. Node.prototype._updateCache = function (ignoreParentClass) {
  18143. };
  18144. // override it in derived class if you add new variables to the cache
  18145. /** @hidden */
  18146. Node.prototype._isSynchronized = function () {
  18147. return true;
  18148. };
  18149. /** @hidden */
  18150. Node.prototype._markSyncedWithParent = function () {
  18151. if (this._parentNode) {
  18152. this._parentRenderId = this._parentNode._childRenderId;
  18153. }
  18154. };
  18155. /** @hidden */
  18156. Node.prototype.isSynchronizedWithParent = function () {
  18157. if (!this._parentNode) {
  18158. return true;
  18159. }
  18160. if (this._parentRenderId !== this._parentNode._childRenderId) {
  18161. return false;
  18162. }
  18163. return this._parentNode.isSynchronized();
  18164. };
  18165. /** @hidden */
  18166. Node.prototype.isSynchronized = function () {
  18167. if (this._cache.parent != this._parentNode) {
  18168. this._cache.parent = this._parentNode;
  18169. return false;
  18170. }
  18171. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18172. return false;
  18173. }
  18174. return this._isSynchronized();
  18175. };
  18176. /**
  18177. * Is this node ready to be used/rendered
  18178. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18179. * @return true if the node is ready
  18180. */
  18181. Node.prototype.isReady = function (completeCheck) {
  18182. if (completeCheck === void 0) { completeCheck = false; }
  18183. return this._isReady;
  18184. };
  18185. /**
  18186. * Is this node enabled?
  18187. * 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
  18188. * @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
  18189. * @return whether this node (and its parent) is enabled
  18190. */
  18191. Node.prototype.isEnabled = function (checkAncestors) {
  18192. if (checkAncestors === void 0) { checkAncestors = true; }
  18193. if (checkAncestors === false) {
  18194. return this._isEnabled;
  18195. }
  18196. if (!this._isEnabled) {
  18197. return false;
  18198. }
  18199. return this._isParentEnabled;
  18200. };
  18201. /** @hidden */
  18202. Node.prototype._syncParentEnabledState = function () {
  18203. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18204. if (this._children) {
  18205. this._children.forEach(function (c) {
  18206. c._syncParentEnabledState(); // Force children to update accordingly
  18207. });
  18208. }
  18209. };
  18210. /**
  18211. * Set the enabled state of this node
  18212. * @param value defines the new enabled state
  18213. */
  18214. Node.prototype.setEnabled = function (value) {
  18215. this._isEnabled = value;
  18216. this._syncParentEnabledState();
  18217. };
  18218. /**
  18219. * Is this node a descendant of the given node?
  18220. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18221. * @param ancestor defines the parent node to inspect
  18222. * @returns a boolean indicating if this node is a descendant of the given node
  18223. */
  18224. Node.prototype.isDescendantOf = function (ancestor) {
  18225. if (this.parent) {
  18226. if (this.parent === ancestor) {
  18227. return true;
  18228. }
  18229. return this.parent.isDescendantOf(ancestor);
  18230. }
  18231. return false;
  18232. };
  18233. /** @hidden */
  18234. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18235. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18236. if (!this._children) {
  18237. return;
  18238. }
  18239. for (var index = 0; index < this._children.length; index++) {
  18240. var item = this._children[index];
  18241. if (!predicate || predicate(item)) {
  18242. results.push(item);
  18243. }
  18244. if (!directDescendantsOnly) {
  18245. item._getDescendants(results, false, predicate);
  18246. }
  18247. }
  18248. };
  18249. /**
  18250. * Will return all nodes that have this node as ascendant
  18251. * @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
  18252. * @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
  18253. * @return all children nodes of all types
  18254. */
  18255. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18256. var results = new Array();
  18257. this._getDescendants(results, directDescendantsOnly, predicate);
  18258. return results;
  18259. };
  18260. /**
  18261. * Get all child-meshes of this node
  18262. * @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
  18263. * @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
  18264. * @returns an array of {BABYLON.AbstractMesh}
  18265. */
  18266. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18267. var results = [];
  18268. this._getDescendants(results, directDescendantsOnly, function (node) {
  18269. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18270. });
  18271. return results;
  18272. };
  18273. /**
  18274. * Get all child-transformNodes of this node
  18275. * @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
  18276. * @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
  18277. * @returns an array of {BABYLON.TransformNode}
  18278. */
  18279. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18280. var results = [];
  18281. this._getDescendants(results, directDescendantsOnly, function (node) {
  18282. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18283. });
  18284. return results;
  18285. };
  18286. /**
  18287. * Get all direct children of this node
  18288. * @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
  18289. * @returns an array of {BABYLON.Node}
  18290. */
  18291. Node.prototype.getChildren = function (predicate) {
  18292. return this.getDescendants(true, predicate);
  18293. };
  18294. /** @hidden */
  18295. Node.prototype._setReady = function (state) {
  18296. if (state === this._isReady) {
  18297. return;
  18298. }
  18299. if (!state) {
  18300. this._isReady = false;
  18301. return;
  18302. }
  18303. if (this.onReady) {
  18304. this.onReady(this);
  18305. }
  18306. this._isReady = true;
  18307. };
  18308. /**
  18309. * Get an animation by name
  18310. * @param name defines the name of the animation to look for
  18311. * @returns null if not found else the requested animation
  18312. */
  18313. Node.prototype.getAnimationByName = function (name) {
  18314. for (var i = 0; i < this.animations.length; i++) {
  18315. var animation = this.animations[i];
  18316. if (animation.name === name) {
  18317. return animation;
  18318. }
  18319. }
  18320. return null;
  18321. };
  18322. /**
  18323. * Creates an animation range for this node
  18324. * @param name defines the name of the range
  18325. * @param from defines the starting key
  18326. * @param to defines the end key
  18327. */
  18328. Node.prototype.createAnimationRange = function (name, from, to) {
  18329. // check name not already in use
  18330. if (!this._ranges[name]) {
  18331. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18332. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18333. if (this.animations[i]) {
  18334. this.animations[i].createRange(name, from, to);
  18335. }
  18336. }
  18337. }
  18338. };
  18339. /**
  18340. * Delete a specific animation range
  18341. * @param name defines the name of the range to delete
  18342. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18343. */
  18344. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18345. if (deleteFrames === void 0) { deleteFrames = true; }
  18346. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18347. if (this.animations[i]) {
  18348. this.animations[i].deleteRange(name, deleteFrames);
  18349. }
  18350. }
  18351. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18352. };
  18353. /**
  18354. * Get an animation range by name
  18355. * @param name defines the name of the animation range to look for
  18356. * @returns null if not found else the requested animation range
  18357. */
  18358. Node.prototype.getAnimationRange = function (name) {
  18359. return this._ranges[name];
  18360. };
  18361. /**
  18362. * Will start the animation sequence
  18363. * @param name defines the range frames for animation sequence
  18364. * @param loop defines if the animation should loop (false by default)
  18365. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18366. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18367. * @returns the object created for this animation. If range does not exist, it will return null
  18368. */
  18369. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18370. var range = this.getAnimationRange(name);
  18371. if (!range) {
  18372. return null;
  18373. }
  18374. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18375. };
  18376. /**
  18377. * Serialize animation ranges into a JSON compatible object
  18378. * @returns serialization object
  18379. */
  18380. Node.prototype.serializeAnimationRanges = function () {
  18381. var serializationRanges = [];
  18382. for (var name in this._ranges) {
  18383. var localRange = this._ranges[name];
  18384. if (!localRange) {
  18385. continue;
  18386. }
  18387. var range = {};
  18388. range.name = name;
  18389. range.from = localRange.from;
  18390. range.to = localRange.to;
  18391. serializationRanges.push(range);
  18392. }
  18393. return serializationRanges;
  18394. };
  18395. /**
  18396. * Computes the world matrix of the node
  18397. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18398. * @returns the world matrix
  18399. */
  18400. Node.prototype.computeWorldMatrix = function (force) {
  18401. if (!this._worldMatrix) {
  18402. this._worldMatrix = BABYLON.Matrix.Identity();
  18403. }
  18404. return this._worldMatrix;
  18405. };
  18406. /**
  18407. * Releases resources associated with this node.
  18408. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18409. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18410. */
  18411. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18412. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18413. if (!doNotRecurse) {
  18414. var nodes = this.getDescendants(true);
  18415. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18416. var node = nodes_1[_i];
  18417. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18418. }
  18419. }
  18420. else {
  18421. var transformNodes = this.getChildTransformNodes(true);
  18422. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18423. var transformNode = transformNodes_1[_a];
  18424. transformNode.parent = null;
  18425. transformNode.computeWorldMatrix(true);
  18426. }
  18427. }
  18428. if (!this.parent) {
  18429. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18430. if (rootNodeIndex > -1) {
  18431. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18432. }
  18433. }
  18434. else {
  18435. this.parent = null;
  18436. }
  18437. // Callback
  18438. this.onDisposeObservable.notifyObservers(this);
  18439. this.onDisposeObservable.clear();
  18440. // Behaviors
  18441. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18442. var behavior = _c[_b];
  18443. behavior.detach();
  18444. }
  18445. this._behaviors = [];
  18446. this._isDisposed = true;
  18447. };
  18448. /**
  18449. * Parse animation range data from a serialization object and store them into a given node
  18450. * @param node defines where to store the animation ranges
  18451. * @param parsedNode defines the serialization object to read data from
  18452. * @param scene defines the hosting scene
  18453. */
  18454. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18455. if (parsedNode.ranges) {
  18456. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18457. var data = parsedNode.ranges[index];
  18458. node.createAnimationRange(data.name, data.from, data.to);
  18459. }
  18460. }
  18461. };
  18462. Node._NodeConstructors = {};
  18463. __decorate([
  18464. BABYLON.serialize()
  18465. ], Node.prototype, "name", void 0);
  18466. __decorate([
  18467. BABYLON.serialize()
  18468. ], Node.prototype, "id", void 0);
  18469. __decorate([
  18470. BABYLON.serialize()
  18471. ], Node.prototype, "uniqueId", void 0);
  18472. __decorate([
  18473. BABYLON.serialize()
  18474. ], Node.prototype, "state", void 0);
  18475. __decorate([
  18476. BABYLON.serialize()
  18477. ], Node.prototype, "metadata", void 0);
  18478. return Node;
  18479. }());
  18480. BABYLON.Node = Node;
  18481. })(BABYLON || (BABYLON = {}));
  18482. //# sourceMappingURL=babylon.node.js.map
  18483. var BABYLON;
  18484. (function (BABYLON) {
  18485. // This matrix is used as a value to reset the bounding box.
  18486. var _identityMatrix = BABYLON.Matrix.Identity();
  18487. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18488. /**
  18489. * Class used to store bounding sphere information
  18490. */
  18491. var BoundingSphere = /** @class */ (function () {
  18492. /**
  18493. * Creates a new bounding sphere
  18494. * @param min defines the minimum vector (in local space)
  18495. * @param max defines the maximum vector (in local space)
  18496. */
  18497. function BoundingSphere(min, max) {
  18498. this.center = BABYLON.Vector3.Zero();
  18499. this.centerWorld = BABYLON.Vector3.Zero();
  18500. this.reConstruct(min, max);
  18501. }
  18502. /**
  18503. * Recreates the entire bounding sphere from scratch
  18504. * @param min defines the new minimum vector (in local space)
  18505. * @param max defines the new maximum vector (in local space)
  18506. */
  18507. BoundingSphere.prototype.reConstruct = function (min, max) {
  18508. this.minimum = min.clone();
  18509. this.maximum = max.clone();
  18510. var distance = BABYLON.Vector3.Distance(min, max);
  18511. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18512. this.radius = distance * 0.5;
  18513. this.centerWorld.set(0, 0, 0);
  18514. this._update(_identityMatrix);
  18515. };
  18516. /**
  18517. * Scale the current bounding sphere by applying a scale factor
  18518. * @param factor defines the scale factor to apply
  18519. * @returns the current bounding box
  18520. */
  18521. BoundingSphere.prototype.scale = function (factor) {
  18522. var newRadius = this.radius * factor;
  18523. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18524. var min = this.center.subtract(_tempRadiusVector);
  18525. var max = this.center.add(_tempRadiusVector);
  18526. this.reConstruct(min, max);
  18527. return this;
  18528. };
  18529. // Methods
  18530. /** @hidden */
  18531. BoundingSphere.prototype._update = function (world) {
  18532. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18533. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18534. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18535. };
  18536. /**
  18537. * Tests if the bounding sphere is intersecting the frustum planes
  18538. * @param frustumPlanes defines the frustum planes to test
  18539. * @returns true if there is an intersection
  18540. */
  18541. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18542. for (var i = 0; i < 6; i++) {
  18543. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18544. return false;
  18545. }
  18546. return true;
  18547. };
  18548. /**
  18549. * Tests if a point is inside the bounding sphere
  18550. * @param point defines the point to test
  18551. * @returns true if the point is inside the bounding sphere
  18552. */
  18553. BoundingSphere.prototype.intersectsPoint = function (point) {
  18554. var x = this.centerWorld.x - point.x;
  18555. var y = this.centerWorld.y - point.y;
  18556. var z = this.centerWorld.z - point.z;
  18557. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18558. if (this.radiusWorld < distance)
  18559. return false;
  18560. return true;
  18561. };
  18562. // Statics
  18563. /**
  18564. * Checks if two sphere intersct
  18565. * @param sphere0 sphere 0
  18566. * @param sphere1 sphere 1
  18567. * @returns true if the speres intersect
  18568. */
  18569. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18570. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18571. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18572. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18573. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18574. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18575. return false;
  18576. return true;
  18577. };
  18578. return BoundingSphere;
  18579. }());
  18580. BABYLON.BoundingSphere = BoundingSphere;
  18581. })(BABYLON || (BABYLON = {}));
  18582. //# sourceMappingURL=babylon.boundingSphere.js.map
  18583. var BABYLON;
  18584. (function (BABYLON) {
  18585. /**
  18586. * Class used to store bounding box information
  18587. */
  18588. var BoundingBox = /** @class */ (function () {
  18589. /**
  18590. * Creates a new bounding box
  18591. * @param min defines the minimum vector (in local space)
  18592. * @param max defines the maximum vector (in local space)
  18593. */
  18594. function BoundingBox(min, max) {
  18595. /**
  18596. * Gets the 8 vectors representing the bounding box in world space
  18597. */
  18598. this.vectorsWorld = new Array();
  18599. this.reConstruct(min, max);
  18600. }
  18601. // Methods
  18602. /**
  18603. * Recreates the entire bounding box from scratch
  18604. * @param min defines the new minimum vector (in local space)
  18605. * @param max defines the new maximum vector (in local space)
  18606. */
  18607. BoundingBox.prototype.reConstruct = function (min, max) {
  18608. this.minimum = min.clone();
  18609. this.maximum = max.clone();
  18610. // Bounding vectors
  18611. this.vectors = [
  18612. this.minimum.clone(),
  18613. this.maximum.clone(),
  18614. this.minimum.clone(),
  18615. this.minimum.clone(),
  18616. this.minimum.clone(),
  18617. this.maximum.clone(),
  18618. this.maximum.clone(),
  18619. this.maximum.clone()
  18620. ];
  18621. this.vectors[2].x = this.maximum.x;
  18622. this.vectors[3].y = this.maximum.y;
  18623. this.vectors[4].z = this.maximum.z;
  18624. this.vectors[5].z = this.minimum.z;
  18625. this.vectors[6].x = this.minimum.x;
  18626. this.vectors[7].y = this.minimum.y;
  18627. // OBB
  18628. this.center = this.maximum.add(this.minimum).scale(0.5);
  18629. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18630. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18631. // World
  18632. for (var index = 0; index < this.vectors.length; index++) {
  18633. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18634. }
  18635. this.minimumWorld = BABYLON.Vector3.Zero();
  18636. this.maximumWorld = BABYLON.Vector3.Zero();
  18637. this.centerWorld = BABYLON.Vector3.Zero();
  18638. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18639. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18640. };
  18641. /**
  18642. * Scale the current bounding box by applying a scale factor
  18643. * @param factor defines the scale factor to apply
  18644. * @returns the current bounding box
  18645. */
  18646. BoundingBox.prototype.scale = function (factor) {
  18647. var diff = this.maximum.subtract(this.minimum);
  18648. var distance = diff.length() * factor;
  18649. diff.normalize();
  18650. var newRadius = diff.scale(distance / 2);
  18651. var min = this.center.subtract(newRadius);
  18652. var max = this.center.add(newRadius);
  18653. this.reConstruct(min, max);
  18654. return this;
  18655. };
  18656. /**
  18657. * Gets the world matrix of the bounding box
  18658. * @returns a matrix
  18659. */
  18660. BoundingBox.prototype.getWorldMatrix = function () {
  18661. return this._worldMatrix;
  18662. };
  18663. /**
  18664. * Sets the world matrix stored in the bounding box
  18665. * @param matrix defines the matrix to store
  18666. * @returns current bounding box
  18667. */
  18668. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18669. this._worldMatrix.copyFrom(matrix);
  18670. return this;
  18671. };
  18672. /** @hidden */
  18673. BoundingBox.prototype._update = function (world) {
  18674. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18675. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18676. for (var index = 0; index < this.vectors.length; index++) {
  18677. var v = this.vectorsWorld[index];
  18678. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18679. if (v.x < this.minimumWorld.x)
  18680. this.minimumWorld.x = v.x;
  18681. if (v.y < this.minimumWorld.y)
  18682. this.minimumWorld.y = v.y;
  18683. if (v.z < this.minimumWorld.z)
  18684. this.minimumWorld.z = v.z;
  18685. if (v.x > this.maximumWorld.x)
  18686. this.maximumWorld.x = v.x;
  18687. if (v.y > this.maximumWorld.y)
  18688. this.maximumWorld.y = v.y;
  18689. if (v.z > this.maximumWorld.z)
  18690. this.maximumWorld.z = v.z;
  18691. }
  18692. // Extend
  18693. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18694. this.extendSizeWorld.scaleInPlace(0.5);
  18695. // OBB
  18696. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18697. this.centerWorld.scaleInPlace(0.5);
  18698. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18699. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18700. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18701. this._worldMatrix = world;
  18702. };
  18703. /**
  18704. * Tests if the bounding box is intersecting the frustum planes
  18705. * @param frustumPlanes defines the frustum planes to test
  18706. * @returns true if there is an intersection
  18707. */
  18708. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18709. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18710. };
  18711. /**
  18712. * Tests if the bounding box is entirely inside the frustum planes
  18713. * @param frustumPlanes defines the frustum planes to test
  18714. * @returns true if there is an inclusion
  18715. */
  18716. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18717. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18718. };
  18719. /**
  18720. * Tests if a point is inside the bounding box
  18721. * @param point defines the point to test
  18722. * @returns true if the point is inside the bounding box
  18723. */
  18724. BoundingBox.prototype.intersectsPoint = function (point) {
  18725. var delta = -BABYLON.Epsilon;
  18726. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18727. return false;
  18728. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18729. return false;
  18730. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18731. return false;
  18732. return true;
  18733. };
  18734. /**
  18735. * Tests if the bounding box intersects with a bounding sphere
  18736. * @param sphere defines the sphere to test
  18737. * @returns true if there is an intersection
  18738. */
  18739. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18740. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18741. };
  18742. /**
  18743. * Tests if the bounding box intersects with a box defined by a min and max vectors
  18744. * @param min defines the min vector to use
  18745. * @param max defines the max vector to use
  18746. * @returns true if there is an intersection
  18747. */
  18748. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18749. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18750. return false;
  18751. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18752. return false;
  18753. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18754. return false;
  18755. return true;
  18756. };
  18757. // Statics
  18758. /**
  18759. * Tests if two bounding boxes are intersections
  18760. * @param box0 defines the first box to test
  18761. * @param box1 defines the second box to test
  18762. * @returns true if there is an intersection
  18763. */
  18764. BoundingBox.Intersects = function (box0, box1) {
  18765. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18766. return false;
  18767. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18768. return false;
  18769. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18770. return false;
  18771. return true;
  18772. };
  18773. /**
  18774. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  18775. * @param minPoint defines the minimum vector of the bounding box
  18776. * @param maxPoint defines the maximum vector of the bounding box
  18777. * @param sphereCenter defines the sphere center
  18778. * @param sphereRadius defines the sphere radius
  18779. * @returns true if there is an intersection
  18780. */
  18781. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18782. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18783. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18784. return (num <= (sphereRadius * sphereRadius));
  18785. };
  18786. /**
  18787. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  18788. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  18789. * @param frustumPlanes defines the frustum planes to test
  18790. * @return true if there is an inclusion
  18791. */
  18792. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18793. for (var p = 0; p < 6; p++) {
  18794. for (var i = 0; i < 8; i++) {
  18795. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18796. return false;
  18797. }
  18798. }
  18799. }
  18800. return true;
  18801. };
  18802. /**
  18803. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  18804. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  18805. * @param frustumPlanes defines the frustum planes to test
  18806. * @return true if there is an intersection
  18807. */
  18808. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18809. for (var p = 0; p < 6; p++) {
  18810. var inCount = 8;
  18811. for (var i = 0; i < 8; i++) {
  18812. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18813. --inCount;
  18814. }
  18815. else {
  18816. break;
  18817. }
  18818. }
  18819. if (inCount === 0)
  18820. return false;
  18821. }
  18822. return true;
  18823. };
  18824. return BoundingBox;
  18825. }());
  18826. BABYLON.BoundingBox = BoundingBox;
  18827. })(BABYLON || (BABYLON = {}));
  18828. //# sourceMappingURL=babylon.boundingBox.js.map
  18829. var BABYLON;
  18830. (function (BABYLON) {
  18831. var computeBoxExtents = function (axis, box) {
  18832. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18833. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18834. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18835. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18836. var r = r0 + r1 + r2;
  18837. return {
  18838. min: p - r,
  18839. max: p + r
  18840. };
  18841. };
  18842. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18843. var axisOverlap = function (axis, box0, box1) {
  18844. var result0 = computeBoxExtents(axis, box0);
  18845. var result1 = computeBoxExtents(axis, box1);
  18846. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18847. };
  18848. /**
  18849. * Info for a bounding data of a mesh
  18850. */
  18851. var BoundingInfo = /** @class */ (function () {
  18852. /**
  18853. * Constructs bounding info
  18854. * @param minimum min vector of the bounding box/sphere
  18855. * @param maximum max vector of the bounding box/sphere
  18856. */
  18857. function BoundingInfo(
  18858. /**
  18859. * min vector of the bounding box/sphere
  18860. */
  18861. minimum,
  18862. /**
  18863. * max vector of the bounding box/sphere
  18864. */
  18865. maximum) {
  18866. this.minimum = minimum;
  18867. this.maximum = maximum;
  18868. this._isLocked = false;
  18869. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18870. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18871. }
  18872. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18873. /**
  18874. * If the info is locked and won't be updated to avoid perf overhead
  18875. */
  18876. get: function () {
  18877. return this._isLocked;
  18878. },
  18879. set: function (value) {
  18880. this._isLocked = value;
  18881. },
  18882. enumerable: true,
  18883. configurable: true
  18884. });
  18885. // Methods
  18886. /**
  18887. * Updates the boudning sphere and box
  18888. * @param world world matrix to be used to update
  18889. */
  18890. BoundingInfo.prototype.update = function (world) {
  18891. if (this._isLocked) {
  18892. return;
  18893. }
  18894. this.boundingBox._update(world);
  18895. this.boundingSphere._update(world);
  18896. };
  18897. /**
  18898. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18899. * @param center New center of the bounding info
  18900. * @param extend New extend of the bounding info
  18901. * @returns the current bounding info
  18902. */
  18903. BoundingInfo.prototype.centerOn = function (center, extend) {
  18904. this.minimum = center.subtract(extend);
  18905. this.maximum = center.add(extend);
  18906. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18907. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18908. return this;
  18909. };
  18910. /**
  18911. * Scale the current bounding info by applying a scale factor
  18912. * @param factor defines the scale factor to apply
  18913. * @returns the current bounding info
  18914. */
  18915. BoundingInfo.prototype.scale = function (factor) {
  18916. this.boundingBox.scale(factor);
  18917. this.boundingSphere.scale(factor);
  18918. return this;
  18919. };
  18920. /**
  18921. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18922. * @param frustumPlanes defines the frustum to test
  18923. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18924. * @returns true if the bounding info is in the frustum planes
  18925. */
  18926. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18927. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18928. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18929. return false;
  18930. }
  18931. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18932. return true;
  18933. }
  18934. return this.boundingBox.isInFrustum(frustumPlanes);
  18935. };
  18936. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18937. /**
  18938. * Gets the world distance between the min and max points of the bounding box
  18939. */
  18940. get: function () {
  18941. var boundingBox = this.boundingBox;
  18942. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18943. return size.length();
  18944. },
  18945. enumerable: true,
  18946. configurable: true
  18947. });
  18948. /**
  18949. * Checks if a cullable object (mesh...) is in the camera frustum
  18950. * Unlike isInFrustum this cheks the full bounding box
  18951. * @param frustumPlanes Camera near/planes
  18952. * @returns true if the object is in frustum otherwise false
  18953. */
  18954. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18955. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18956. };
  18957. /** @hidden */
  18958. BoundingInfo.prototype._checkCollision = function (collider) {
  18959. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18960. };
  18961. /**
  18962. * Checks if a point is inside the bounding box and bounding sphere or the mesh
  18963. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  18964. * @param point the point to check intersection with
  18965. * @returns if the point intersects
  18966. */
  18967. BoundingInfo.prototype.intersectsPoint = function (point) {
  18968. if (!this.boundingSphere.centerWorld) {
  18969. return false;
  18970. }
  18971. if (!this.boundingSphere.intersectsPoint(point)) {
  18972. return false;
  18973. }
  18974. if (!this.boundingBox.intersectsPoint(point)) {
  18975. return false;
  18976. }
  18977. return true;
  18978. };
  18979. /**
  18980. * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
  18981. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  18982. * @param boundingInfo the bounding info to check intersection with
  18983. * @param precise if the intersection should be done using OBB
  18984. * @returns if the bounding info intersects
  18985. */
  18986. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18987. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18988. return false;
  18989. }
  18990. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18991. return false;
  18992. }
  18993. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18994. return false;
  18995. }
  18996. if (!precise) {
  18997. return true;
  18998. }
  18999. var box0 = this.boundingBox;
  19000. var box1 = boundingInfo.boundingBox;
  19001. if (!axisOverlap(box0.directions[0], box0, box1))
  19002. return false;
  19003. if (!axisOverlap(box0.directions[1], box0, box1))
  19004. return false;
  19005. if (!axisOverlap(box0.directions[2], box0, box1))
  19006. return false;
  19007. if (!axisOverlap(box1.directions[0], box0, box1))
  19008. return false;
  19009. if (!axisOverlap(box1.directions[1], box0, box1))
  19010. return false;
  19011. if (!axisOverlap(box1.directions[2], box0, box1))
  19012. return false;
  19013. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  19014. return false;
  19015. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  19016. return false;
  19017. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  19018. return false;
  19019. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  19020. return false;
  19021. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  19022. return false;
  19023. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  19024. return false;
  19025. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  19026. return false;
  19027. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  19028. return false;
  19029. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  19030. return false;
  19031. return true;
  19032. };
  19033. return BoundingInfo;
  19034. }());
  19035. BABYLON.BoundingInfo = BoundingInfo;
  19036. })(BABYLON || (BABYLON = {}));
  19037. //# sourceMappingURL=babylon.boundingInfo.js.map
  19038. var BABYLON;
  19039. (function (BABYLON) {
  19040. var TransformNode = /** @class */ (function (_super) {
  19041. __extends(TransformNode, _super);
  19042. function TransformNode(name, scene, isPure) {
  19043. if (scene === void 0) { scene = null; }
  19044. if (isPure === void 0) { isPure = true; }
  19045. var _this = _super.call(this, name, scene) || this;
  19046. _this._forward = new BABYLON.Vector3(0, 0, 1);
  19047. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  19048. _this._up = new BABYLON.Vector3(0, 1, 0);
  19049. _this._right = new BABYLON.Vector3(1, 0, 0);
  19050. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  19051. // Properties
  19052. _this._position = BABYLON.Vector3.Zero();
  19053. _this._rotation = BABYLON.Vector3.Zero();
  19054. _this._scaling = BABYLON.Vector3.One();
  19055. _this._isDirty = false;
  19056. /**
  19057. * Set the billboard mode. Default is 0.
  19058. *
  19059. * | Value | Type | Description |
  19060. * | --- | --- | --- |
  19061. * | 0 | BILLBOARDMODE_NONE | |
  19062. * | 1 | BILLBOARDMODE_X | |
  19063. * | 2 | BILLBOARDMODE_Y | |
  19064. * | 4 | BILLBOARDMODE_Z | |
  19065. * | 7 | BILLBOARDMODE_ALL | |
  19066. *
  19067. */
  19068. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  19069. _this.scalingDeterminant = 1;
  19070. _this.infiniteDistance = false;
  19071. /**
  19072. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  19073. * By default the system will update normals to compensate
  19074. */
  19075. _this.ignoreNonUniformScaling = false;
  19076. _this._localWorld = BABYLON.Matrix.Zero();
  19077. _this._absolutePosition = BABYLON.Vector3.Zero();
  19078. _this._pivotMatrix = BABYLON.Matrix.Identity();
  19079. _this._postMultiplyPivotMatrix = false;
  19080. _this._isWorldMatrixFrozen = false;
  19081. /**
  19082. * An event triggered after the world matrix is updated
  19083. */
  19084. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  19085. _this._nonUniformScaling = false;
  19086. if (isPure) {
  19087. _this.getScene().addTransformNode(_this);
  19088. }
  19089. return _this;
  19090. }
  19091. /**
  19092. * Gets a string identifying the name of the class
  19093. * @returns "TransformNode" string
  19094. */
  19095. TransformNode.prototype.getClassName = function () {
  19096. return "TransformNode";
  19097. };
  19098. Object.defineProperty(TransformNode.prototype, "position", {
  19099. /**
  19100. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  19101. */
  19102. get: function () {
  19103. return this._position;
  19104. },
  19105. set: function (newPosition) {
  19106. this._position = newPosition;
  19107. this._isDirty = true;
  19108. },
  19109. enumerable: true,
  19110. configurable: true
  19111. });
  19112. Object.defineProperty(TransformNode.prototype, "rotation", {
  19113. /**
  19114. * 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)).
  19115. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  19116. */
  19117. get: function () {
  19118. return this._rotation;
  19119. },
  19120. set: function (newRotation) {
  19121. this._rotation = newRotation;
  19122. this._isDirty = true;
  19123. },
  19124. enumerable: true,
  19125. configurable: true
  19126. });
  19127. Object.defineProperty(TransformNode.prototype, "scaling", {
  19128. /**
  19129. * 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)).
  19130. */
  19131. get: function () {
  19132. return this._scaling;
  19133. },
  19134. set: function (newScaling) {
  19135. this._scaling = newScaling;
  19136. this._isDirty = true;
  19137. },
  19138. enumerable: true,
  19139. configurable: true
  19140. });
  19141. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  19142. /**
  19143. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  19144. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  19145. */
  19146. get: function () {
  19147. return this._rotationQuaternion;
  19148. },
  19149. set: function (quaternion) {
  19150. this._rotationQuaternion = quaternion;
  19151. //reset the rotation vector.
  19152. if (quaternion && this.rotation.length()) {
  19153. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  19154. }
  19155. },
  19156. enumerable: true,
  19157. configurable: true
  19158. });
  19159. Object.defineProperty(TransformNode.prototype, "forward", {
  19160. /**
  19161. * The forward direction of that transform in world space.
  19162. */
  19163. get: function () {
  19164. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  19165. },
  19166. enumerable: true,
  19167. configurable: true
  19168. });
  19169. Object.defineProperty(TransformNode.prototype, "up", {
  19170. /**
  19171. * The up direction of that transform in world space.
  19172. */
  19173. get: function () {
  19174. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  19175. },
  19176. enumerable: true,
  19177. configurable: true
  19178. });
  19179. Object.defineProperty(TransformNode.prototype, "right", {
  19180. /**
  19181. * The right direction of that transform in world space.
  19182. */
  19183. get: function () {
  19184. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  19185. },
  19186. enumerable: true,
  19187. configurable: true
  19188. });
  19189. /**
  19190. * Copies the parameter passed Matrix into the mesh Pose matrix.
  19191. * Returns the TransformNode.
  19192. */
  19193. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  19194. this._poseMatrix.copyFrom(matrix);
  19195. return this;
  19196. };
  19197. /**
  19198. * Returns the mesh Pose matrix.
  19199. * Returned object : Matrix
  19200. */
  19201. TransformNode.prototype.getPoseMatrix = function () {
  19202. return this._poseMatrix;
  19203. };
  19204. /** @hidden */
  19205. TransformNode.prototype._isSynchronized = function () {
  19206. if (this._isDirty) {
  19207. return false;
  19208. }
  19209. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  19210. return false;
  19211. if (this._cache.pivotMatrixUpdated) {
  19212. return false;
  19213. }
  19214. if (this.infiniteDistance) {
  19215. return false;
  19216. }
  19217. if (!this._cache.position.equals(this._position))
  19218. return false;
  19219. if (this._rotationQuaternion) {
  19220. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  19221. return false;
  19222. }
  19223. if (!this._cache.rotation.equals(this._rotation))
  19224. return false;
  19225. if (!this._cache.scaling.equals(this._scaling))
  19226. return false;
  19227. return true;
  19228. };
  19229. /** @hidden */
  19230. TransformNode.prototype._initCache = function () {
  19231. _super.prototype._initCache.call(this);
  19232. this._cache.localMatrixUpdated = false;
  19233. this._cache.position = BABYLON.Vector3.Zero();
  19234. this._cache.scaling = BABYLON.Vector3.Zero();
  19235. this._cache.rotation = BABYLON.Vector3.Zero();
  19236. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  19237. this._cache.billboardMode = -1;
  19238. };
  19239. TransformNode.prototype.markAsDirty = function (property) {
  19240. if (property === "rotation") {
  19241. this.rotationQuaternion = null;
  19242. }
  19243. this._currentRenderId = Number.MAX_VALUE;
  19244. this._isDirty = true;
  19245. return this;
  19246. };
  19247. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  19248. /**
  19249. * Returns the current mesh absolute position.
  19250. * Returns a Vector3.
  19251. */
  19252. get: function () {
  19253. return this._absolutePosition;
  19254. },
  19255. enumerable: true,
  19256. configurable: true
  19257. });
  19258. /**
  19259. * Sets a new matrix to apply before all other transformation
  19260. * @param matrix defines the transform matrix
  19261. * @returns the current TransformNode
  19262. */
  19263. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  19264. return this.setPivotMatrix(matrix, false);
  19265. };
  19266. /**
  19267. * Sets a new pivot matrix to the current node
  19268. * @param matrix defines the new pivot matrix to use
  19269. * @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
  19270. * @returns the current TransformNode
  19271. */
  19272. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  19273. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  19274. this._pivotMatrix = matrix.clone();
  19275. this._cache.pivotMatrixUpdated = true;
  19276. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  19277. if (this._postMultiplyPivotMatrix) {
  19278. if (!this._pivotMatrixInverse) {
  19279. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  19280. }
  19281. else {
  19282. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  19283. }
  19284. }
  19285. return this;
  19286. };
  19287. /**
  19288. * Returns the mesh pivot matrix.
  19289. * Default : Identity.
  19290. * A Matrix is returned.
  19291. */
  19292. TransformNode.prototype.getPivotMatrix = function () {
  19293. return this._pivotMatrix;
  19294. };
  19295. /**
  19296. * Prevents the World matrix to be computed any longer.
  19297. * Returns the TransformNode.
  19298. */
  19299. TransformNode.prototype.freezeWorldMatrix = function () {
  19300. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  19301. this.computeWorldMatrix(true);
  19302. this._isWorldMatrixFrozen = true;
  19303. return this;
  19304. };
  19305. /**
  19306. * Allows back the World matrix computation.
  19307. * Returns the TransformNode.
  19308. */
  19309. TransformNode.prototype.unfreezeWorldMatrix = function () {
  19310. this._isWorldMatrixFrozen = false;
  19311. this.computeWorldMatrix(true);
  19312. return this;
  19313. };
  19314. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  19315. /**
  19316. * True if the World matrix has been frozen.
  19317. * Returns a boolean.
  19318. */
  19319. get: function () {
  19320. return this._isWorldMatrixFrozen;
  19321. },
  19322. enumerable: true,
  19323. configurable: true
  19324. });
  19325. /**
  19326. * Retuns the mesh absolute position in the World.
  19327. * Returns a Vector3.
  19328. */
  19329. TransformNode.prototype.getAbsolutePosition = function () {
  19330. this.computeWorldMatrix();
  19331. return this._absolutePosition;
  19332. };
  19333. /**
  19334. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  19335. * Returns the TransformNode.
  19336. */
  19337. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  19338. if (!absolutePosition) {
  19339. return this;
  19340. }
  19341. var absolutePositionX;
  19342. var absolutePositionY;
  19343. var absolutePositionZ;
  19344. if (absolutePosition.x === undefined) {
  19345. if (arguments.length < 3) {
  19346. return this;
  19347. }
  19348. absolutePositionX = arguments[0];
  19349. absolutePositionY = arguments[1];
  19350. absolutePositionZ = arguments[2];
  19351. }
  19352. else {
  19353. absolutePositionX = absolutePosition.x;
  19354. absolutePositionY = absolutePosition.y;
  19355. absolutePositionZ = absolutePosition.z;
  19356. }
  19357. if (this.parent) {
  19358. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19359. invertParentWorldMatrix.invert();
  19360. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  19361. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  19362. }
  19363. else {
  19364. this.position.x = absolutePositionX;
  19365. this.position.y = absolutePositionY;
  19366. this.position.z = absolutePositionZ;
  19367. }
  19368. return this;
  19369. };
  19370. /**
  19371. * Sets the mesh position in its local space.
  19372. * Returns the TransformNode.
  19373. */
  19374. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19375. this.computeWorldMatrix();
  19376. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19377. return this;
  19378. };
  19379. /**
  19380. * Returns the mesh position in the local space from the current World matrix values.
  19381. * Returns a new Vector3.
  19382. */
  19383. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19384. this.computeWorldMatrix();
  19385. var invLocalWorldMatrix = this._localWorld.clone();
  19386. invLocalWorldMatrix.invert();
  19387. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19388. };
  19389. /**
  19390. * Translates the mesh along the passed Vector3 in its local space.
  19391. * Returns the TransformNode.
  19392. */
  19393. TransformNode.prototype.locallyTranslate = function (vector3) {
  19394. this.computeWorldMatrix(true);
  19395. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19396. return this;
  19397. };
  19398. /**
  19399. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19400. * @param targetPoint the position (must be in same space as current mesh) to look at
  19401. * @param yawCor optional yaw (y-axis) correction in radians
  19402. * @param pitchCor optional pitch (x-axis) correction in radians
  19403. * @param rollCor optional roll (z-axis) correction in radians
  19404. * @param space the choosen space of the target
  19405. * @returns the TransformNode.
  19406. */
  19407. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19408. if (yawCor === void 0) { yawCor = 0; }
  19409. if (pitchCor === void 0) { pitchCor = 0; }
  19410. if (rollCor === void 0) { rollCor = 0; }
  19411. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19412. var dv = TransformNode._lookAtVectorCache;
  19413. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19414. targetPoint.subtractToRef(pos, dv);
  19415. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19416. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19417. var pitch = Math.atan2(dv.y, len);
  19418. if (this.rotationQuaternion) {
  19419. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19420. }
  19421. else {
  19422. this.rotation.x = pitch + pitchCor;
  19423. this.rotation.y = yaw + yawCor;
  19424. this.rotation.z = rollCor;
  19425. }
  19426. return this;
  19427. };
  19428. /**
  19429. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19430. * This Vector3 is expressed in the World space.
  19431. */
  19432. TransformNode.prototype.getDirection = function (localAxis) {
  19433. var result = BABYLON.Vector3.Zero();
  19434. this.getDirectionToRef(localAxis, result);
  19435. return result;
  19436. };
  19437. /**
  19438. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19439. * localAxis is expressed in the mesh local space.
  19440. * result is computed in the Wordl space from the mesh World matrix.
  19441. * Returns the TransformNode.
  19442. */
  19443. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19444. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19445. return this;
  19446. };
  19447. /**
  19448. * Sets a new pivot point to the current node
  19449. * @param point defines the new pivot point to use
  19450. * @param space defines if the point is in world or local space (local by default)
  19451. * @returns the current TransformNode
  19452. */
  19453. TransformNode.prototype.setPivotPoint = function (point, space) {
  19454. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19455. if (this.getScene().getRenderId() == 0) {
  19456. this.computeWorldMatrix(true);
  19457. }
  19458. var wm = this.getWorldMatrix();
  19459. if (space == BABYLON.Space.WORLD) {
  19460. var tmat = BABYLON.Tmp.Matrix[0];
  19461. wm.invertToRef(tmat);
  19462. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19463. }
  19464. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19465. };
  19466. /**
  19467. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19468. */
  19469. TransformNode.prototype.getPivotPoint = function () {
  19470. var point = BABYLON.Vector3.Zero();
  19471. this.getPivotPointToRef(point);
  19472. return point;
  19473. };
  19474. /**
  19475. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19476. * Returns the TransformNode.
  19477. */
  19478. TransformNode.prototype.getPivotPointToRef = function (result) {
  19479. result.x = -this._pivotMatrix.m[12];
  19480. result.y = -this._pivotMatrix.m[13];
  19481. result.z = -this._pivotMatrix.m[14];
  19482. return this;
  19483. };
  19484. /**
  19485. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19486. */
  19487. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19488. var point = BABYLON.Vector3.Zero();
  19489. this.getAbsolutePivotPointToRef(point);
  19490. return point;
  19491. };
  19492. /**
  19493. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19494. * Returns the TransformNode.
  19495. */
  19496. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19497. result.x = this._pivotMatrix.m[12];
  19498. result.y = this._pivotMatrix.m[13];
  19499. result.z = this._pivotMatrix.m[14];
  19500. this.getPivotPointToRef(result);
  19501. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19502. return this;
  19503. };
  19504. /**
  19505. * Defines the passed node as the parent of the current node.
  19506. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19507. * Returns the TransformNode.
  19508. */
  19509. TransformNode.prototype.setParent = function (node) {
  19510. if (!node && !this.parent) {
  19511. return this;
  19512. }
  19513. if (!node) {
  19514. var rotation = BABYLON.Tmp.Quaternion[0];
  19515. var position = BABYLON.Tmp.Vector3[0];
  19516. var scale = BABYLON.Tmp.Vector3[1];
  19517. if (this.parent && this.parent.computeWorldMatrix) {
  19518. this.parent.computeWorldMatrix(true);
  19519. }
  19520. this.computeWorldMatrix(true);
  19521. this.getWorldMatrix().decompose(scale, rotation, position);
  19522. if (this.rotationQuaternion) {
  19523. this.rotationQuaternion.copyFrom(rotation);
  19524. }
  19525. else {
  19526. rotation.toEulerAnglesToRef(this.rotation);
  19527. }
  19528. this.scaling.x = scale.x;
  19529. this.scaling.y = scale.y;
  19530. this.scaling.z = scale.z;
  19531. this.position.x = position.x;
  19532. this.position.y = position.y;
  19533. this.position.z = position.z;
  19534. }
  19535. else {
  19536. var rotation = BABYLON.Tmp.Quaternion[0];
  19537. var position = BABYLON.Tmp.Vector3[0];
  19538. var scale = BABYLON.Tmp.Vector3[1];
  19539. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19540. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19541. this.computeWorldMatrix(true);
  19542. node.computeWorldMatrix(true);
  19543. node.getWorldMatrix().invertToRef(invParentMatrix);
  19544. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19545. diffMatrix.decompose(scale, rotation, position);
  19546. if (this.rotationQuaternion) {
  19547. this.rotationQuaternion.copyFrom(rotation);
  19548. }
  19549. else {
  19550. rotation.toEulerAnglesToRef(this.rotation);
  19551. }
  19552. this.position.x = position.x;
  19553. this.position.y = position.y;
  19554. this.position.z = position.z;
  19555. this.scaling.x = scale.x;
  19556. this.scaling.y = scale.y;
  19557. this.scaling.z = scale.z;
  19558. }
  19559. this.parent = node;
  19560. return this;
  19561. };
  19562. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19563. get: function () {
  19564. return this._nonUniformScaling;
  19565. },
  19566. enumerable: true,
  19567. configurable: true
  19568. });
  19569. /** @hidden */
  19570. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19571. if (this._nonUniformScaling === value) {
  19572. return false;
  19573. }
  19574. this._nonUniformScaling = value;
  19575. return true;
  19576. };
  19577. /**
  19578. * Attach the current TransformNode to another TransformNode associated with a bone
  19579. * @param bone Bone affecting the TransformNode
  19580. * @param affectedTransformNode TransformNode associated with the bone
  19581. */
  19582. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19583. this._transformToBoneReferal = affectedTransformNode;
  19584. this.parent = bone;
  19585. if (bone.getWorldMatrix().determinant() < 0) {
  19586. this.scalingDeterminant *= -1;
  19587. }
  19588. return this;
  19589. };
  19590. TransformNode.prototype.detachFromBone = function () {
  19591. if (!this.parent) {
  19592. return this;
  19593. }
  19594. if (this.parent.getWorldMatrix().determinant() < 0) {
  19595. this.scalingDeterminant *= -1;
  19596. }
  19597. this._transformToBoneReferal = null;
  19598. this.parent = null;
  19599. return this;
  19600. };
  19601. /**
  19602. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19603. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19604. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19605. * The passed axis is also normalized.
  19606. * Returns the TransformNode.
  19607. */
  19608. TransformNode.prototype.rotate = function (axis, amount, space) {
  19609. axis.normalize();
  19610. if (!this.rotationQuaternion) {
  19611. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19612. this.rotation = BABYLON.Vector3.Zero();
  19613. }
  19614. var rotationQuaternion;
  19615. if (!space || space === BABYLON.Space.LOCAL) {
  19616. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19617. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19618. }
  19619. else {
  19620. if (this.parent) {
  19621. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19622. invertParentWorldMatrix.invert();
  19623. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19624. }
  19625. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19626. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19627. }
  19628. return this;
  19629. };
  19630. /**
  19631. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19632. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19633. * The passed axis is also normalized.
  19634. * Returns the TransformNode.
  19635. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19636. */
  19637. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19638. axis.normalize();
  19639. if (!this.rotationQuaternion) {
  19640. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19641. this.rotation.copyFromFloats(0, 0, 0);
  19642. }
  19643. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19644. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19645. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19646. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19647. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19648. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19649. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19650. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19651. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19652. return this;
  19653. };
  19654. /**
  19655. * Translates the mesh along the axis vector for the passed distance in the given space.
  19656. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19657. * Returns the TransformNode.
  19658. */
  19659. TransformNode.prototype.translate = function (axis, distance, space) {
  19660. var displacementVector = axis.scale(distance);
  19661. if (!space || space === BABYLON.Space.LOCAL) {
  19662. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19663. this.setPositionWithLocalVector(tempV3);
  19664. }
  19665. else {
  19666. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19667. }
  19668. return this;
  19669. };
  19670. /**
  19671. * Adds a rotation step to the mesh current rotation.
  19672. * x, y, z are Euler angles expressed in radians.
  19673. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19674. * This means this rotation is made in the mesh local space only.
  19675. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19676. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19677. * ```javascript
  19678. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19679. * ```
  19680. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19681. * 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.
  19682. * Returns the TransformNode.
  19683. */
  19684. TransformNode.prototype.addRotation = function (x, y, z) {
  19685. var rotationQuaternion;
  19686. if (this.rotationQuaternion) {
  19687. rotationQuaternion = this.rotationQuaternion;
  19688. }
  19689. else {
  19690. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19691. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19692. }
  19693. var accumulation = BABYLON.Tmp.Quaternion[0];
  19694. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19695. rotationQuaternion.multiplyInPlace(accumulation);
  19696. if (!this.rotationQuaternion) {
  19697. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19698. }
  19699. return this;
  19700. };
  19701. /**
  19702. * Computes the world matrix of the node
  19703. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19704. * @returns the world matrix
  19705. */
  19706. TransformNode.prototype.computeWorldMatrix = function (force) {
  19707. if (this._isWorldMatrixFrozen) {
  19708. return this._worldMatrix;
  19709. }
  19710. if (!force && this.isSynchronized()) {
  19711. this._currentRenderId = this.getScene().getRenderId();
  19712. return this._worldMatrix;
  19713. }
  19714. this._updateCache();
  19715. this._cache.position.copyFrom(this.position);
  19716. this._cache.scaling.copyFrom(this.scaling);
  19717. this._cache.pivotMatrixUpdated = false;
  19718. this._cache.billboardMode = this.billboardMode;
  19719. this._currentRenderId = this.getScene().getRenderId();
  19720. this._childRenderId = this.getScene().getRenderId();
  19721. this._isDirty = false;
  19722. // Scaling
  19723. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19724. // Rotation
  19725. //rotate, if quaternion is set and rotation was used
  19726. if (this.rotationQuaternion) {
  19727. var len = this.rotation.length();
  19728. if (len) {
  19729. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19730. this.rotation.copyFromFloats(0, 0, 0);
  19731. }
  19732. }
  19733. if (this.rotationQuaternion) {
  19734. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19735. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19736. }
  19737. else {
  19738. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19739. this._cache.rotation.copyFrom(this.rotation);
  19740. }
  19741. // Translation
  19742. var camera = this.getScene().activeCamera;
  19743. if (this.infiniteDistance && !this.parent && camera) {
  19744. var cameraWorldMatrix = camera.getWorldMatrix();
  19745. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19746. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19747. }
  19748. else {
  19749. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19750. }
  19751. // Composing transformations
  19752. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19753. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19754. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19755. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19756. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19757. // Need to decompose each rotation here
  19758. var currentPosition = BABYLON.Tmp.Vector3[3];
  19759. if (this.parent && this.parent.getWorldMatrix) {
  19760. if (this._transformToBoneReferal) {
  19761. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19762. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19763. }
  19764. else {
  19765. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19766. }
  19767. }
  19768. else {
  19769. currentPosition.copyFrom(this.position);
  19770. }
  19771. currentPosition.subtractInPlace(camera.globalPosition);
  19772. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19773. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19774. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19775. }
  19776. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19777. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19778. }
  19779. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19780. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19781. }
  19782. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19783. }
  19784. else {
  19785. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19786. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19787. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19788. }
  19789. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19790. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19791. }
  19792. // Post multiply inverse of pivotMatrix
  19793. if (this._postMultiplyPivotMatrix) {
  19794. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19795. }
  19796. // Local world
  19797. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19798. // Parent
  19799. if (this.parent && this.parent.getWorldMatrix) {
  19800. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19801. if (this._transformToBoneReferal) {
  19802. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19803. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19804. }
  19805. else {
  19806. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19807. }
  19808. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19809. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19810. this._worldMatrix.copyFrom(this._localWorld);
  19811. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19812. }
  19813. else {
  19814. if (this._transformToBoneReferal) {
  19815. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19816. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19817. }
  19818. else {
  19819. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19820. }
  19821. }
  19822. this._markSyncedWithParent();
  19823. }
  19824. else {
  19825. this._worldMatrix.copyFrom(this._localWorld);
  19826. }
  19827. // Normal matrix
  19828. if (!this.ignoreNonUniformScaling) {
  19829. if (this.scaling.isNonUniform) {
  19830. this._updateNonUniformScalingState(true);
  19831. }
  19832. else if (this.parent && this.parent._nonUniformScaling) {
  19833. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19834. }
  19835. else {
  19836. this._updateNonUniformScalingState(false);
  19837. }
  19838. }
  19839. else {
  19840. this._updateNonUniformScalingState(false);
  19841. }
  19842. this._afterComputeWorldMatrix();
  19843. // Absolute position
  19844. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19845. // Callbacks
  19846. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19847. if (!this._poseMatrix) {
  19848. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19849. }
  19850. // Cache the determinant
  19851. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19852. return this._worldMatrix;
  19853. };
  19854. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19855. };
  19856. /**
  19857. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19858. * @param func: callback function to add
  19859. *
  19860. * Returns the TransformNode.
  19861. */
  19862. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19863. this.onAfterWorldMatrixUpdateObservable.add(func);
  19864. return this;
  19865. };
  19866. /**
  19867. * Removes a registered callback function.
  19868. * Returns the TransformNode.
  19869. */
  19870. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19871. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19872. return this;
  19873. };
  19874. /**
  19875. * Clone the current transform node
  19876. * Returns the new transform node
  19877. * @param name Name of the new clone
  19878. * @param newParent New parent for the clone
  19879. * @param doNotCloneChildren Do not clone children hierarchy
  19880. */
  19881. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19882. var _this = this;
  19883. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19884. result.name = name;
  19885. result.id = name;
  19886. if (newParent) {
  19887. result.parent = newParent;
  19888. }
  19889. if (!doNotCloneChildren) {
  19890. // Children
  19891. var directDescendants = this.getDescendants(true);
  19892. for (var index = 0; index < directDescendants.length; index++) {
  19893. var child = directDescendants[index];
  19894. if (child.clone) {
  19895. child.clone(name + "." + child.name, result);
  19896. }
  19897. }
  19898. }
  19899. return result;
  19900. };
  19901. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19902. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19903. serializationObject.type = this.getClassName();
  19904. // Parent
  19905. if (this.parent) {
  19906. serializationObject.parentId = this.parent.id;
  19907. }
  19908. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19909. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19910. }
  19911. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19912. serializationObject.isEnabled = this.isEnabled();
  19913. // Parent
  19914. if (this.parent) {
  19915. serializationObject.parentId = this.parent.id;
  19916. }
  19917. return serializationObject;
  19918. };
  19919. // Statics
  19920. /**
  19921. * Returns a new TransformNode object parsed from the source provided.
  19922. * The parameter `parsedMesh` is the source.
  19923. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19924. */
  19925. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19926. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19927. if (BABYLON.Tags) {
  19928. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19929. }
  19930. if (parsedTransformNode.localMatrix) {
  19931. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19932. }
  19933. else if (parsedTransformNode.pivotMatrix) {
  19934. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19935. }
  19936. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19937. // Parent
  19938. if (parsedTransformNode.parentId) {
  19939. transformNode._waitingParentId = parsedTransformNode.parentId;
  19940. }
  19941. return transformNode;
  19942. };
  19943. /**
  19944. * Releases resources associated with this transform node.
  19945. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19946. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19947. */
  19948. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19949. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19950. // Animations
  19951. this.getScene().stopAnimation(this);
  19952. // Remove from scene
  19953. this.getScene().removeTransformNode(this);
  19954. this.onAfterWorldMatrixUpdateObservable.clear();
  19955. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19956. };
  19957. // Statics
  19958. TransformNode.BILLBOARDMODE_NONE = 0;
  19959. TransformNode.BILLBOARDMODE_X = 1;
  19960. TransformNode.BILLBOARDMODE_Y = 2;
  19961. TransformNode.BILLBOARDMODE_Z = 4;
  19962. TransformNode.BILLBOARDMODE_ALL = 7;
  19963. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19964. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19965. __decorate([
  19966. BABYLON.serializeAsVector3("position")
  19967. ], TransformNode.prototype, "_position", void 0);
  19968. __decorate([
  19969. BABYLON.serializeAsVector3("rotation")
  19970. ], TransformNode.prototype, "_rotation", void 0);
  19971. __decorate([
  19972. BABYLON.serializeAsQuaternion("rotationQuaternion")
  19973. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19974. __decorate([
  19975. BABYLON.serializeAsVector3("scaling")
  19976. ], TransformNode.prototype, "_scaling", void 0);
  19977. __decorate([
  19978. BABYLON.serialize()
  19979. ], TransformNode.prototype, "billboardMode", void 0);
  19980. __decorate([
  19981. BABYLON.serialize()
  19982. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19983. __decorate([
  19984. BABYLON.serialize()
  19985. ], TransformNode.prototype, "infiniteDistance", void 0);
  19986. __decorate([
  19987. BABYLON.serialize()
  19988. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19989. return TransformNode;
  19990. }(BABYLON.Node));
  19991. BABYLON.TransformNode = TransformNode;
  19992. })(BABYLON || (BABYLON = {}));
  19993. //# sourceMappingURL=babylon.transformNode.js.map
  19994. var BABYLON;
  19995. (function (BABYLON) {
  19996. /** @hidden */
  19997. var _FacetDataStorage = /** @class */ (function () {
  19998. function _FacetDataStorage() {
  19999. this.facetNb = 0; // facet number
  20000. this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  20001. this.partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  20002. this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  20003. this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  20004. this.bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  20005. this.subDiv = {
  20006. max: 1,
  20007. X: 1,
  20008. Y: 1,
  20009. Z: 1
  20010. };
  20011. this.facetDepthSort = false; // is the facet depth sort to be computed
  20012. this.facetDepthSortEnabled = false; // is the facet depth sort initialized
  20013. }
  20014. return _FacetDataStorage;
  20015. }());
  20016. /**
  20017. * Class used to store all common mesh properties
  20018. */
  20019. var AbstractMesh = /** @class */ (function (_super) {
  20020. __extends(AbstractMesh, _super);
  20021. // Constructor
  20022. /**
  20023. * Creates a new AbstractMesh
  20024. * @param name defines the name of the mesh
  20025. * @param scene defines the hosting scene
  20026. */
  20027. function AbstractMesh(name, scene) {
  20028. if (scene === void 0) { scene = null; }
  20029. var _this = _super.call(this, name, scene, false) || this;
  20030. _this._facetData = new _FacetDataStorage();
  20031. /** Gets ot sets the culling strategy to use to find visible meshes */
  20032. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  20033. // Events
  20034. /**
  20035. * An event triggered when this mesh collides with another one
  20036. */
  20037. _this.onCollideObservable = new BABYLON.Observable();
  20038. /**
  20039. * An event triggered when the collision's position changes
  20040. */
  20041. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  20042. /**
  20043. * An event triggered when material is changed
  20044. */
  20045. _this.onMaterialChangedObservable = new BABYLON.Observable();
  20046. // Properties
  20047. /**
  20048. * Gets or sets the orientation for POV movement & rotation
  20049. */
  20050. _this.definedFacingForward = true;
  20051. _this._visibility = 1.0;
  20052. /** Gets or sets the alpha index used to sort transparent meshes
  20053. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  20054. */
  20055. _this.alphaIndex = Number.MAX_VALUE;
  20056. /**
  20057. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  20058. */
  20059. _this.isVisible = true;
  20060. /**
  20061. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  20062. */
  20063. _this.isPickable = true;
  20064. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  20065. _this.showSubMeshesBoundingBox = false;
  20066. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  20067. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  20068. */
  20069. _this.isBlocker = false;
  20070. /**
  20071. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  20072. */
  20073. _this.enablePointerMoveEvents = false;
  20074. /**
  20075. * Specifies the rendering group id for this mesh (0 by default)
  20076. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  20077. */
  20078. _this.renderingGroupId = 0;
  20079. _this._receiveShadows = false;
  20080. /** Defines color to use when rendering outline */
  20081. _this.outlineColor = BABYLON.Color3.Red();
  20082. /** Define width to use when rendering outline */
  20083. _this.outlineWidth = 0.02;
  20084. /** Defines color to use when rendering overlay */
  20085. _this.overlayColor = BABYLON.Color3.Red();
  20086. /** Defines alpha to use when rendering overlay */
  20087. _this.overlayAlpha = 0.5;
  20088. _this._hasVertexAlpha = false;
  20089. _this._useVertexColors = true;
  20090. _this._computeBonesUsingShaders = true;
  20091. _this._numBoneInfluencers = 4;
  20092. _this._applyFog = true;
  20093. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  20094. _this.useOctreeForRenderingSelection = true;
  20095. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  20096. _this.useOctreeForPicking = true;
  20097. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  20098. _this.useOctreeForCollisions = true;
  20099. _this._layerMask = 0x0FFFFFFF;
  20100. /**
  20101. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  20102. */
  20103. _this.alwaysSelectAsActiveMesh = false;
  20104. /**
  20105. * Gets or sets the current action manager
  20106. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  20107. */
  20108. _this.actionManager = null;
  20109. // Collisions
  20110. _this._checkCollisions = false;
  20111. _this._collisionMask = -1;
  20112. _this._collisionGroup = -1;
  20113. /**
  20114. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  20115. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20116. */
  20117. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  20118. /**
  20119. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  20120. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20121. */
  20122. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  20123. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20124. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20125. // Edges
  20126. /**
  20127. * Defines edge width used when edgesRenderer is enabled
  20128. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20129. */
  20130. _this.edgesWidth = 1;
  20131. /**
  20132. * Defines edge color used when edgesRenderer is enabled
  20133. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20134. */
  20135. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  20136. // Cache
  20137. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  20138. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  20139. /** @hidden */
  20140. _this._renderId = 0;
  20141. /** @hidden */
  20142. _this._intersectionsInProgress = new Array();
  20143. /** @hidden */
  20144. _this._unIndexed = false;
  20145. /** @hidden */
  20146. _this._lightSources = new Array();
  20147. /**
  20148. * An event triggered when the mesh is rebuilt.
  20149. */
  20150. _this.onRebuildObservable = new BABYLON.Observable();
  20151. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  20152. if (collidedMesh === void 0) { collidedMesh = null; }
  20153. //TODO move this to the collision coordinator!
  20154. if (_this.getScene().workerCollisions)
  20155. newPosition.multiplyInPlace(_this._collider._radius);
  20156. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  20157. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  20158. _this.position.addInPlace(_this._diffPositionForCollisions);
  20159. }
  20160. if (collidedMesh) {
  20161. _this.onCollideObservable.notifyObservers(collidedMesh);
  20162. }
  20163. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  20164. };
  20165. _this.getScene().addMesh(_this);
  20166. _this._resyncLightSources();
  20167. return _this;
  20168. }
  20169. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  20170. /**
  20171. * No billboard
  20172. */
  20173. get: function () {
  20174. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  20175. },
  20176. enumerable: true,
  20177. configurable: true
  20178. });
  20179. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  20180. /** Billboard on X axis */
  20181. get: function () {
  20182. return BABYLON.TransformNode.BILLBOARDMODE_X;
  20183. },
  20184. enumerable: true,
  20185. configurable: true
  20186. });
  20187. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  20188. /** Billboard on Y axis */
  20189. get: function () {
  20190. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  20191. },
  20192. enumerable: true,
  20193. configurable: true
  20194. });
  20195. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  20196. /** Billboard on Z axis */
  20197. get: function () {
  20198. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  20199. },
  20200. enumerable: true,
  20201. configurable: true
  20202. });
  20203. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  20204. /** Billboard on all axes */
  20205. get: function () {
  20206. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  20207. },
  20208. enumerable: true,
  20209. configurable: true
  20210. });
  20211. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  20212. /**
  20213. * Gets the number of facets in the mesh
  20214. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20215. */
  20216. get: function () {
  20217. return this._facetData.facetNb;
  20218. },
  20219. enumerable: true,
  20220. configurable: true
  20221. });
  20222. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  20223. /**
  20224. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  20225. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20226. */
  20227. get: function () {
  20228. return this._facetData.partitioningSubdivisions;
  20229. },
  20230. set: function (nb) {
  20231. this._facetData.partitioningSubdivisions = nb;
  20232. },
  20233. enumerable: true,
  20234. configurable: true
  20235. });
  20236. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  20237. /**
  20238. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  20239. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  20240. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20241. */
  20242. get: function () {
  20243. return this._facetData.partitioningBBoxRatio;
  20244. },
  20245. set: function (ratio) {
  20246. this._facetData.partitioningBBoxRatio = ratio;
  20247. },
  20248. enumerable: true,
  20249. configurable: true
  20250. });
  20251. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  20252. /**
  20253. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  20254. * Works only for updatable meshes.
  20255. * Doesn't work with multi-materials
  20256. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20257. */
  20258. get: function () {
  20259. return this._facetData.facetDepthSort;
  20260. },
  20261. set: function (sort) {
  20262. this._facetData.facetDepthSort = sort;
  20263. },
  20264. enumerable: true,
  20265. configurable: true
  20266. });
  20267. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  20268. /**
  20269. * The location (Vector3) where the facet depth sort must be computed from.
  20270. * By default, the active camera position.
  20271. * Used only when facet depth sort is enabled
  20272. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20273. */
  20274. get: function () {
  20275. return this._facetData.facetDepthSortFrom;
  20276. },
  20277. set: function (location) {
  20278. this._facetData.facetDepthSortFrom = location;
  20279. },
  20280. enumerable: true,
  20281. configurable: true
  20282. });
  20283. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  20284. /**
  20285. * gets a boolean indicating if facetData is enabled
  20286. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20287. */
  20288. get: function () {
  20289. return this._facetData.facetDataEnabled;
  20290. },
  20291. enumerable: true,
  20292. configurable: true
  20293. });
  20294. /** @hidden */
  20295. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  20296. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  20297. return false;
  20298. }
  20299. this._markSubMeshesAsMiscDirty();
  20300. return true;
  20301. };
  20302. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  20303. /** Set a function to call when this mesh collides with another one */
  20304. set: function (callback) {
  20305. if (this._onCollideObserver) {
  20306. this.onCollideObservable.remove(this._onCollideObserver);
  20307. }
  20308. this._onCollideObserver = this.onCollideObservable.add(callback);
  20309. },
  20310. enumerable: true,
  20311. configurable: true
  20312. });
  20313. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  20314. /** Set a function to call when the collision's position changes */
  20315. set: function (callback) {
  20316. if (this._onCollisionPositionChangeObserver) {
  20317. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  20318. }
  20319. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  20320. },
  20321. enumerable: true,
  20322. configurable: true
  20323. });
  20324. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20325. /**
  20326. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20327. */
  20328. get: function () {
  20329. return this._visibility;
  20330. },
  20331. /**
  20332. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20333. */
  20334. set: function (value) {
  20335. if (this._visibility === value) {
  20336. return;
  20337. }
  20338. this._visibility = value;
  20339. this._markSubMeshesAsMiscDirty();
  20340. },
  20341. enumerable: true,
  20342. configurable: true
  20343. });
  20344. Object.defineProperty(AbstractMesh.prototype, "material", {
  20345. /** Gets or sets current material */
  20346. get: function () {
  20347. return this._material;
  20348. },
  20349. set: function (value) {
  20350. if (this._material === value) {
  20351. return;
  20352. }
  20353. this._material = value;
  20354. if (this.onMaterialChangedObservable.hasObservers) {
  20355. this.onMaterialChangedObservable.notifyObservers(this);
  20356. }
  20357. if (!this.subMeshes) {
  20358. return;
  20359. }
  20360. this._unBindEffect();
  20361. },
  20362. enumerable: true,
  20363. configurable: true
  20364. });
  20365. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20366. /**
  20367. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20368. * @see http://doc.babylonjs.com/babylon101/shadows
  20369. */
  20370. get: function () {
  20371. return this._receiveShadows;
  20372. },
  20373. set: function (value) {
  20374. if (this._receiveShadows === value) {
  20375. return;
  20376. }
  20377. this._receiveShadows = value;
  20378. this._markSubMeshesAsLightDirty();
  20379. },
  20380. enumerable: true,
  20381. configurable: true
  20382. });
  20383. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20384. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20385. get: function () {
  20386. return this._hasVertexAlpha;
  20387. },
  20388. set: function (value) {
  20389. if (this._hasVertexAlpha === value) {
  20390. return;
  20391. }
  20392. this._hasVertexAlpha = value;
  20393. this._markSubMeshesAsAttributesDirty();
  20394. this._markSubMeshesAsMiscDirty();
  20395. },
  20396. enumerable: true,
  20397. configurable: true
  20398. });
  20399. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20400. /** 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) */
  20401. get: function () {
  20402. return this._useVertexColors;
  20403. },
  20404. set: function (value) {
  20405. if (this._useVertexColors === value) {
  20406. return;
  20407. }
  20408. this._useVertexColors = value;
  20409. this._markSubMeshesAsAttributesDirty();
  20410. },
  20411. enumerable: true,
  20412. configurable: true
  20413. });
  20414. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20415. /**
  20416. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20417. */
  20418. get: function () {
  20419. return this._computeBonesUsingShaders;
  20420. },
  20421. set: function (value) {
  20422. if (this._computeBonesUsingShaders === value) {
  20423. return;
  20424. }
  20425. this._computeBonesUsingShaders = value;
  20426. this._markSubMeshesAsAttributesDirty();
  20427. },
  20428. enumerable: true,
  20429. configurable: true
  20430. });
  20431. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20432. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20433. get: function () {
  20434. return this._numBoneInfluencers;
  20435. },
  20436. set: function (value) {
  20437. if (this._numBoneInfluencers === value) {
  20438. return;
  20439. }
  20440. this._numBoneInfluencers = value;
  20441. this._markSubMeshesAsAttributesDirty();
  20442. },
  20443. enumerable: true,
  20444. configurable: true
  20445. });
  20446. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20447. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20448. get: function () {
  20449. return this._applyFog;
  20450. },
  20451. set: function (value) {
  20452. if (this._applyFog === value) {
  20453. return;
  20454. }
  20455. this._applyFog = value;
  20456. this._markSubMeshesAsMiscDirty();
  20457. },
  20458. enumerable: true,
  20459. configurable: true
  20460. });
  20461. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20462. /**
  20463. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20464. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20465. */
  20466. get: function () {
  20467. return this._layerMask;
  20468. },
  20469. set: function (value) {
  20470. if (value === this._layerMask) {
  20471. return;
  20472. }
  20473. this._layerMask = value;
  20474. this._resyncLightSources();
  20475. },
  20476. enumerable: true,
  20477. configurable: true
  20478. });
  20479. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20480. /**
  20481. * Gets or sets a collision mask used to mask collisions (default is -1).
  20482. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20483. */
  20484. get: function () {
  20485. return this._collisionMask;
  20486. },
  20487. set: function (mask) {
  20488. this._collisionMask = !isNaN(mask) ? mask : -1;
  20489. },
  20490. enumerable: true,
  20491. configurable: true
  20492. });
  20493. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20494. /**
  20495. * Gets or sets the current collision group mask (-1 by default).
  20496. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20497. */
  20498. get: function () {
  20499. return this._collisionGroup;
  20500. },
  20501. set: function (mask) {
  20502. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20503. },
  20504. enumerable: true,
  20505. configurable: true
  20506. });
  20507. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20508. /** @hidden */
  20509. get: function () {
  20510. return null;
  20511. },
  20512. enumerable: true,
  20513. configurable: true
  20514. });
  20515. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20516. get: function () {
  20517. return this._skeleton;
  20518. },
  20519. /**
  20520. * Gets or sets a skeleton to apply skining transformations
  20521. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20522. */
  20523. set: function (value) {
  20524. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20525. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20526. }
  20527. if (value && value.needInitialSkinMatrix) {
  20528. value._registerMeshWithPoseMatrix(this);
  20529. }
  20530. this._skeleton = value;
  20531. if (!this._skeleton) {
  20532. this._bonesTransformMatrices = null;
  20533. }
  20534. this._markSubMeshesAsAttributesDirty();
  20535. },
  20536. enumerable: true,
  20537. configurable: true
  20538. });
  20539. /**
  20540. * Returns the string "AbstractMesh"
  20541. * @returns "AbstractMesh"
  20542. */
  20543. AbstractMesh.prototype.getClassName = function () {
  20544. return "AbstractMesh";
  20545. };
  20546. /**
  20547. * Gets a string representation of the current mesh
  20548. * @param fullDetails defines a boolean indicating if full details must be included
  20549. * @returns a string representation of the current mesh
  20550. */
  20551. AbstractMesh.prototype.toString = function (fullDetails) {
  20552. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20553. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20554. if (this._skeleton) {
  20555. ret += ", skeleton: " + this._skeleton.name;
  20556. }
  20557. if (fullDetails) {
  20558. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20559. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20560. }
  20561. return ret;
  20562. };
  20563. /** @hidden */
  20564. AbstractMesh.prototype._rebuild = function () {
  20565. this.onRebuildObservable.notifyObservers(this);
  20566. if (this._occlusionQuery) {
  20567. this._occlusionQuery = null;
  20568. }
  20569. if (!this.subMeshes) {
  20570. return;
  20571. }
  20572. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20573. var subMesh = _a[_i];
  20574. subMesh._rebuild();
  20575. }
  20576. };
  20577. /** @hidden */
  20578. AbstractMesh.prototype._resyncLightSources = function () {
  20579. this._lightSources.length = 0;
  20580. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20581. var light = _a[_i];
  20582. if (!light.isEnabled()) {
  20583. continue;
  20584. }
  20585. if (light.canAffectMesh(this)) {
  20586. this._lightSources.push(light);
  20587. }
  20588. }
  20589. this._markSubMeshesAsLightDirty();
  20590. };
  20591. /** @hidden */
  20592. AbstractMesh.prototype._resyncLighSource = function (light) {
  20593. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20594. var index = this._lightSources.indexOf(light);
  20595. if (index === -1) {
  20596. if (!isIn) {
  20597. return;
  20598. }
  20599. this._lightSources.push(light);
  20600. }
  20601. else {
  20602. if (isIn) {
  20603. return;
  20604. }
  20605. this._lightSources.splice(index, 1);
  20606. }
  20607. this._markSubMeshesAsLightDirty();
  20608. };
  20609. /** @hidden */
  20610. AbstractMesh.prototype._unBindEffect = function () {
  20611. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20612. var subMesh = _a[_i];
  20613. subMesh.setEffect(null);
  20614. }
  20615. };
  20616. /** @hidden */
  20617. AbstractMesh.prototype._removeLightSource = function (light) {
  20618. var index = this._lightSources.indexOf(light);
  20619. if (index === -1) {
  20620. return;
  20621. }
  20622. this._lightSources.splice(index, 1);
  20623. this._markSubMeshesAsLightDirty();
  20624. };
  20625. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20626. if (!this.subMeshes) {
  20627. return;
  20628. }
  20629. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20630. var subMesh = _a[_i];
  20631. if (subMesh._materialDefines) {
  20632. func(subMesh._materialDefines);
  20633. }
  20634. }
  20635. };
  20636. /** @hidden */
  20637. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20638. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20639. };
  20640. /** @hidden */
  20641. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20642. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20643. };
  20644. /** @hidden */
  20645. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20646. if (!this.subMeshes) {
  20647. return;
  20648. }
  20649. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20650. var subMesh = _a[_i];
  20651. var material = subMesh.getMaterial();
  20652. if (material) {
  20653. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20654. }
  20655. }
  20656. };
  20657. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20658. /**
  20659. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20660. */
  20661. get: function () {
  20662. return this._scaling;
  20663. },
  20664. set: function (newScaling) {
  20665. this._scaling = newScaling;
  20666. if (this.physicsImpostor) {
  20667. this.physicsImpostor.forceUpdate();
  20668. }
  20669. },
  20670. enumerable: true,
  20671. configurable: true
  20672. });
  20673. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20674. // Methods
  20675. /**
  20676. * Returns true if the mesh is blocked. Implemented by child classes
  20677. */
  20678. get: function () {
  20679. return false;
  20680. },
  20681. enumerable: true,
  20682. configurable: true
  20683. });
  20684. /**
  20685. * Returns the mesh itself by default. Implemented by child classes
  20686. * @param camera defines the camera to use to pick the right LOD level
  20687. * @returns the currentAbstractMesh
  20688. */
  20689. AbstractMesh.prototype.getLOD = function (camera) {
  20690. return this;
  20691. };
  20692. /**
  20693. * Returns 0 by default. Implemented by child classes
  20694. * @returns an integer
  20695. */
  20696. AbstractMesh.prototype.getTotalVertices = function () {
  20697. return 0;
  20698. };
  20699. /**
  20700. * Returns null by default. Implemented by child classes
  20701. * @returns null
  20702. */
  20703. AbstractMesh.prototype.getIndices = function () {
  20704. return null;
  20705. };
  20706. /**
  20707. * Returns the array of the requested vertex data kind. Implemented by child classes
  20708. * @param kind defines the vertex data kind to use
  20709. * @returns null
  20710. */
  20711. AbstractMesh.prototype.getVerticesData = function (kind) {
  20712. return null;
  20713. };
  20714. /**
  20715. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20716. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20717. * Note that a new underlying VertexBuffer object is created each call.
  20718. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20719. * @param kind defines vertex data kind:
  20720. * * BABYLON.VertexBuffer.PositionKind
  20721. * * BABYLON.VertexBuffer.UVKind
  20722. * * BABYLON.VertexBuffer.UV2Kind
  20723. * * BABYLON.VertexBuffer.UV3Kind
  20724. * * BABYLON.VertexBuffer.UV4Kind
  20725. * * BABYLON.VertexBuffer.UV5Kind
  20726. * * BABYLON.VertexBuffer.UV6Kind
  20727. * * BABYLON.VertexBuffer.ColorKind
  20728. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20729. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20730. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20731. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20732. * @param data defines the data source
  20733. * @param updatable defines if the data must be flagged as updatable (or static)
  20734. * @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
  20735. * @returns the current mesh
  20736. */
  20737. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20738. return this;
  20739. };
  20740. /**
  20741. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20742. * If the mesh has no geometry, it is simply returned as it is.
  20743. * @param kind defines vertex data kind:
  20744. * * BABYLON.VertexBuffer.PositionKind
  20745. * * BABYLON.VertexBuffer.UVKind
  20746. * * BABYLON.VertexBuffer.UV2Kind
  20747. * * BABYLON.VertexBuffer.UV3Kind
  20748. * * BABYLON.VertexBuffer.UV4Kind
  20749. * * BABYLON.VertexBuffer.UV5Kind
  20750. * * BABYLON.VertexBuffer.UV6Kind
  20751. * * BABYLON.VertexBuffer.ColorKind
  20752. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20753. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20754. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20755. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20756. * @param data defines the data source
  20757. * @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
  20758. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20759. * @returns the current mesh
  20760. */
  20761. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20762. return this;
  20763. };
  20764. /**
  20765. * Sets the mesh indices,
  20766. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20767. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20768. * @param totalVertices Defines the total number of vertices
  20769. * @returns the current mesh
  20770. */
  20771. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20772. return this;
  20773. };
  20774. /**
  20775. * Gets a boolean indicating if specific vertex data is present
  20776. * @param kind defines the vertex data kind to use
  20777. * @returns true is data kind is present
  20778. */
  20779. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20780. return false;
  20781. };
  20782. /**
  20783. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20784. * @returns a BoundingInfo
  20785. */
  20786. AbstractMesh.prototype.getBoundingInfo = function () {
  20787. if (this._masterMesh) {
  20788. return this._masterMesh.getBoundingInfo();
  20789. }
  20790. if (!this._boundingInfo) {
  20791. // this._boundingInfo is being created here
  20792. this._updateBoundingInfo();
  20793. }
  20794. // cannot be null.
  20795. return this._boundingInfo;
  20796. };
  20797. /**
  20798. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20799. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20800. * @returns the current mesh
  20801. */
  20802. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20803. if (includeDescendants === void 0) { includeDescendants = true; }
  20804. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20805. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20806. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20807. if (maxDimension === 0) {
  20808. return this;
  20809. }
  20810. var scale = 1 / maxDimension;
  20811. this.scaling.scaleInPlace(scale);
  20812. return this;
  20813. };
  20814. /**
  20815. * Overwrite the current bounding info
  20816. * @param boundingInfo defines the new bounding info
  20817. * @returns the current mesh
  20818. */
  20819. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20820. this._boundingInfo = boundingInfo;
  20821. return this;
  20822. };
  20823. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20824. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20825. get: function () {
  20826. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20827. },
  20828. enumerable: true,
  20829. configurable: true
  20830. });
  20831. /** @hidden */
  20832. AbstractMesh.prototype._preActivate = function () {
  20833. };
  20834. /** @hidden */
  20835. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20836. };
  20837. /** @hidden */
  20838. AbstractMesh.prototype._activate = function (renderId) {
  20839. this._renderId = renderId;
  20840. };
  20841. /**
  20842. * Gets the current world matrix
  20843. * @returns a Matrix
  20844. */
  20845. AbstractMesh.prototype.getWorldMatrix = function () {
  20846. if (this._masterMesh) {
  20847. return this._masterMesh.getWorldMatrix();
  20848. }
  20849. return _super.prototype.getWorldMatrix.call(this);
  20850. };
  20851. /** @hidden */
  20852. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20853. if (this._masterMesh) {
  20854. return this._masterMesh._getWorldMatrixDeterminant();
  20855. }
  20856. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20857. };
  20858. // ================================== Point of View Movement =================================
  20859. /**
  20860. * Perform relative position change from the point of view of behind the front of the mesh.
  20861. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20862. * Supports definition of mesh facing forward or backward
  20863. * @param amountRight defines the distance on the right axis
  20864. * @param amountUp defines the distance on the up axis
  20865. * @param amountForward defines the distance on the forward axis
  20866. * @returns the current mesh
  20867. */
  20868. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20869. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20870. return this;
  20871. };
  20872. /**
  20873. * Calculate relative position change from the point of view of behind the front of the mesh.
  20874. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20875. * Supports definition of mesh facing forward or backward
  20876. * @param amountRight defines the distance on the right axis
  20877. * @param amountUp defines the distance on the up axis
  20878. * @param amountForward defines the distance on the forward axis
  20879. * @returns the new displacement vector
  20880. */
  20881. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20882. var rotMatrix = new BABYLON.Matrix();
  20883. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20884. rotQuaternion.toRotationMatrix(rotMatrix);
  20885. var translationDelta = BABYLON.Vector3.Zero();
  20886. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20887. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20888. return translationDelta;
  20889. };
  20890. // ================================== Point of View Rotation =================================
  20891. /**
  20892. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20893. * Supports definition of mesh facing forward or backward
  20894. * @param flipBack defines the flip
  20895. * @param twirlClockwise defines the twirl
  20896. * @param tiltRight defines the tilt
  20897. * @returns the current mesh
  20898. */
  20899. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20900. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20901. return this;
  20902. };
  20903. /**
  20904. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20905. * Supports definition of mesh facing forward or backward.
  20906. * @param flipBack defines the flip
  20907. * @param twirlClockwise defines the twirl
  20908. * @param tiltRight defines the tilt
  20909. * @returns the new rotation vector
  20910. */
  20911. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20912. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20913. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20914. };
  20915. /**
  20916. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20917. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20918. * @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
  20919. * @returns the new bounding vectors
  20920. */
  20921. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20922. if (includeDescendants === void 0) { includeDescendants = true; }
  20923. if (predicate === void 0) { predicate = null; }
  20924. // Ensures that all world matrix will be recomputed.
  20925. this.getScene().incrementRenderId();
  20926. this.computeWorldMatrix(true);
  20927. var min;
  20928. var max;
  20929. var boundingInfo = this.getBoundingInfo();
  20930. if (!this.subMeshes) {
  20931. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20932. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20933. }
  20934. else {
  20935. min = boundingInfo.boundingBox.minimumWorld;
  20936. max = boundingInfo.boundingBox.maximumWorld;
  20937. }
  20938. if (includeDescendants) {
  20939. var descendants = this.getDescendants(false);
  20940. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20941. var descendant = descendants_1[_i];
  20942. var childMesh = descendant;
  20943. childMesh.computeWorldMatrix(true);
  20944. // Filters meshes based on custom predicate function.
  20945. if (predicate && !predicate(childMesh)) {
  20946. continue;
  20947. }
  20948. //make sure we have the needed params to get mix and max
  20949. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20950. continue;
  20951. }
  20952. var childBoundingInfo = childMesh.getBoundingInfo();
  20953. var boundingBox = childBoundingInfo.boundingBox;
  20954. var minBox = boundingBox.minimumWorld;
  20955. var maxBox = boundingBox.maximumWorld;
  20956. BABYLON.Tools.CheckExtends(minBox, min, max);
  20957. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20958. }
  20959. }
  20960. return {
  20961. min: min,
  20962. max: max
  20963. };
  20964. };
  20965. /** @hidden */
  20966. AbstractMesh.prototype._updateBoundingInfo = function () {
  20967. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20968. this._boundingInfo.update(this.worldMatrixFromCache);
  20969. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20970. return this;
  20971. };
  20972. /** @hidden */
  20973. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20974. if (!this.subMeshes) {
  20975. return this;
  20976. }
  20977. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20978. var subMesh = this.subMeshes[subIndex];
  20979. if (!subMesh.IsGlobal) {
  20980. subMesh.updateBoundingInfo(matrix);
  20981. }
  20982. }
  20983. return this;
  20984. };
  20985. /** @hidden */
  20986. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20987. // Bounding info
  20988. this._updateBoundingInfo();
  20989. };
  20990. /**
  20991. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20992. * A mesh is in the frustum if its bounding box intersects the frustum
  20993. * @param frustumPlanes defines the frustum to test
  20994. * @returns true if the mesh is in the frustum planes
  20995. */
  20996. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20997. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20998. };
  20999. /**
  21000. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  21001. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  21002. * @param frustumPlanes defines the frustum to test
  21003. * @returns true if the mesh is completely in the frustum planes
  21004. */
  21005. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21006. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  21007. };
  21008. /**
  21009. * True if the mesh intersects another mesh or a SolidParticle object
  21010. * @param mesh defines a target mesh or SolidParticle to test
  21011. * @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)
  21012. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  21013. * @returns true if there is an intersection
  21014. */
  21015. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  21016. if (precise === void 0) { precise = false; }
  21017. if (!this._boundingInfo || !mesh._boundingInfo) {
  21018. return false;
  21019. }
  21020. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  21021. return true;
  21022. }
  21023. if (includeDescendants) {
  21024. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  21025. var child = _a[_i];
  21026. if (child.intersectsMesh(mesh, precise, true)) {
  21027. return true;
  21028. }
  21029. }
  21030. }
  21031. return false;
  21032. };
  21033. /**
  21034. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  21035. * @param point defines the point to test
  21036. * @returns true if there is an intersection
  21037. */
  21038. AbstractMesh.prototype.intersectsPoint = function (point) {
  21039. if (!this._boundingInfo) {
  21040. return false;
  21041. }
  21042. return this._boundingInfo.intersectsPoint(point);
  21043. };
  21044. /**
  21045. * Gets the position of the current mesh in camera space
  21046. * @param camera defines the camera to use
  21047. * @returns a position
  21048. */
  21049. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  21050. if (camera === void 0) { camera = null; }
  21051. if (!camera) {
  21052. camera = this.getScene().activeCamera;
  21053. }
  21054. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  21055. };
  21056. /**
  21057. * Returns the distance from the mesh to the active camera
  21058. * @param camera defines the camera to use
  21059. * @returns the distance
  21060. */
  21061. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  21062. if (camera === void 0) { camera = null; }
  21063. if (!camera) {
  21064. camera = this.getScene().activeCamera;
  21065. }
  21066. return this.absolutePosition.subtract(camera.position).length();
  21067. };
  21068. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  21069. // Collisions
  21070. /**
  21071. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  21072. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21073. */
  21074. get: function () {
  21075. return this._checkCollisions;
  21076. },
  21077. set: function (collisionEnabled) {
  21078. this._checkCollisions = collisionEnabled;
  21079. if (this.getScene().workerCollisions) {
  21080. this.getScene().collisionCoordinator.onMeshUpdated(this);
  21081. }
  21082. },
  21083. enumerable: true,
  21084. configurable: true
  21085. });
  21086. Object.defineProperty(AbstractMesh.prototype, "collider", {
  21087. /**
  21088. * Gets Collider object used to compute collisions (not physics)
  21089. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21090. */
  21091. get: function () {
  21092. return this._collider;
  21093. },
  21094. enumerable: true,
  21095. configurable: true
  21096. });
  21097. /**
  21098. * Move the mesh using collision engine
  21099. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21100. * @param displacement defines the requested displacement vector
  21101. * @returns the current mesh
  21102. */
  21103. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  21104. var globalPosition = this.getAbsolutePosition();
  21105. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  21106. if (!this._collider) {
  21107. this._collider = new BABYLON.Collider();
  21108. }
  21109. this._collider._radius = this.ellipsoid;
  21110. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  21111. return this;
  21112. };
  21113. // Collisions
  21114. /** @hidden */
  21115. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  21116. this._generatePointsArray();
  21117. if (!this._positions) {
  21118. return this;
  21119. }
  21120. // Transformation
  21121. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  21122. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  21123. subMesh._lastColliderWorldVertices = [];
  21124. subMesh._trianglePlanes = [];
  21125. var start = subMesh.verticesStart;
  21126. var end = (subMesh.verticesStart + subMesh.verticesCount);
  21127. for (var i = start; i < end; i++) {
  21128. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  21129. }
  21130. }
  21131. // Collide
  21132. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  21133. if (collider.collisionFound) {
  21134. collider.collidedMesh = this;
  21135. }
  21136. return this;
  21137. };
  21138. /** @hidden */
  21139. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  21140. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  21141. var len = subMeshes.length;
  21142. for (var index = 0; index < len; index++) {
  21143. var subMesh = subMeshes.data[index];
  21144. // Bounding test
  21145. if (len > 1 && !subMesh._checkCollision(collider))
  21146. continue;
  21147. this._collideForSubMesh(subMesh, transformMatrix, collider);
  21148. }
  21149. return this;
  21150. };
  21151. /** @hidden */
  21152. AbstractMesh.prototype._checkCollision = function (collider) {
  21153. // Bounding box test
  21154. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  21155. return this;
  21156. // Transformation matrix
  21157. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  21158. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  21159. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  21160. return this;
  21161. };
  21162. // Picking
  21163. /** @hidden */
  21164. AbstractMesh.prototype._generatePointsArray = function () {
  21165. return false;
  21166. };
  21167. /**
  21168. * Checks if the passed Ray intersects with the mesh
  21169. * @param ray defines the ray to use
  21170. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  21171. * @returns the picking info
  21172. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  21173. */
  21174. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  21175. var pickingInfo = new BABYLON.PickingInfo();
  21176. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  21177. return pickingInfo;
  21178. }
  21179. if (!this._generatePointsArray()) {
  21180. return pickingInfo;
  21181. }
  21182. var intersectInfo = null;
  21183. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  21184. var len = subMeshes.length;
  21185. for (var index = 0; index < len; index++) {
  21186. var subMesh = subMeshes.data[index];
  21187. // Bounding test
  21188. if (len > 1 && !subMesh.canIntersects(ray))
  21189. continue;
  21190. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21191. if (currentIntersectInfo) {
  21192. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21193. intersectInfo = currentIntersectInfo;
  21194. intersectInfo.subMeshId = index;
  21195. if (fastCheck) {
  21196. break;
  21197. }
  21198. }
  21199. }
  21200. }
  21201. if (intersectInfo) {
  21202. // Get picked point
  21203. var world = this.getWorldMatrix();
  21204. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21205. var direction = ray.direction.clone();
  21206. direction = direction.scale(intersectInfo.distance);
  21207. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21208. var pickedPoint = worldOrigin.add(worldDirection);
  21209. // Return result
  21210. pickingInfo.hit = true;
  21211. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21212. pickingInfo.pickedPoint = pickedPoint;
  21213. pickingInfo.pickedMesh = this;
  21214. pickingInfo.bu = intersectInfo.bu || 0;
  21215. pickingInfo.bv = intersectInfo.bv || 0;
  21216. pickingInfo.faceId = intersectInfo.faceId;
  21217. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21218. return pickingInfo;
  21219. }
  21220. return pickingInfo;
  21221. };
  21222. /**
  21223. * Clones the current mesh
  21224. * @param name defines the mesh name
  21225. * @param newParent defines the new mesh parent
  21226. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21227. * @returns the new mesh
  21228. */
  21229. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21230. return null;
  21231. };
  21232. /**
  21233. * Disposes all the submeshes of the current meshnp
  21234. * @returns the current mesh
  21235. */
  21236. AbstractMesh.prototype.releaseSubMeshes = function () {
  21237. if (this.subMeshes) {
  21238. while (this.subMeshes.length) {
  21239. this.subMeshes[0].dispose();
  21240. }
  21241. }
  21242. else {
  21243. this.subMeshes = new Array();
  21244. }
  21245. return this;
  21246. };
  21247. /**
  21248. * Releases resources associated with this abstract mesh.
  21249. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21250. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21251. */
  21252. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21253. var _this = this;
  21254. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21255. var index;
  21256. // Smart Array Retainers.
  21257. this.getScene().freeActiveMeshes();
  21258. this.getScene().freeRenderingGroups();
  21259. // Action manager
  21260. if (this.actionManager !== undefined && this.actionManager !== null) {
  21261. this.actionManager.dispose();
  21262. this.actionManager = null;
  21263. }
  21264. // Skeleton
  21265. this._skeleton = null;
  21266. // Intersections in progress
  21267. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21268. var other = this._intersectionsInProgress[index];
  21269. var pos = other._intersectionsInProgress.indexOf(this);
  21270. other._intersectionsInProgress.splice(pos, 1);
  21271. }
  21272. this._intersectionsInProgress = [];
  21273. // Lights
  21274. var lights = this.getScene().lights;
  21275. lights.forEach(function (light) {
  21276. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21277. if (meshIndex !== -1) {
  21278. light.includedOnlyMeshes.splice(meshIndex, 1);
  21279. }
  21280. meshIndex = light.excludedMeshes.indexOf(_this);
  21281. if (meshIndex !== -1) {
  21282. light.excludedMeshes.splice(meshIndex, 1);
  21283. }
  21284. // Shadow generators
  21285. var generator = light.getShadowGenerator();
  21286. if (generator) {
  21287. var shadowMap = generator.getShadowMap();
  21288. if (shadowMap && shadowMap.renderList) {
  21289. meshIndex = shadowMap.renderList.indexOf(_this);
  21290. if (meshIndex !== -1) {
  21291. shadowMap.renderList.splice(meshIndex, 1);
  21292. }
  21293. }
  21294. }
  21295. });
  21296. // SubMeshes
  21297. if (this.getClassName() !== "InstancedMesh") {
  21298. this.releaseSubMeshes();
  21299. }
  21300. // Query
  21301. var engine = this.getScene().getEngine();
  21302. if (this._occlusionQuery) {
  21303. this.isOcclusionQueryInProgress = false;
  21304. engine.deleteQuery(this._occlusionQuery);
  21305. this._occlusionQuery = null;
  21306. }
  21307. // Engine
  21308. engine.wipeCaches();
  21309. // Remove from scene
  21310. this.getScene().removeMesh(this);
  21311. if (disposeMaterialAndTextures) {
  21312. if (this.material) {
  21313. this.material.dispose(false, true);
  21314. }
  21315. }
  21316. if (!doNotRecurse) {
  21317. // Particles
  21318. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21319. if (this.getScene().particleSystems[index].emitter === this) {
  21320. this.getScene().particleSystems[index].dispose();
  21321. index--;
  21322. }
  21323. }
  21324. }
  21325. // facet data
  21326. if (this._facetData.facetDataEnabled) {
  21327. this.disableFacetData();
  21328. }
  21329. this.onAfterWorldMatrixUpdateObservable.clear();
  21330. this.onCollideObservable.clear();
  21331. this.onCollisionPositionChangeObservable.clear();
  21332. this.onRebuildObservable.clear();
  21333. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21334. };
  21335. /**
  21336. * Adds the passed mesh as a child to the current mesh
  21337. * @param mesh defines the child mesh
  21338. * @returns the current mesh
  21339. */
  21340. AbstractMesh.prototype.addChild = function (mesh) {
  21341. mesh.setParent(this);
  21342. return this;
  21343. };
  21344. /**
  21345. * Removes the passed mesh from the current mesh children list
  21346. * @param mesh defines the child mesh
  21347. * @returns the current mesh
  21348. */
  21349. AbstractMesh.prototype.removeChild = function (mesh) {
  21350. mesh.setParent(null);
  21351. return this;
  21352. };
  21353. // Facet data
  21354. /** @hidden */
  21355. AbstractMesh.prototype._initFacetData = function () {
  21356. var data = this._facetData;
  21357. if (!data.facetNormals) {
  21358. data.facetNormals = new Array();
  21359. }
  21360. if (!data.facetPositions) {
  21361. data.facetPositions = new Array();
  21362. }
  21363. if (!data.facetPartitioning) {
  21364. data.facetPartitioning = new Array();
  21365. }
  21366. data.facetNb = (this.getIndices().length / 3) | 0;
  21367. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21368. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21369. for (var f = 0; f < data.facetNb; f++) {
  21370. data.facetNormals[f] = BABYLON.Vector3.Zero();
  21371. data.facetPositions[f] = BABYLON.Vector3.Zero();
  21372. }
  21373. data.facetDataEnabled = true;
  21374. return this;
  21375. };
  21376. /**
  21377. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21378. * This method can be called within the render loop.
  21379. * 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
  21380. * @returns the current mesh
  21381. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21382. */
  21383. AbstractMesh.prototype.updateFacetData = function () {
  21384. var data = this._facetData;
  21385. if (!data.facetDataEnabled) {
  21386. this._initFacetData();
  21387. }
  21388. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21389. var indices = this.getIndices();
  21390. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21391. var bInfo = this.getBoundingInfo();
  21392. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  21393. // init arrays, matrix and sort function on first call
  21394. data.facetDepthSortEnabled = true;
  21395. if (indices instanceof Uint16Array) {
  21396. data.depthSortedIndices = new Uint16Array(indices);
  21397. }
  21398. else if (indices instanceof Uint32Array) {
  21399. data.depthSortedIndices = new Uint32Array(indices);
  21400. }
  21401. else {
  21402. var needs32bits = false;
  21403. for (var i = 0; i < indices.length; i++) {
  21404. if (indices[i] > 65535) {
  21405. needs32bits = true;
  21406. break;
  21407. }
  21408. }
  21409. if (needs32bits) {
  21410. data.depthSortedIndices = new Uint32Array(indices);
  21411. }
  21412. else {
  21413. data.depthSortedIndices = new Uint16Array(indices);
  21414. }
  21415. }
  21416. data.facetDepthSortFunction = function (f1, f2) {
  21417. return (f2.sqDistance - f1.sqDistance);
  21418. };
  21419. if (!data.facetDepthSortFrom) {
  21420. var camera = this.getScene().activeCamera;
  21421. data.facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21422. }
  21423. data.depthSortedFacets = [];
  21424. for (var f = 0; f < data.facetNb; f++) {
  21425. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21426. data.depthSortedFacets.push(depthSortedFacet);
  21427. }
  21428. data.invertedMatrix = BABYLON.Matrix.Identity();
  21429. data.facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21430. }
  21431. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21432. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21433. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21434. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  21435. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  21436. data.subDiv.max = data.partitioningSubdivisions;
  21437. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21438. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  21439. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  21440. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  21441. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  21442. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  21443. // set the parameters for ComputeNormals()
  21444. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  21445. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  21446. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21447. data.facetParameters.bInfo = bInfo;
  21448. data.facetParameters.bbSize = data.bbSize;
  21449. data.facetParameters.subDiv = data.subDiv;
  21450. data.facetParameters.ratio = this.partitioningBBoxRatio;
  21451. data.facetParameters.depthSort = data.facetDepthSort;
  21452. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  21453. this.computeWorldMatrix(true);
  21454. this._worldMatrix.invertToRef(data.invertedMatrix);
  21455. BABYLON.Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  21456. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  21457. }
  21458. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  21459. BABYLON.VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  21460. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  21461. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  21462. var l = (data.depthSortedIndices.length / 3) | 0;
  21463. for (var f = 0; f < l; f++) {
  21464. var sind = data.depthSortedFacets[f].ind;
  21465. data.depthSortedIndices[f * 3] = indices[sind];
  21466. data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21467. data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21468. }
  21469. this.updateIndices(data.depthSortedIndices);
  21470. }
  21471. return this;
  21472. };
  21473. /**
  21474. * Returns the facetLocalNormals array.
  21475. * The normals are expressed in the mesh local spac
  21476. * @returns an array of Vector3
  21477. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21478. */
  21479. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21480. if (!this._facetData.facetNormals) {
  21481. this.updateFacetData();
  21482. }
  21483. return this._facetData.facetNormals;
  21484. };
  21485. /**
  21486. * Returns the facetLocalPositions array.
  21487. * The facet positions are expressed in the mesh local space
  21488. * @returns an array of Vector3
  21489. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21490. */
  21491. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21492. if (!this._facetData.facetPositions) {
  21493. this.updateFacetData();
  21494. }
  21495. return this._facetData.facetPositions;
  21496. };
  21497. /**
  21498. * Returns the facetLocalPartioning array
  21499. * @returns an array of array of numbers
  21500. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21501. */
  21502. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21503. if (!this._facetData.facetPartitioning) {
  21504. this.updateFacetData();
  21505. }
  21506. return this._facetData.facetPartitioning;
  21507. };
  21508. /**
  21509. * Returns the i-th facet position in the world system.
  21510. * This method allocates a new Vector3 per call
  21511. * @param i defines the facet index
  21512. * @returns a new Vector3
  21513. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21514. */
  21515. AbstractMesh.prototype.getFacetPosition = function (i) {
  21516. var pos = BABYLON.Vector3.Zero();
  21517. this.getFacetPositionToRef(i, pos);
  21518. return pos;
  21519. };
  21520. /**
  21521. * Sets the reference Vector3 with the i-th facet position in the world system
  21522. * @param i defines the facet index
  21523. * @param ref defines the target vector
  21524. * @returns the current mesh
  21525. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21526. */
  21527. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21528. var localPos = (this.getFacetLocalPositions())[i];
  21529. var world = this.getWorldMatrix();
  21530. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21531. return this;
  21532. };
  21533. /**
  21534. * Returns the i-th facet normal in the world system.
  21535. * This method allocates a new Vector3 per call
  21536. * @param i defines the facet index
  21537. * @returns a new Vector3
  21538. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21539. */
  21540. AbstractMesh.prototype.getFacetNormal = function (i) {
  21541. var norm = BABYLON.Vector3.Zero();
  21542. this.getFacetNormalToRef(i, norm);
  21543. return norm;
  21544. };
  21545. /**
  21546. * Sets the reference Vector3 with the i-th facet normal in the world system
  21547. * @param i defines the facet index
  21548. * @param ref defines the target vector
  21549. * @returns the current mesh
  21550. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21551. */
  21552. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21553. var localNorm = (this.getFacetLocalNormals())[i];
  21554. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21555. return this;
  21556. };
  21557. /**
  21558. * 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)
  21559. * @param x defines x coordinate
  21560. * @param y defines y coordinate
  21561. * @param z defines z coordinate
  21562. * @returns the array of facet indexes
  21563. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21564. */
  21565. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21566. var bInfo = this.getBoundingInfo();
  21567. var data = this._facetData;
  21568. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  21569. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  21570. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  21571. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  21572. return null;
  21573. }
  21574. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  21575. };
  21576. /**
  21577. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21578. * @param projected sets as the (x,y,z) world projection on the facet
  21579. * @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
  21580. * @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
  21581. * @param x defines x coordinate
  21582. * @param y defines y coordinate
  21583. * @param z defines z coordinate
  21584. * @returns the face index if found (or null instead)
  21585. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21586. */
  21587. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21588. if (checkFace === void 0) { checkFace = false; }
  21589. if (facing === void 0) { facing = true; }
  21590. var world = this.getWorldMatrix();
  21591. var invMat = BABYLON.Tmp.Matrix[5];
  21592. world.invertToRef(invMat);
  21593. var invVect = BABYLON.Tmp.Vector3[8];
  21594. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21595. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21596. if (projected) {
  21597. // tranform the local computed projected vector to world coordinates
  21598. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21599. }
  21600. return closest;
  21601. };
  21602. /**
  21603. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21604. * @param projected sets as the (x,y,z) local projection on the facet
  21605. * @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
  21606. * @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
  21607. * @param x defines x coordinate
  21608. * @param y defines y coordinate
  21609. * @param z defines z coordinate
  21610. * @returns the face index if found (or null instead)
  21611. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21612. */
  21613. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21614. if (checkFace === void 0) { checkFace = false; }
  21615. if (facing === void 0) { facing = true; }
  21616. var closest = null;
  21617. var tmpx = 0.0;
  21618. var tmpy = 0.0;
  21619. var tmpz = 0.0;
  21620. var d = 0.0; // tmp dot facet normal * facet position
  21621. var t0 = 0.0;
  21622. var projx = 0.0;
  21623. var projy = 0.0;
  21624. var projz = 0.0;
  21625. // Get all the facets in the same partitioning block than (x, y, z)
  21626. var facetPositions = this.getFacetLocalPositions();
  21627. var facetNormals = this.getFacetLocalNormals();
  21628. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21629. if (!facetsInBlock) {
  21630. return null;
  21631. }
  21632. // Get the closest facet to (x, y, z)
  21633. var shortest = Number.MAX_VALUE; // init distance vars
  21634. var tmpDistance = shortest;
  21635. var fib; // current facet in the block
  21636. var norm; // current facet normal
  21637. var p0; // current facet barycenter position
  21638. // loop on all the facets in the current partitioning block
  21639. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21640. fib = facetsInBlock[idx];
  21641. norm = facetNormals[fib];
  21642. p0 = facetPositions[fib];
  21643. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21644. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21645. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21646. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21647. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21648. projx = x + norm.x * t0;
  21649. projy = y + norm.y * t0;
  21650. projz = z + norm.z * t0;
  21651. tmpx = projx - x;
  21652. tmpy = projy - y;
  21653. tmpz = projz - z;
  21654. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21655. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21656. shortest = tmpDistance;
  21657. closest = fib;
  21658. if (projected) {
  21659. projected.x = projx;
  21660. projected.y = projy;
  21661. projected.z = projz;
  21662. }
  21663. }
  21664. }
  21665. }
  21666. return closest;
  21667. };
  21668. /**
  21669. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21670. * @returns the parameters
  21671. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21672. */
  21673. AbstractMesh.prototype.getFacetDataParameters = function () {
  21674. return this._facetData.facetParameters;
  21675. };
  21676. /**
  21677. * Disables the feature FacetData and frees the related memory
  21678. * @returns the current mesh
  21679. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21680. */
  21681. AbstractMesh.prototype.disableFacetData = function () {
  21682. if (this._facetData.facetDataEnabled) {
  21683. this._facetData.facetDataEnabled = false;
  21684. this._facetData.facetPositions = new Array();
  21685. this._facetData.facetNormals = new Array();
  21686. this._facetData.facetPartitioning = new Array();
  21687. this._facetData.facetParameters = null;
  21688. this._facetData.depthSortedIndices = new Uint32Array(0);
  21689. }
  21690. return this;
  21691. };
  21692. /**
  21693. * Updates the AbstractMesh indices array
  21694. * @param indices defines the data source
  21695. * @returns the current mesh
  21696. */
  21697. AbstractMesh.prototype.updateIndices = function (indices) {
  21698. return this;
  21699. };
  21700. /**
  21701. * Creates new normals data for the mesh
  21702. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21703. * @returns the current mesh
  21704. */
  21705. AbstractMesh.prototype.createNormals = function (updatable) {
  21706. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21707. var indices = this.getIndices();
  21708. var normals;
  21709. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21710. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21711. }
  21712. else {
  21713. normals = [];
  21714. }
  21715. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21716. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21717. return this;
  21718. };
  21719. /**
  21720. * Align the mesh with a normal
  21721. * @param normal defines the normal to use
  21722. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21723. * @returns the current mesh
  21724. */
  21725. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21726. if (!upDirection) {
  21727. upDirection = BABYLON.Axis.Y;
  21728. }
  21729. var axisX = BABYLON.Tmp.Vector3[0];
  21730. var axisZ = BABYLON.Tmp.Vector3[1];
  21731. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21732. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21733. if (this.rotationQuaternion) {
  21734. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21735. }
  21736. else {
  21737. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21738. }
  21739. return this;
  21740. };
  21741. /** @hidden */
  21742. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21743. return false;
  21744. };
  21745. /** No occlusion */
  21746. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21747. /** Occlusion set to optimisitic */
  21748. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21749. /** Occlusion set to strict */
  21750. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21751. /** Use an accurante occlusion algorithm */
  21752. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21753. /** Use a conservative occlusion algorithm */
  21754. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21755. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21756. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21757. /** Culling strategy with bounding sphere only and then frustum culling */
  21758. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21759. return AbstractMesh;
  21760. }(BABYLON.TransformNode));
  21761. BABYLON.AbstractMesh = AbstractMesh;
  21762. })(BABYLON || (BABYLON = {}));
  21763. //# sourceMappingURL=babylon.abstractMesh.js.map
  21764. var BABYLON;
  21765. (function (BABYLON) {
  21766. /**
  21767. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21768. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21769. * 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.
  21770. */
  21771. var Light = /** @class */ (function (_super) {
  21772. __extends(Light, _super);
  21773. /**
  21774. * Creates a Light object in the scene.
  21775. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21776. * @param name The firendly name of the light
  21777. * @param scene The scene the light belongs too
  21778. */
  21779. function Light(name, scene) {
  21780. var _this = _super.call(this, name, scene) || this;
  21781. /**
  21782. * Diffuse gives the basic color to an object.
  21783. */
  21784. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21785. /**
  21786. * Specular produces a highlight color on an object.
  21787. * Note: This is note affecting PBR materials.
  21788. */
  21789. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21790. /**
  21791. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21792. * falling off base on range or angle.
  21793. * This can be set to any values in Light.FALLOFF_x.
  21794. *
  21795. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21796. * other types of materials.
  21797. */
  21798. _this.falloffType = Light.FALLOFF_DEFAULT;
  21799. /**
  21800. * Strength of the light.
  21801. * Note: By default it is define in the framework own unit.
  21802. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21803. */
  21804. _this.intensity = 1.0;
  21805. _this._range = Number.MAX_VALUE;
  21806. _this._inverseSquaredRange = 0;
  21807. /**
  21808. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21809. * of light.
  21810. */
  21811. _this._photometricScale = 1.0;
  21812. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21813. _this._radius = 0.00001;
  21814. /**
  21815. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21816. * exceeding the number allowed of the materials.
  21817. */
  21818. _this.renderPriority = 0;
  21819. _this._shadowEnabled = true;
  21820. _this._excludeWithLayerMask = 0;
  21821. _this._includeOnlyWithLayerMask = 0;
  21822. _this._lightmapMode = 0;
  21823. /**
  21824. * @hidden Internal use only.
  21825. */
  21826. _this._excludedMeshesIds = new Array();
  21827. /**
  21828. * @hidden Internal use only.
  21829. */
  21830. _this._includedOnlyMeshesIds = new Array();
  21831. _this.getScene().addLight(_this);
  21832. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21833. _this._buildUniformLayout();
  21834. _this.includedOnlyMeshes = new Array();
  21835. _this.excludedMeshes = new Array();
  21836. _this._resyncMeshes();
  21837. return _this;
  21838. }
  21839. Object.defineProperty(Light.prototype, "range", {
  21840. /**
  21841. * Defines how far from the source the light is impacting in scene units.
  21842. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21843. */
  21844. get: function () {
  21845. return this._range;
  21846. },
  21847. /**
  21848. * Defines how far from the source the light is impacting in scene units.
  21849. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21850. */
  21851. set: function (value) {
  21852. this._range = value;
  21853. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21854. },
  21855. enumerable: true,
  21856. configurable: true
  21857. });
  21858. Object.defineProperty(Light.prototype, "intensityMode", {
  21859. /**
  21860. * Gets the photometric scale used to interpret the intensity.
  21861. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21862. */
  21863. get: function () {
  21864. return this._intensityMode;
  21865. },
  21866. /**
  21867. * Sets the photometric scale used to interpret the intensity.
  21868. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21869. */
  21870. set: function (value) {
  21871. this._intensityMode = value;
  21872. this._computePhotometricScale();
  21873. },
  21874. enumerable: true,
  21875. configurable: true
  21876. });
  21877. ;
  21878. ;
  21879. Object.defineProperty(Light.prototype, "radius", {
  21880. /**
  21881. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21882. */
  21883. get: function () {
  21884. return this._radius;
  21885. },
  21886. /**
  21887. * sets the light radius used by PBR Materials to simulate soft area lights.
  21888. */
  21889. set: function (value) {
  21890. this._radius = value;
  21891. this._computePhotometricScale();
  21892. },
  21893. enumerable: true,
  21894. configurable: true
  21895. });
  21896. ;
  21897. ;
  21898. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21899. /**
  21900. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21901. * the current shadow generator.
  21902. */
  21903. get: function () {
  21904. return this._shadowEnabled;
  21905. },
  21906. /**
  21907. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21908. * the current shadow generator.
  21909. */
  21910. set: function (value) {
  21911. if (this._shadowEnabled === value) {
  21912. return;
  21913. }
  21914. this._shadowEnabled = value;
  21915. this._markMeshesAsLightDirty();
  21916. },
  21917. enumerable: true,
  21918. configurable: true
  21919. });
  21920. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21921. /**
  21922. * Gets the only meshes impacted by this light.
  21923. */
  21924. get: function () {
  21925. return this._includedOnlyMeshes;
  21926. },
  21927. /**
  21928. * Sets the only meshes impacted by this light.
  21929. */
  21930. set: function (value) {
  21931. this._includedOnlyMeshes = value;
  21932. this._hookArrayForIncludedOnly(value);
  21933. },
  21934. enumerable: true,
  21935. configurable: true
  21936. });
  21937. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21938. /**
  21939. * Gets the meshes not impacted by this light.
  21940. */
  21941. get: function () {
  21942. return this._excludedMeshes;
  21943. },
  21944. /**
  21945. * Sets the meshes not impacted by this light.
  21946. */
  21947. set: function (value) {
  21948. this._excludedMeshes = value;
  21949. this._hookArrayForExcluded(value);
  21950. },
  21951. enumerable: true,
  21952. configurable: true
  21953. });
  21954. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21955. /**
  21956. * Gets the layer id use to find what meshes are not impacted by the light.
  21957. * Inactive if 0
  21958. */
  21959. get: function () {
  21960. return this._excludeWithLayerMask;
  21961. },
  21962. /**
  21963. * Sets the layer id use to find what meshes are not impacted by the light.
  21964. * Inactive if 0
  21965. */
  21966. set: function (value) {
  21967. this._excludeWithLayerMask = value;
  21968. this._resyncMeshes();
  21969. },
  21970. enumerable: true,
  21971. configurable: true
  21972. });
  21973. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21974. /**
  21975. * Gets the layer id use to find what meshes are impacted by the light.
  21976. * Inactive if 0
  21977. */
  21978. get: function () {
  21979. return this._includeOnlyWithLayerMask;
  21980. },
  21981. /**
  21982. * Sets the layer id use to find what meshes are impacted by the light.
  21983. * Inactive if 0
  21984. */
  21985. set: function (value) {
  21986. this._includeOnlyWithLayerMask = value;
  21987. this._resyncMeshes();
  21988. },
  21989. enumerable: true,
  21990. configurable: true
  21991. });
  21992. Object.defineProperty(Light.prototype, "lightmapMode", {
  21993. /**
  21994. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21995. */
  21996. get: function () {
  21997. return this._lightmapMode;
  21998. },
  21999. /**
  22000. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22001. */
  22002. set: function (value) {
  22003. if (this._lightmapMode === value) {
  22004. return;
  22005. }
  22006. this._lightmapMode = value;
  22007. this._markMeshesAsLightDirty();
  22008. },
  22009. enumerable: true,
  22010. configurable: true
  22011. });
  22012. /**
  22013. * Returns the string "Light".
  22014. * @returns the class name
  22015. */
  22016. Light.prototype.getClassName = function () {
  22017. return "Light";
  22018. };
  22019. /**
  22020. * Converts the light information to a readable string for debug purpose.
  22021. * @param fullDetails Supports for multiple levels of logging within scene loading
  22022. * @returns the human readable light info
  22023. */
  22024. Light.prototype.toString = function (fullDetails) {
  22025. var ret = "Name: " + this.name;
  22026. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  22027. if (this.animations) {
  22028. for (var i = 0; i < this.animations.length; i++) {
  22029. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22030. }
  22031. }
  22032. if (fullDetails) {
  22033. }
  22034. return ret;
  22035. };
  22036. /** @hidden */
  22037. Light.prototype._syncParentEnabledState = function () {
  22038. _super.prototype._syncParentEnabledState.call(this);
  22039. this._resyncMeshes();
  22040. };
  22041. /**
  22042. * Set the enabled state of this node.
  22043. * @param value - the new enabled state
  22044. */
  22045. Light.prototype.setEnabled = function (value) {
  22046. _super.prototype.setEnabled.call(this, value);
  22047. this._resyncMeshes();
  22048. };
  22049. /**
  22050. * Returns the Light associated shadow generator if any.
  22051. * @return the associated shadow generator.
  22052. */
  22053. Light.prototype.getShadowGenerator = function () {
  22054. return this._shadowGenerator;
  22055. };
  22056. /**
  22057. * Returns a Vector3, the absolute light position in the World.
  22058. * @returns the world space position of the light
  22059. */
  22060. Light.prototype.getAbsolutePosition = function () {
  22061. return BABYLON.Vector3.Zero();
  22062. };
  22063. /**
  22064. * Specifies if the light will affect the passed mesh.
  22065. * @param mesh The mesh to test against the light
  22066. * @return true the mesh is affected otherwise, false.
  22067. */
  22068. Light.prototype.canAffectMesh = function (mesh) {
  22069. if (!mesh) {
  22070. return true;
  22071. }
  22072. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22073. return false;
  22074. }
  22075. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22076. return false;
  22077. }
  22078. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22079. return false;
  22080. }
  22081. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22082. return false;
  22083. }
  22084. return true;
  22085. };
  22086. /**
  22087. * Sort function to order lights for rendering.
  22088. * @param a First Light object to compare to second.
  22089. * @param b Second Light object to compare first.
  22090. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22091. */
  22092. Light.CompareLightsPriority = function (a, b) {
  22093. //shadow-casting lights have priority over non-shadow-casting lights
  22094. //the renderPrioirty is a secondary sort criterion
  22095. if (a.shadowEnabled !== b.shadowEnabled) {
  22096. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22097. }
  22098. return b.renderPriority - a.renderPriority;
  22099. };
  22100. /**
  22101. * Releases resources associated with this node.
  22102. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22103. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22104. */
  22105. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22106. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22107. if (this._shadowGenerator) {
  22108. this._shadowGenerator.dispose();
  22109. this._shadowGenerator = null;
  22110. }
  22111. // Animations
  22112. this.getScene().stopAnimation(this);
  22113. // Remove from meshes
  22114. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22115. var mesh = _a[_i];
  22116. mesh._removeLightSource(this);
  22117. }
  22118. this._uniformBuffer.dispose();
  22119. // Remove from scene
  22120. this.getScene().removeLight(this);
  22121. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22122. };
  22123. /**
  22124. * Returns the light type ID (integer).
  22125. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22126. */
  22127. Light.prototype.getTypeID = function () {
  22128. return 0;
  22129. };
  22130. /**
  22131. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22132. * @returns the scaled intensity in intensity mode unit
  22133. */
  22134. Light.prototype.getScaledIntensity = function () {
  22135. return this._photometricScale * this.intensity;
  22136. };
  22137. /**
  22138. * Returns a new Light object, named "name", from the current one.
  22139. * @param name The name of the cloned light
  22140. * @returns the new created light
  22141. */
  22142. Light.prototype.clone = function (name) {
  22143. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22144. if (!constructor) {
  22145. return null;
  22146. }
  22147. return BABYLON.SerializationHelper.Clone(constructor, this);
  22148. };
  22149. /**
  22150. * Serializes the current light into a Serialization object.
  22151. * @returns the serialized object.
  22152. */
  22153. Light.prototype.serialize = function () {
  22154. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22155. // Type
  22156. serializationObject.type = this.getTypeID();
  22157. // Parent
  22158. if (this.parent) {
  22159. serializationObject.parentId = this.parent.id;
  22160. }
  22161. // Inclusion / exclusions
  22162. if (this.excludedMeshes.length > 0) {
  22163. serializationObject.excludedMeshesIds = [];
  22164. this.excludedMeshes.forEach(function (mesh) {
  22165. serializationObject.excludedMeshesIds.push(mesh.id);
  22166. });
  22167. }
  22168. if (this.includedOnlyMeshes.length > 0) {
  22169. serializationObject.includedOnlyMeshesIds = [];
  22170. this.includedOnlyMeshes.forEach(function (mesh) {
  22171. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22172. });
  22173. }
  22174. // Animations
  22175. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22176. serializationObject.ranges = this.serializeAnimationRanges();
  22177. return serializationObject;
  22178. };
  22179. /**
  22180. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22181. * This new light is named "name" and added to the passed scene.
  22182. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22183. * @param name The friendly name of the light
  22184. * @param scene The scene the new light will belong to
  22185. * @returns the constructor function
  22186. */
  22187. Light.GetConstructorFromName = function (type, name, scene) {
  22188. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  22189. if (constructorFunc) {
  22190. return constructorFunc;
  22191. }
  22192. // Default to no light for none present once.
  22193. return null;
  22194. };
  22195. /**
  22196. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22197. * @param parsedLight The JSON representation of the light
  22198. * @param scene The scene to create the parsed light in
  22199. * @returns the created light after parsing
  22200. */
  22201. Light.Parse = function (parsedLight, scene) {
  22202. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22203. if (!constructor) {
  22204. return null;
  22205. }
  22206. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22207. // Inclusion / exclusions
  22208. if (parsedLight.excludedMeshesIds) {
  22209. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22210. }
  22211. if (parsedLight.includedOnlyMeshesIds) {
  22212. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22213. }
  22214. // Parent
  22215. if (parsedLight.parentId) {
  22216. light._waitingParentId = parsedLight.parentId;
  22217. }
  22218. // Animations
  22219. if (parsedLight.animations) {
  22220. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22221. var parsedAnimation = parsedLight.animations[animationIndex];
  22222. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22223. }
  22224. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22225. }
  22226. if (parsedLight.autoAnimate) {
  22227. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22228. }
  22229. return light;
  22230. };
  22231. Light.prototype._hookArrayForExcluded = function (array) {
  22232. var _this = this;
  22233. var oldPush = array.push;
  22234. array.push = function () {
  22235. var items = [];
  22236. for (var _i = 0; _i < arguments.length; _i++) {
  22237. items[_i] = arguments[_i];
  22238. }
  22239. var result = oldPush.apply(array, items);
  22240. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22241. var item = items_1[_a];
  22242. item._resyncLighSource(_this);
  22243. }
  22244. return result;
  22245. };
  22246. var oldSplice = array.splice;
  22247. array.splice = function (index, deleteCount) {
  22248. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22249. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22250. var item = deleted_1[_i];
  22251. item._resyncLighSource(_this);
  22252. }
  22253. return deleted;
  22254. };
  22255. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22256. var item = array_1[_i];
  22257. item._resyncLighSource(this);
  22258. }
  22259. };
  22260. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22261. var _this = this;
  22262. var oldPush = array.push;
  22263. array.push = function () {
  22264. var items = [];
  22265. for (var _i = 0; _i < arguments.length; _i++) {
  22266. items[_i] = arguments[_i];
  22267. }
  22268. var result = oldPush.apply(array, items);
  22269. _this._resyncMeshes();
  22270. return result;
  22271. };
  22272. var oldSplice = array.splice;
  22273. array.splice = function (index, deleteCount) {
  22274. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22275. _this._resyncMeshes();
  22276. return deleted;
  22277. };
  22278. this._resyncMeshes();
  22279. };
  22280. Light.prototype._resyncMeshes = function () {
  22281. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22282. var mesh = _a[_i];
  22283. mesh._resyncLighSource(this);
  22284. }
  22285. };
  22286. /**
  22287. * Forces the meshes to update their light related information in their rendering used effects
  22288. * @hidden Internal Use Only
  22289. */
  22290. Light.prototype._markMeshesAsLightDirty = function () {
  22291. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22292. var mesh = _a[_i];
  22293. if (mesh._lightSources.indexOf(this) !== -1) {
  22294. mesh._markSubMeshesAsLightDirty();
  22295. }
  22296. }
  22297. };
  22298. /**
  22299. * Recomputes the cached photometric scale if needed.
  22300. */
  22301. Light.prototype._computePhotometricScale = function () {
  22302. this._photometricScale = this._getPhotometricScale();
  22303. this.getScene().resetCachedMaterial();
  22304. };
  22305. /**
  22306. * Returns the Photometric Scale according to the light type and intensity mode.
  22307. */
  22308. Light.prototype._getPhotometricScale = function () {
  22309. var photometricScale = 0.0;
  22310. var lightTypeID = this.getTypeID();
  22311. //get photometric mode
  22312. var photometricMode = this.intensityMode;
  22313. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22314. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22315. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22316. }
  22317. else {
  22318. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22319. }
  22320. }
  22321. //compute photometric scale
  22322. switch (lightTypeID) {
  22323. case Light.LIGHTTYPEID_POINTLIGHT:
  22324. case Light.LIGHTTYPEID_SPOTLIGHT:
  22325. switch (photometricMode) {
  22326. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22327. photometricScale = 1.0 / (4.0 * Math.PI);
  22328. break;
  22329. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22330. photometricScale = 1.0;
  22331. break;
  22332. case Light.INTENSITYMODE_LUMINANCE:
  22333. photometricScale = this.radius * this.radius;
  22334. break;
  22335. }
  22336. break;
  22337. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22338. switch (photometricMode) {
  22339. case Light.INTENSITYMODE_ILLUMINANCE:
  22340. photometricScale = 1.0;
  22341. break;
  22342. case Light.INTENSITYMODE_LUMINANCE:
  22343. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22344. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22345. var apexAngleRadians = this.radius;
  22346. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22347. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22348. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22349. photometricScale = solidAngle;
  22350. break;
  22351. }
  22352. break;
  22353. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22354. // No fall off in hemisperic light.
  22355. photometricScale = 1.0;
  22356. break;
  22357. }
  22358. return photometricScale;
  22359. };
  22360. /**
  22361. * Reorder the light in the scene according to their defined priority.
  22362. * @hidden Internal Use Only
  22363. */
  22364. Light.prototype._reorderLightsInScene = function () {
  22365. var scene = this.getScene();
  22366. if (this._renderPriority != 0) {
  22367. scene.requireLightSorting = true;
  22368. }
  22369. this.getScene().sortLightsByPriority();
  22370. };
  22371. /**
  22372. * Falloff Default: light is falling off following the material specification:
  22373. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22374. */
  22375. Light.FALLOFF_DEFAULT = 0;
  22376. /**
  22377. * Falloff Physical: light is falling off following the inverse squared distance law.
  22378. */
  22379. Light.FALLOFF_PHYSICAL = 1;
  22380. /**
  22381. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22382. * to enhance interoperability with other engines.
  22383. */
  22384. Light.FALLOFF_GLTF = 2;
  22385. /**
  22386. * Falloff Standard: light is falling off like in the standard material
  22387. * to enhance interoperability with other materials.
  22388. */
  22389. Light.FALLOFF_STANDARD = 3;
  22390. //lightmapMode Consts
  22391. /**
  22392. * If every light affecting the material is in this lightmapMode,
  22393. * material.lightmapTexture adds or multiplies
  22394. * (depends on material.useLightmapAsShadowmap)
  22395. * after every other light calculations.
  22396. */
  22397. Light.LIGHTMAP_DEFAULT = 0;
  22398. /**
  22399. * material.lightmapTexture as only diffuse lighting from this light
  22400. * adds only specular lighting from this light
  22401. * adds dynamic shadows
  22402. */
  22403. Light.LIGHTMAP_SPECULAR = 1;
  22404. /**
  22405. * material.lightmapTexture as only lighting
  22406. * no light calculation from this light
  22407. * only adds dynamic shadows from this light
  22408. */
  22409. Light.LIGHTMAP_SHADOWSONLY = 2;
  22410. // Intensity Mode Consts
  22411. /**
  22412. * Each light type uses the default quantity according to its type:
  22413. * point/spot lights use luminous intensity
  22414. * directional lights use illuminance
  22415. */
  22416. Light.INTENSITYMODE_AUTOMATIC = 0;
  22417. /**
  22418. * lumen (lm)
  22419. */
  22420. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22421. /**
  22422. * candela (lm/sr)
  22423. */
  22424. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22425. /**
  22426. * lux (lm/m^2)
  22427. */
  22428. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22429. /**
  22430. * nit (cd/m^2)
  22431. */
  22432. Light.INTENSITYMODE_LUMINANCE = 4;
  22433. // Light types ids const.
  22434. /**
  22435. * Light type const id of the point light.
  22436. */
  22437. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22438. /**
  22439. * Light type const id of the directional light.
  22440. */
  22441. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22442. /**
  22443. * Light type const id of the spot light.
  22444. */
  22445. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22446. /**
  22447. * Light type const id of the hemispheric light.
  22448. */
  22449. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22450. __decorate([
  22451. BABYLON.serializeAsColor3()
  22452. ], Light.prototype, "diffuse", void 0);
  22453. __decorate([
  22454. BABYLON.serializeAsColor3()
  22455. ], Light.prototype, "specular", void 0);
  22456. __decorate([
  22457. BABYLON.serialize()
  22458. ], Light.prototype, "falloffType", void 0);
  22459. __decorate([
  22460. BABYLON.serialize()
  22461. ], Light.prototype, "intensity", void 0);
  22462. __decorate([
  22463. BABYLON.serialize()
  22464. ], Light.prototype, "range", null);
  22465. __decorate([
  22466. BABYLON.serialize()
  22467. ], Light.prototype, "intensityMode", null);
  22468. __decorate([
  22469. BABYLON.serialize()
  22470. ], Light.prototype, "radius", null);
  22471. __decorate([
  22472. BABYLON.serialize()
  22473. ], Light.prototype, "_renderPriority", void 0);
  22474. __decorate([
  22475. BABYLON.expandToProperty("_reorderLightsInScene")
  22476. ], Light.prototype, "renderPriority", void 0);
  22477. __decorate([
  22478. BABYLON.serialize("shadowEnabled")
  22479. ], Light.prototype, "_shadowEnabled", void 0);
  22480. __decorate([
  22481. BABYLON.serialize("excludeWithLayerMask")
  22482. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22483. __decorate([
  22484. BABYLON.serialize("includeOnlyWithLayerMask")
  22485. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22486. __decorate([
  22487. BABYLON.serialize("lightmapMode")
  22488. ], Light.prototype, "_lightmapMode", void 0);
  22489. return Light;
  22490. }(BABYLON.Node));
  22491. BABYLON.Light = Light;
  22492. })(BABYLON || (BABYLON = {}));
  22493. //# sourceMappingURL=babylon.light.js.map
  22494. var BABYLON;
  22495. (function (BABYLON) {
  22496. /**
  22497. * This is the base class of all the camera used in the application.
  22498. * @see http://doc.babylonjs.com/features/cameras
  22499. */
  22500. var Camera = /** @class */ (function (_super) {
  22501. __extends(Camera, _super);
  22502. /**
  22503. * Instantiates a new camera object.
  22504. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  22505. * @see http://doc.babylonjs.com/features/cameras
  22506. * @param name Defines the name of the camera in the scene
  22507. * @param position Defines the position of the camera
  22508. * @param scene Defines the scene the camera belongs too
  22509. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  22510. */
  22511. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22512. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22513. var _this = _super.call(this, name, scene) || this;
  22514. /**
  22515. * The vector the camera should consider as up.
  22516. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22517. */
  22518. _this.upVector = BABYLON.Vector3.Up();
  22519. /**
  22520. * Define the current limit on the left side for an orthographic camera
  22521. * In scene unit
  22522. */
  22523. _this.orthoLeft = null;
  22524. /**
  22525. * Define the current limit on the right side for an orthographic camera
  22526. * In scene unit
  22527. */
  22528. _this.orthoRight = null;
  22529. /**
  22530. * Define the current limit on the bottom side for an orthographic camera
  22531. * In scene unit
  22532. */
  22533. _this.orthoBottom = null;
  22534. /**
  22535. * Define the current limit on the top side for an orthographic camera
  22536. * In scene unit
  22537. */
  22538. _this.orthoTop = null;
  22539. /**
  22540. * Field Of View is set in Radians. (default is 0.8)
  22541. */
  22542. _this.fov = 0.8;
  22543. /**
  22544. * Define the minimum distance the camera can see from.
  22545. * This is important to note that the depth buffer are not infinite and the closer it starts
  22546. * the more your scene might encounter depth fighting issue.
  22547. */
  22548. _this.minZ = 1;
  22549. /**
  22550. * Define the maximum distance the camera can see to.
  22551. * This is important to note that the depth buffer are not infinite and the further it end
  22552. * the more your scene might encounter depth fighting issue.
  22553. */
  22554. _this.maxZ = 10000.0;
  22555. /**
  22556. * Define the default inertia of the camera.
  22557. * This helps giving a smooth feeling to the camera movement.
  22558. */
  22559. _this.inertia = 0.9;
  22560. /**
  22561. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  22562. */
  22563. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22564. /**
  22565. * Define wether the camera is intermediate.
  22566. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  22567. */
  22568. _this.isIntermediate = false;
  22569. /**
  22570. * Define the viewport of the camera.
  22571. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  22572. */
  22573. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22574. /**
  22575. * Restricts the camera to viewing objects with the same layerMask.
  22576. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22577. */
  22578. _this.layerMask = 0x0FFFFFFF;
  22579. /**
  22580. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22581. */
  22582. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22583. /**
  22584. * Rig mode of the camera.
  22585. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  22586. * This is normally controlled byt the camera themselves as internal use.
  22587. */
  22588. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22589. /**
  22590. * Defines the list of custom render target the camera should render to.
  22591. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  22592. * else in the scene.
  22593. */
  22594. _this.customRenderTargets = new Array();
  22595. /**
  22596. * Observable triggered when the camera view matrix has changed.
  22597. */
  22598. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22599. /**
  22600. * Observable triggered when the camera Projection matrix has changed.
  22601. */
  22602. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22603. /**
  22604. * Observable triggered when the inputs have been processed.
  22605. */
  22606. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22607. /**
  22608. * Observable triggered when reset has been called and applied to the camera.
  22609. */
  22610. _this.onRestoreStateObservable = new BABYLON.Observable();
  22611. /** @hidden */
  22612. _this._rigCameras = new Array();
  22613. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22614. /** @hidden */
  22615. _this._skipRendering = false;
  22616. /** @hidden */
  22617. _this._projectionMatrix = new BABYLON.Matrix();
  22618. /** @hidden */
  22619. _this._postProcesses = new Array();
  22620. /** @hidden */
  22621. _this._activeMeshes = new BABYLON.SmartArray(256);
  22622. _this._globalPosition = BABYLON.Vector3.Zero();
  22623. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22624. _this._doNotComputeProjectionMatrix = false;
  22625. _this._transformMatrix = BABYLON.Matrix.Zero();
  22626. _this._refreshFrustumPlanes = true;
  22627. _this.getScene().addCamera(_this);
  22628. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22629. _this.getScene().activeCamera = _this;
  22630. }
  22631. _this.position = position;
  22632. return _this;
  22633. }
  22634. /**
  22635. * Store current camera state (fov, position, etc..)
  22636. * @returns the camera
  22637. */
  22638. Camera.prototype.storeState = function () {
  22639. this._stateStored = true;
  22640. this._storedFov = this.fov;
  22641. return this;
  22642. };
  22643. /**
  22644. * Restores the camera state values if it has been stored. You must call storeState() first
  22645. */
  22646. Camera.prototype._restoreStateValues = function () {
  22647. if (!this._stateStored) {
  22648. return false;
  22649. }
  22650. this.fov = this._storedFov;
  22651. return true;
  22652. };
  22653. /**
  22654. * Restored camera state. You must call storeState() first.
  22655. * @returns true if restored and false otherwise
  22656. */
  22657. Camera.prototype.restoreState = function () {
  22658. if (this._restoreStateValues()) {
  22659. this.onRestoreStateObservable.notifyObservers(this);
  22660. return true;
  22661. }
  22662. return false;
  22663. };
  22664. /**
  22665. * Gets the class name of the camera.
  22666. * @returns the class name
  22667. */
  22668. Camera.prototype.getClassName = function () {
  22669. return "Camera";
  22670. };
  22671. /**
  22672. * Gets a string representation of the camera usefull for debug purpose.
  22673. * @param fullDetails Defines that a more verboe level of logging is required
  22674. * @returns the string representation
  22675. */
  22676. Camera.prototype.toString = function (fullDetails) {
  22677. var ret = "Name: " + this.name;
  22678. ret += ", type: " + this.getClassName();
  22679. if (this.animations) {
  22680. for (var i = 0; i < this.animations.length; i++) {
  22681. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22682. }
  22683. }
  22684. if (fullDetails) {
  22685. }
  22686. return ret;
  22687. };
  22688. Object.defineProperty(Camera.prototype, "globalPosition", {
  22689. /**
  22690. * Gets the current world space position of the camera.
  22691. */
  22692. get: function () {
  22693. return this._globalPosition;
  22694. },
  22695. enumerable: true,
  22696. configurable: true
  22697. });
  22698. /**
  22699. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  22700. * @returns the active meshe list
  22701. */
  22702. Camera.prototype.getActiveMeshes = function () {
  22703. return this._activeMeshes;
  22704. };
  22705. /**
  22706. * Check wether a mesh is part of the current active mesh list of the camera
  22707. * @param mesh Defines the mesh to check
  22708. * @returns true if active, false otherwise
  22709. */
  22710. Camera.prototype.isActiveMesh = function (mesh) {
  22711. return (this._activeMeshes.indexOf(mesh) !== -1);
  22712. };
  22713. /**
  22714. * Is this camera ready to be used/rendered
  22715. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22716. * @return true if the camera is ready
  22717. */
  22718. Camera.prototype.isReady = function (completeCheck) {
  22719. if (completeCheck === void 0) { completeCheck = false; }
  22720. if (completeCheck) {
  22721. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22722. var pp = _a[_i];
  22723. if (pp && !pp.isReady()) {
  22724. return false;
  22725. }
  22726. }
  22727. }
  22728. return _super.prototype.isReady.call(this, completeCheck);
  22729. };
  22730. /** @hidden */
  22731. Camera.prototype._initCache = function () {
  22732. _super.prototype._initCache.call(this);
  22733. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22734. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22735. this._cache.mode = undefined;
  22736. this._cache.minZ = undefined;
  22737. this._cache.maxZ = undefined;
  22738. this._cache.fov = undefined;
  22739. this._cache.fovMode = undefined;
  22740. this._cache.aspectRatio = undefined;
  22741. this._cache.orthoLeft = undefined;
  22742. this._cache.orthoRight = undefined;
  22743. this._cache.orthoBottom = undefined;
  22744. this._cache.orthoTop = undefined;
  22745. this._cache.renderWidth = undefined;
  22746. this._cache.renderHeight = undefined;
  22747. };
  22748. /** @hidden */
  22749. Camera.prototype._updateCache = function (ignoreParentClass) {
  22750. if (!ignoreParentClass) {
  22751. _super.prototype._updateCache.call(this);
  22752. }
  22753. this._cache.position.copyFrom(this.position);
  22754. this._cache.upVector.copyFrom(this.upVector);
  22755. };
  22756. /** @hidden */
  22757. Camera.prototype._isSynchronized = function () {
  22758. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22759. };
  22760. /** @hidden */
  22761. Camera.prototype._isSynchronizedViewMatrix = function () {
  22762. if (!_super.prototype._isSynchronized.call(this))
  22763. return false;
  22764. return this._cache.position.equals(this.position)
  22765. && this._cache.upVector.equals(this.upVector)
  22766. && this.isSynchronizedWithParent();
  22767. };
  22768. /** @hidden */
  22769. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22770. var check = this._cache.mode === this.mode
  22771. && this._cache.minZ === this.minZ
  22772. && this._cache.maxZ === this.maxZ;
  22773. if (!check) {
  22774. return false;
  22775. }
  22776. var engine = this.getEngine();
  22777. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22778. check = this._cache.fov === this.fov
  22779. && this._cache.fovMode === this.fovMode
  22780. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22781. }
  22782. else {
  22783. check = this._cache.orthoLeft === this.orthoLeft
  22784. && this._cache.orthoRight === this.orthoRight
  22785. && this._cache.orthoBottom === this.orthoBottom
  22786. && this._cache.orthoTop === this.orthoTop
  22787. && this._cache.renderWidth === engine.getRenderWidth()
  22788. && this._cache.renderHeight === engine.getRenderHeight();
  22789. }
  22790. return check;
  22791. };
  22792. /**
  22793. * Attach the input controls to a specific dom element to get the input from.
  22794. * @param element Defines the element the controls should be listened from
  22795. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  22796. */
  22797. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22798. };
  22799. /**
  22800. * Detach the current controls from the specified dom element.
  22801. * @param element Defines the element to stop listening the inputs from
  22802. */
  22803. Camera.prototype.detachControl = function (element) {
  22804. };
  22805. /**
  22806. * Update the camera state according to the different inputs gathered during the frame.
  22807. */
  22808. Camera.prototype.update = function () {
  22809. this._checkInputs();
  22810. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22811. this._updateRigCameras();
  22812. }
  22813. };
  22814. /** @hidden */
  22815. Camera.prototype._checkInputs = function () {
  22816. this.onAfterCheckInputsObservable.notifyObservers(this);
  22817. };
  22818. Object.defineProperty(Camera.prototype, "rigCameras", {
  22819. /** @hidden */
  22820. get: function () {
  22821. return this._rigCameras;
  22822. },
  22823. enumerable: true,
  22824. configurable: true
  22825. });
  22826. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22827. get: function () {
  22828. return this._rigPostProcess;
  22829. },
  22830. enumerable: true,
  22831. configurable: true
  22832. });
  22833. /**
  22834. * Internal, gets the first post proces.
  22835. * @returns the first post process to be run on this camera.
  22836. */
  22837. Camera.prototype._getFirstPostProcess = function () {
  22838. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22839. if (this._postProcesses[ppIndex] !== null) {
  22840. return this._postProcesses[ppIndex];
  22841. }
  22842. }
  22843. return null;
  22844. };
  22845. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22846. // invalidate framebuffer
  22847. var firstPostProcess = this._getFirstPostProcess();
  22848. if (firstPostProcess) {
  22849. firstPostProcess.markTextureDirty();
  22850. }
  22851. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22852. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22853. var cam = this._rigCameras[i];
  22854. var rigPostProcess = cam._rigPostProcess;
  22855. // for VR rig, there does not have to be a post process
  22856. if (rigPostProcess) {
  22857. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22858. if (isPass) {
  22859. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22860. cam.isIntermediate = this._postProcesses.length === 0;
  22861. }
  22862. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22863. rigPostProcess.markTextureDirty();
  22864. }
  22865. else {
  22866. cam._postProcesses = this._postProcesses.slice(0);
  22867. }
  22868. }
  22869. };
  22870. /**
  22871. * Attach a post process to the camera.
  22872. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  22873. * @param postProcess The post process to attach to the camera
  22874. * @param insertAt The position of the post process in case several of them are in use in the scene
  22875. * @returns the position the post process has been inserted at
  22876. */
  22877. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22878. if (insertAt === void 0) { insertAt = null; }
  22879. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22880. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22881. return 0;
  22882. }
  22883. if (insertAt == null || insertAt < 0) {
  22884. this._postProcesses.push(postProcess);
  22885. }
  22886. else if (this._postProcesses[insertAt] === null) {
  22887. this._postProcesses[insertAt] = postProcess;
  22888. }
  22889. else {
  22890. this._postProcesses.splice(insertAt, 0, postProcess);
  22891. }
  22892. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22893. return this._postProcesses.indexOf(postProcess);
  22894. };
  22895. /**
  22896. * Detach a post process to the camera.
  22897. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  22898. * @param postProcess The post process to detach from the camera
  22899. */
  22900. Camera.prototype.detachPostProcess = function (postProcess) {
  22901. var idx = this._postProcesses.indexOf(postProcess);
  22902. if (idx !== -1) {
  22903. this._postProcesses[idx] = null;
  22904. }
  22905. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22906. };
  22907. /**
  22908. * Gets the current world matrix of the camera
  22909. */
  22910. Camera.prototype.getWorldMatrix = function () {
  22911. if (this._isSynchronizedViewMatrix()) {
  22912. return this._worldMatrix;
  22913. }
  22914. // Getting the the view matrix will also compute the world matrix.
  22915. this.getViewMatrix();
  22916. return this._worldMatrix;
  22917. };
  22918. /** @hidden */
  22919. Camera.prototype._getViewMatrix = function () {
  22920. return BABYLON.Matrix.Identity();
  22921. };
  22922. /**
  22923. * Gets the current view matrix of the camera.
  22924. * @param force forces the camera to recompute the matrix without looking at the cached state
  22925. * @returns the view matrix
  22926. */
  22927. Camera.prototype.getViewMatrix = function (force) {
  22928. if (!force && this._isSynchronizedViewMatrix()) {
  22929. return this._computedViewMatrix;
  22930. }
  22931. this.updateCache();
  22932. this._computedViewMatrix = this._getViewMatrix();
  22933. this._currentRenderId = this.getScene().getRenderId();
  22934. this._childRenderId = this._currentRenderId;
  22935. this._refreshFrustumPlanes = true;
  22936. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22937. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22938. }
  22939. this.onViewMatrixChangedObservable.notifyObservers(this);
  22940. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22941. return this._computedViewMatrix;
  22942. };
  22943. /**
  22944. * Freeze the projection matrix.
  22945. * It will prevent the cache check of the camera projection compute and can speed up perf
  22946. * if no parameter of the camera are meant to change
  22947. * @param projection Defines manually a projection if necessary
  22948. */
  22949. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22950. this._doNotComputeProjectionMatrix = true;
  22951. if (projection !== undefined) {
  22952. this._projectionMatrix = projection;
  22953. }
  22954. };
  22955. ;
  22956. /**
  22957. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  22958. */
  22959. Camera.prototype.unfreezeProjectionMatrix = function () {
  22960. this._doNotComputeProjectionMatrix = false;
  22961. };
  22962. ;
  22963. /**
  22964. * Gets the current projection matrix of the camera.
  22965. * @param force forces the camera to recompute the matrix without looking at the cached state
  22966. * @returns the projection matrix
  22967. */
  22968. Camera.prototype.getProjectionMatrix = function (force) {
  22969. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22970. return this._projectionMatrix;
  22971. }
  22972. // Cache
  22973. this._cache.mode = this.mode;
  22974. this._cache.minZ = this.minZ;
  22975. this._cache.maxZ = this.maxZ;
  22976. // Matrix
  22977. this._refreshFrustumPlanes = true;
  22978. var engine = this.getEngine();
  22979. var scene = this.getScene();
  22980. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22981. this._cache.fov = this.fov;
  22982. this._cache.fovMode = this.fovMode;
  22983. this._cache.aspectRatio = engine.getAspectRatio(this);
  22984. if (this.minZ <= 0) {
  22985. this.minZ = 0.1;
  22986. }
  22987. if (scene.useRightHandedSystem) {
  22988. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22989. }
  22990. else {
  22991. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22992. }
  22993. }
  22994. else {
  22995. var halfWidth = engine.getRenderWidth() / 2.0;
  22996. var halfHeight = engine.getRenderHeight() / 2.0;
  22997. if (scene.useRightHandedSystem) {
  22998. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22999. }
  23000. else {
  23001. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23002. }
  23003. this._cache.orthoLeft = this.orthoLeft;
  23004. this._cache.orthoRight = this.orthoRight;
  23005. this._cache.orthoBottom = this.orthoBottom;
  23006. this._cache.orthoTop = this.orthoTop;
  23007. this._cache.renderWidth = engine.getRenderWidth();
  23008. this._cache.renderHeight = engine.getRenderHeight();
  23009. }
  23010. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  23011. return this._projectionMatrix;
  23012. };
  23013. /**
  23014. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  23015. * @returns a Matrix
  23016. */
  23017. Camera.prototype.getTransformationMatrix = function () {
  23018. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23019. return this._transformMatrix;
  23020. };
  23021. Camera.prototype._updateFrustumPlanes = function () {
  23022. if (!this._refreshFrustumPlanes) {
  23023. return;
  23024. }
  23025. this.getTransformationMatrix();
  23026. if (!this._frustumPlanes) {
  23027. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23028. }
  23029. else {
  23030. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23031. }
  23032. this._refreshFrustumPlanes = false;
  23033. };
  23034. /**
  23035. * Checks if a cullable object (mesh...) is in the camera frustum
  23036. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  23037. * @param target The object to check
  23038. * @returns true if the object is in frustum otherwise false
  23039. */
  23040. Camera.prototype.isInFrustum = function (target) {
  23041. this._updateFrustumPlanes();
  23042. return target.isInFrustum(this._frustumPlanes);
  23043. };
  23044. /**
  23045. * Checks if a cullable object (mesh...) is in the camera frustum
  23046. * Unlike isInFrustum this cheks the full bounding box
  23047. * @param target The object to check
  23048. * @returns true if the object is in frustum otherwise false
  23049. */
  23050. Camera.prototype.isCompletelyInFrustum = function (target) {
  23051. this._updateFrustumPlanes();
  23052. return target.isCompletelyInFrustum(this._frustumPlanes);
  23053. };
  23054. /**
  23055. * Gets a ray in the forward direction from the camera.
  23056. * @param length Defines the length of the ray to create
  23057. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  23058. * @param origin Defines the start point of the ray which defaults to the camera position
  23059. * @returns the forward ray
  23060. */
  23061. Camera.prototype.getForwardRay = function (length, transform, origin) {
  23062. if (length === void 0) { length = 100; }
  23063. if (!transform) {
  23064. transform = this.getWorldMatrix();
  23065. }
  23066. if (!origin) {
  23067. origin = this.position;
  23068. }
  23069. var forward = new BABYLON.Vector3(0, 0, 1);
  23070. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  23071. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  23072. return new BABYLON.Ray(origin, direction, length);
  23073. };
  23074. /**
  23075. * Releases resources associated with this node.
  23076. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  23077. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  23078. */
  23079. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  23080. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  23081. // Observables
  23082. this.onViewMatrixChangedObservable.clear();
  23083. this.onProjectionMatrixChangedObservable.clear();
  23084. this.onAfterCheckInputsObservable.clear();
  23085. this.onRestoreStateObservable.clear();
  23086. // Inputs
  23087. if (this.inputs) {
  23088. this.inputs.clear();
  23089. }
  23090. // Animations
  23091. this.getScene().stopAnimation(this);
  23092. // Remove from scene
  23093. this.getScene().removeCamera(this);
  23094. while (this._rigCameras.length > 0) {
  23095. var camera = this._rigCameras.pop();
  23096. if (camera) {
  23097. camera.dispose();
  23098. }
  23099. }
  23100. // Postprocesses
  23101. if (this._rigPostProcess) {
  23102. this._rigPostProcess.dispose(this);
  23103. this._rigPostProcess = null;
  23104. this._postProcesses = [];
  23105. }
  23106. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23107. this._rigPostProcess = null;
  23108. this._postProcesses = [];
  23109. }
  23110. else {
  23111. var i = this._postProcesses.length;
  23112. while (--i >= 0) {
  23113. var postProcess = this._postProcesses[i];
  23114. if (postProcess) {
  23115. postProcess.dispose(this);
  23116. }
  23117. }
  23118. }
  23119. // Render targets
  23120. var i = this.customRenderTargets.length;
  23121. while (--i >= 0) {
  23122. this.customRenderTargets[i].dispose();
  23123. }
  23124. this.customRenderTargets = [];
  23125. // Active Meshes
  23126. this._activeMeshes.dispose();
  23127. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23128. };
  23129. Object.defineProperty(Camera.prototype, "leftCamera", {
  23130. /**
  23131. * Gets the left camera of a rig setup in case of Rigged Camera
  23132. */
  23133. get: function () {
  23134. if (this._rigCameras.length < 1) {
  23135. return null;
  23136. }
  23137. return this._rigCameras[0];
  23138. },
  23139. enumerable: true,
  23140. configurable: true
  23141. });
  23142. Object.defineProperty(Camera.prototype, "rightCamera", {
  23143. /**
  23144. * Gets the right camera of a rig setup in case of Rigged Camera
  23145. */
  23146. get: function () {
  23147. if (this._rigCameras.length < 2) {
  23148. return null;
  23149. }
  23150. return this._rigCameras[1];
  23151. },
  23152. enumerable: true,
  23153. configurable: true
  23154. });
  23155. /**
  23156. * Gets the left camera target of a rig setup in case of Rigged Camera
  23157. * @returns the target position
  23158. */
  23159. Camera.prototype.getLeftTarget = function () {
  23160. if (this._rigCameras.length < 1) {
  23161. return null;
  23162. }
  23163. return this._rigCameras[0].getTarget();
  23164. };
  23165. /**
  23166. * Gets the right camera target of a rig setup in case of Rigged Camera
  23167. * @returns the target position
  23168. */
  23169. Camera.prototype.getRightTarget = function () {
  23170. if (this._rigCameras.length < 2) {
  23171. return null;
  23172. }
  23173. return this._rigCameras[1].getTarget();
  23174. };
  23175. /**
  23176. * @hidden
  23177. */
  23178. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  23179. if (this.cameraRigMode === mode) {
  23180. return;
  23181. }
  23182. while (this._rigCameras.length > 0) {
  23183. var camera = this._rigCameras.pop();
  23184. if (camera) {
  23185. camera.dispose();
  23186. }
  23187. }
  23188. this.cameraRigMode = mode;
  23189. this._cameraRigParams = {};
  23190. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23191. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23192. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23193. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23194. // create the rig cameras, unless none
  23195. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23196. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23197. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23198. if (leftCamera && rightCamera) {
  23199. this._rigCameras.push(leftCamera);
  23200. this._rigCameras.push(rightCamera);
  23201. }
  23202. }
  23203. switch (this.cameraRigMode) {
  23204. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23205. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23206. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23207. break;
  23208. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23209. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23210. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23211. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23212. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23213. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23214. break;
  23215. case Camera.RIG_MODE_VR:
  23216. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23217. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23218. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23219. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23220. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23221. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23222. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23223. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23224. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23225. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23226. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23227. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23228. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23229. if (metrics.compensateDistortion) {
  23230. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23231. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23232. }
  23233. break;
  23234. case Camera.RIG_MODE_WEBVR:
  23235. if (rigParams.vrDisplay) {
  23236. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23237. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23238. //Left eye
  23239. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23240. this._rigCameras[0].setCameraRigParameter("left", true);
  23241. //leaving this for future reference
  23242. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23243. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23244. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23245. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23246. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23247. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23248. this._rigCameras[0].parent = this;
  23249. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23250. //Right eye
  23251. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23252. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23253. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23254. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23255. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23256. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23257. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23258. this._rigCameras[1].parent = this;
  23259. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23260. if (Camera.UseAlternateWebVRRendering) {
  23261. this._rigCameras[1]._skipRendering = true;
  23262. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23263. }
  23264. }
  23265. break;
  23266. }
  23267. this._cascadePostProcessesToRigCams();
  23268. this.update();
  23269. };
  23270. Camera.prototype._getVRProjectionMatrix = function () {
  23271. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23272. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23273. return this._projectionMatrix;
  23274. };
  23275. Camera.prototype._updateCameraRotationMatrix = function () {
  23276. //Here for WebVR
  23277. };
  23278. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23279. //Here for WebVR
  23280. };
  23281. /**
  23282. * This function MUST be overwritten by the different WebVR cameras available.
  23283. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23284. */
  23285. Camera.prototype._getWebVRProjectionMatrix = function () {
  23286. return BABYLON.Matrix.Identity();
  23287. };
  23288. /**
  23289. * This function MUST be overwritten by the different WebVR cameras available.
  23290. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23291. */
  23292. Camera.prototype._getWebVRViewMatrix = function () {
  23293. return BABYLON.Matrix.Identity();
  23294. };
  23295. /** @hidden */
  23296. Camera.prototype.setCameraRigParameter = function (name, value) {
  23297. if (!this._cameraRigParams) {
  23298. this._cameraRigParams = {};
  23299. }
  23300. this._cameraRigParams[name] = value;
  23301. //provisionnally:
  23302. if (name === "interaxialDistance") {
  23303. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23304. }
  23305. };
  23306. /**
  23307. * needs to be overridden by children so sub has required properties to be copied
  23308. * @hidden
  23309. */
  23310. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23311. return null;
  23312. };
  23313. /**
  23314. * May need to be overridden by children
  23315. * @hidden
  23316. */
  23317. Camera.prototype._updateRigCameras = function () {
  23318. for (var i = 0; i < this._rigCameras.length; i++) {
  23319. this._rigCameras[i].minZ = this.minZ;
  23320. this._rigCameras[i].maxZ = this.maxZ;
  23321. this._rigCameras[i].fov = this.fov;
  23322. }
  23323. // only update viewport when ANAGLYPH
  23324. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23325. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23326. }
  23327. };
  23328. /** @hidden */
  23329. Camera.prototype._setupInputs = function () {
  23330. };
  23331. /**
  23332. * Serialiaze the camera setup to a json represention
  23333. * @returns the JSON representation
  23334. */
  23335. Camera.prototype.serialize = function () {
  23336. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23337. // Type
  23338. serializationObject.type = this.getClassName();
  23339. // Parent
  23340. if (this.parent) {
  23341. serializationObject.parentId = this.parent.id;
  23342. }
  23343. if (this.inputs) {
  23344. this.inputs.serialize(serializationObject);
  23345. }
  23346. // Animations
  23347. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23348. serializationObject.ranges = this.serializeAnimationRanges();
  23349. return serializationObject;
  23350. };
  23351. /**
  23352. * Clones the current camera.
  23353. * @param name The cloned camera name
  23354. * @returns the cloned camera
  23355. */
  23356. Camera.prototype.clone = function (name) {
  23357. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23358. };
  23359. /**
  23360. * Gets the direction of the camera relative to a given local axis.
  23361. * @param localAxis Defines the reference axis to provide a relative direction.
  23362. * @return the direction
  23363. */
  23364. Camera.prototype.getDirection = function (localAxis) {
  23365. var result = BABYLON.Vector3.Zero();
  23366. this.getDirectionToRef(localAxis, result);
  23367. return result;
  23368. };
  23369. /**
  23370. * Gets the direction of the camera relative to a given local axis into a passed vector.
  23371. * @param localAxis Defines the reference axis to provide a relative direction.
  23372. * @param result Defines the vector to store the result in
  23373. */
  23374. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23375. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23376. };
  23377. /**
  23378. * Gets a camera constructor for a given camera type
  23379. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  23380. * @param name The name of the camera the result will be able to instantiate
  23381. * @param scene The scene the result will construct the camera in
  23382. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  23383. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  23384. * @returns a factory method to construc the camera
  23385. */
  23386. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23387. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23388. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23389. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  23390. interaxial_distance: interaxial_distance,
  23391. isStereoscopicSideBySide: isStereoscopicSideBySide
  23392. });
  23393. if (constructorFunc) {
  23394. return constructorFunc;
  23395. }
  23396. // Default to universal camera
  23397. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23398. };
  23399. /**
  23400. * Compute the world matrix of the camera.
  23401. * @returns the camera workd matrix
  23402. */
  23403. Camera.prototype.computeWorldMatrix = function () {
  23404. return this.getWorldMatrix();
  23405. };
  23406. /**
  23407. * Parse a JSON and creates the camera from the parsed information
  23408. * @param parsedCamera The JSON to parse
  23409. * @param scene The scene to instantiate the camera in
  23410. * @returns the newly constructed camera
  23411. */
  23412. Camera.Parse = function (parsedCamera, scene) {
  23413. var type = parsedCamera.type;
  23414. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23415. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23416. // Parent
  23417. if (parsedCamera.parentId) {
  23418. camera._waitingParentId = parsedCamera.parentId;
  23419. }
  23420. //If camera has an input manager, let it parse inputs settings
  23421. if (camera.inputs) {
  23422. camera.inputs.parse(parsedCamera);
  23423. camera._setupInputs();
  23424. }
  23425. if (camera.setPosition) { // need to force position
  23426. camera.position.copyFromFloats(0, 0, 0);
  23427. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23428. }
  23429. // Target
  23430. if (parsedCamera.target) {
  23431. if (camera.setTarget) {
  23432. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23433. }
  23434. }
  23435. // Apply 3d rig, when found
  23436. if (parsedCamera.cameraRigMode) {
  23437. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23438. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23439. }
  23440. // Animations
  23441. if (parsedCamera.animations) {
  23442. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23443. var parsedAnimation = parsedCamera.animations[animationIndex];
  23444. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23445. }
  23446. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23447. }
  23448. if (parsedCamera.autoAnimate) {
  23449. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23450. }
  23451. return camera;
  23452. };
  23453. /**
  23454. * This is the default projection mode used by the cameras.
  23455. * It helps recreating a feeling of perspective and better appreciate depth.
  23456. * This is the best way to simulate real life cameras.
  23457. */
  23458. Camera.PERSPECTIVE_CAMERA = 0;
  23459. /**
  23460. * This helps creating camera with an orthographic mode.
  23461. * 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.
  23462. */
  23463. Camera.ORTHOGRAPHIC_CAMERA = 1;
  23464. /**
  23465. * This is the default FOV mode for perspective cameras.
  23466. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  23467. */
  23468. Camera.FOVMODE_VERTICAL_FIXED = 0;
  23469. /**
  23470. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  23471. */
  23472. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  23473. /**
  23474. * This specifies ther is no need for a camera rig.
  23475. * Basically only one eye is rendered corresponding to the camera.
  23476. */
  23477. Camera.RIG_MODE_NONE = 0;
  23478. /**
  23479. * Simulates a camera Rig with one blue eye and one red eye.
  23480. * This can be use with 3d blue and red glasses.
  23481. */
  23482. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23483. /**
  23484. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  23485. */
  23486. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23487. /**
  23488. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  23489. */
  23490. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23491. /**
  23492. * Defines that both eyes of the camera will be rendered over under each other.
  23493. */
  23494. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23495. /**
  23496. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  23497. */
  23498. Camera.RIG_MODE_VR = 20;
  23499. /**
  23500. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  23501. */
  23502. Camera.RIG_MODE_WEBVR = 21;
  23503. /**
  23504. * Defines if by default attaching controls should prevent the default javascript event to continue.
  23505. */
  23506. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23507. /**
  23508. * @hidden
  23509. * Might be removed once multiview will be a thing
  23510. */
  23511. Camera.UseAlternateWebVRRendering = false;
  23512. __decorate([
  23513. BABYLON.serializeAsVector3()
  23514. ], Camera.prototype, "position", void 0);
  23515. __decorate([
  23516. BABYLON.serializeAsVector3()
  23517. ], Camera.prototype, "upVector", void 0);
  23518. __decorate([
  23519. BABYLON.serialize()
  23520. ], Camera.prototype, "orthoLeft", void 0);
  23521. __decorate([
  23522. BABYLON.serialize()
  23523. ], Camera.prototype, "orthoRight", void 0);
  23524. __decorate([
  23525. BABYLON.serialize()
  23526. ], Camera.prototype, "orthoBottom", void 0);
  23527. __decorate([
  23528. BABYLON.serialize()
  23529. ], Camera.prototype, "orthoTop", void 0);
  23530. __decorate([
  23531. BABYLON.serialize()
  23532. ], Camera.prototype, "fov", void 0);
  23533. __decorate([
  23534. BABYLON.serialize()
  23535. ], Camera.prototype, "minZ", void 0);
  23536. __decorate([
  23537. BABYLON.serialize()
  23538. ], Camera.prototype, "maxZ", void 0);
  23539. __decorate([
  23540. BABYLON.serialize()
  23541. ], Camera.prototype, "inertia", void 0);
  23542. __decorate([
  23543. BABYLON.serialize()
  23544. ], Camera.prototype, "mode", void 0);
  23545. __decorate([
  23546. BABYLON.serialize()
  23547. ], Camera.prototype, "layerMask", void 0);
  23548. __decorate([
  23549. BABYLON.serialize()
  23550. ], Camera.prototype, "fovMode", void 0);
  23551. __decorate([
  23552. BABYLON.serialize()
  23553. ], Camera.prototype, "cameraRigMode", void 0);
  23554. __decorate([
  23555. BABYLON.serialize()
  23556. ], Camera.prototype, "interaxialDistance", void 0);
  23557. __decorate([
  23558. BABYLON.serialize()
  23559. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23560. return Camera;
  23561. }(BABYLON.Node));
  23562. BABYLON.Camera = Camera;
  23563. })(BABYLON || (BABYLON = {}));
  23564. //# sourceMappingURL=babylon.camera.js.map
  23565. var BABYLON;
  23566. (function (BABYLON) {
  23567. /**
  23568. * This is the manager responsible of all the rendering for meshes sprites and particles.
  23569. * It is enable to manage the different groups as well as the different necessary sort functions.
  23570. * This should not be used directly aside of the few static configurations
  23571. */
  23572. var RenderingManager = /** @class */ (function () {
  23573. /**
  23574. * Instantiates a new rendering group for a particular scene
  23575. * @param scene Defines the scene the groups belongs to
  23576. */
  23577. function RenderingManager(scene) {
  23578. /**
  23579. * @hidden
  23580. */
  23581. this._useSceneAutoClearSetup = false;
  23582. this._renderingGroups = new Array();
  23583. this._autoClearDepthStencil = {};
  23584. this._customOpaqueSortCompareFn = {};
  23585. this._customAlphaTestSortCompareFn = {};
  23586. this._customTransparentSortCompareFn = {};
  23587. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23588. this._scene = scene;
  23589. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23590. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23591. }
  23592. }
  23593. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23594. if (depth === void 0) { depth = true; }
  23595. if (stencil === void 0) { stencil = true; }
  23596. if (this._depthStencilBufferAlreadyCleaned) {
  23597. return;
  23598. }
  23599. this._scene.getEngine().clear(null, false, depth, stencil);
  23600. this._depthStencilBufferAlreadyCleaned = true;
  23601. };
  23602. /**
  23603. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  23604. * @hidden
  23605. */
  23606. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23607. // Update the observable context (not null as it only goes away on dispose)
  23608. var info = this._renderingGroupInfo;
  23609. info.scene = this._scene;
  23610. info.camera = this._scene.activeCamera;
  23611. // Dispatch sprites
  23612. if (this._scene.spriteManagers && renderSprites) {
  23613. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23614. var manager = this._scene.spriteManagers[index];
  23615. this.dispatchSprites(manager);
  23616. }
  23617. }
  23618. // Render
  23619. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23620. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23621. var renderingGroup = this._renderingGroups[index];
  23622. if (!renderingGroup)
  23623. continue;
  23624. var renderingGroupMask = Math.pow(2, index);
  23625. info.renderingGroupId = index;
  23626. // Before Observable
  23627. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23628. // Clear depth/stencil if needed
  23629. if (RenderingManager.AUTOCLEAR) {
  23630. var autoClear = this._useSceneAutoClearSetup ?
  23631. this._scene.getAutoClearDepthStencilSetup(index) :
  23632. this._autoClearDepthStencil[index];
  23633. if (autoClear && autoClear.autoClear) {
  23634. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23635. }
  23636. }
  23637. // Render
  23638. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23639. var step = _a[_i];
  23640. step.action(index);
  23641. }
  23642. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23643. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23644. var step = _c[_b];
  23645. step.action(index);
  23646. }
  23647. // After Observable
  23648. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23649. }
  23650. };
  23651. /**
  23652. * Resets the different information of the group to prepare a new frame
  23653. * @hidden
  23654. */
  23655. RenderingManager.prototype.reset = function () {
  23656. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23657. var renderingGroup = this._renderingGroups[index];
  23658. if (renderingGroup) {
  23659. renderingGroup.prepare();
  23660. }
  23661. }
  23662. };
  23663. /**
  23664. * Dispose and release the group and its associated resources.
  23665. * @hidden
  23666. */
  23667. RenderingManager.prototype.dispose = function () {
  23668. this.freeRenderingGroups();
  23669. this._renderingGroups.length = 0;
  23670. this._renderingGroupInfo = null;
  23671. };
  23672. /**
  23673. * Clear the info related to rendering groups preventing retention points during dispose.
  23674. */
  23675. RenderingManager.prototype.freeRenderingGroups = function () {
  23676. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23677. var renderingGroup = this._renderingGroups[index];
  23678. if (renderingGroup) {
  23679. renderingGroup.dispose();
  23680. }
  23681. }
  23682. };
  23683. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23684. if (this._renderingGroups[renderingGroupId] === undefined) {
  23685. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23686. }
  23687. };
  23688. /**
  23689. * Add a sprite manager to the rendering manager in order to render it this frame.
  23690. * @param spriteManager Define the sprite manager to render
  23691. */
  23692. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23693. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23694. this._prepareRenderingGroup(renderingGroupId);
  23695. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23696. };
  23697. /**
  23698. * Add a particle system to the rendering manager in order to render it this frame.
  23699. * @param particleSystem Define the particle system to render
  23700. */
  23701. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23702. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23703. this._prepareRenderingGroup(renderingGroupId);
  23704. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23705. };
  23706. /**
  23707. * Add a submesh to the manager in order to render it this frame
  23708. * @param subMesh The submesh to dispatch
  23709. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23710. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23711. */
  23712. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23713. if (mesh === undefined) {
  23714. mesh = subMesh.getMesh();
  23715. }
  23716. var renderingGroupId = mesh.renderingGroupId || 0;
  23717. this._prepareRenderingGroup(renderingGroupId);
  23718. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23719. };
  23720. /**
  23721. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23722. * This allowed control for front to back rendering or reversly depending of the special needs.
  23723. *
  23724. * @param renderingGroupId The rendering group id corresponding to its index
  23725. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23726. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23727. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23728. */
  23729. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23730. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23731. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23732. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23733. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23734. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23735. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23736. if (this._renderingGroups[renderingGroupId]) {
  23737. var group = this._renderingGroups[renderingGroupId];
  23738. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23739. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23740. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23741. }
  23742. };
  23743. /**
  23744. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23745. *
  23746. * @param renderingGroupId The rendering group id corresponding to its index
  23747. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23748. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23749. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23750. */
  23751. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23752. if (depth === void 0) { depth = true; }
  23753. if (stencil === void 0) { stencil = true; }
  23754. this._autoClearDepthStencil[renderingGroupId] = {
  23755. autoClear: autoClearDepthStencil,
  23756. depth: depth,
  23757. stencil: stencil
  23758. };
  23759. };
  23760. /**
  23761. * Gets the current auto clear configuration for one rendering group of the rendering
  23762. * manager.
  23763. * @param index the rendering group index to get the information for
  23764. * @returns The auto clear setup for the requested rendering group
  23765. */
  23766. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23767. return this._autoClearDepthStencil[index];
  23768. };
  23769. /**
  23770. * The max id used for rendering groups (not included)
  23771. */
  23772. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23773. /**
  23774. * The min id used for rendering groups (included)
  23775. */
  23776. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23777. /**
  23778. * Used to globally prevent autoclearing scenes.
  23779. */
  23780. RenderingManager.AUTOCLEAR = true;
  23781. return RenderingManager;
  23782. }());
  23783. BABYLON.RenderingManager = RenderingManager;
  23784. })(BABYLON || (BABYLON = {}));
  23785. //# sourceMappingURL=babylon.renderingManager.js.map
  23786. var BABYLON;
  23787. (function (BABYLON) {
  23788. /**
  23789. * This represents the object necessary to create a rendering group.
  23790. * This is exclusively used and created by the rendering manager.
  23791. * To modify the behavior, you use the available helpers in your scene or meshes.
  23792. * @hidden
  23793. */
  23794. var RenderingGroup = /** @class */ (function () {
  23795. /**
  23796. * Creates a new rendering group.
  23797. * @param index The rendering group index
  23798. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23799. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23800. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23801. */
  23802. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23803. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23804. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23805. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23806. this.index = index;
  23807. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23808. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23809. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23810. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23811. this._particleSystems = new BABYLON.SmartArray(256);
  23812. this._spriteManagers = new BABYLON.SmartArray(256);
  23813. this._edgesRenderers = new BABYLON.SmartArray(16);
  23814. this._scene = scene;
  23815. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23816. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23817. this.transparentSortCompareFn = transparentSortCompareFn;
  23818. }
  23819. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23820. /**
  23821. * Set the opaque sort comparison function.
  23822. * If null the sub meshes will be render in the order they were created
  23823. */
  23824. set: function (value) {
  23825. this._opaqueSortCompareFn = value;
  23826. if (value) {
  23827. this._renderOpaque = this.renderOpaqueSorted;
  23828. }
  23829. else {
  23830. this._renderOpaque = RenderingGroup.renderUnsorted;
  23831. }
  23832. },
  23833. enumerable: true,
  23834. configurable: true
  23835. });
  23836. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23837. /**
  23838. * Set the alpha test sort comparison function.
  23839. * If null the sub meshes will be render in the order they were created
  23840. */
  23841. set: function (value) {
  23842. this._alphaTestSortCompareFn = value;
  23843. if (value) {
  23844. this._renderAlphaTest = this.renderAlphaTestSorted;
  23845. }
  23846. else {
  23847. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23848. }
  23849. },
  23850. enumerable: true,
  23851. configurable: true
  23852. });
  23853. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23854. /**
  23855. * Set the transparent sort comparison function.
  23856. * If null the sub meshes will be render in the order they were created
  23857. */
  23858. set: function (value) {
  23859. if (value) {
  23860. this._transparentSortCompareFn = value;
  23861. }
  23862. else {
  23863. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23864. }
  23865. this._renderTransparent = this.renderTransparentSorted;
  23866. },
  23867. enumerable: true,
  23868. configurable: true
  23869. });
  23870. /**
  23871. * Render all the sub meshes contained in the group.
  23872. * @param customRenderFunction Used to override the default render behaviour of the group.
  23873. * @returns true if rendered some submeshes.
  23874. */
  23875. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23876. if (customRenderFunction) {
  23877. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23878. return;
  23879. }
  23880. var engine = this._scene.getEngine();
  23881. // Depth only
  23882. if (this._depthOnlySubMeshes.length !== 0) {
  23883. engine.setColorWrite(false);
  23884. this._renderAlphaTest(this._depthOnlySubMeshes);
  23885. engine.setColorWrite(true);
  23886. }
  23887. // Opaque
  23888. if (this._opaqueSubMeshes.length !== 0) {
  23889. this._renderOpaque(this._opaqueSubMeshes);
  23890. }
  23891. // Alpha test
  23892. if (this._alphaTestSubMeshes.length !== 0) {
  23893. this._renderAlphaTest(this._alphaTestSubMeshes);
  23894. }
  23895. var stencilState = engine.getStencilBuffer();
  23896. engine.setStencilBuffer(false);
  23897. // Sprites
  23898. if (renderSprites) {
  23899. this._renderSprites();
  23900. }
  23901. // Particles
  23902. if (renderParticles) {
  23903. this._renderParticles(activeMeshes);
  23904. }
  23905. if (this.onBeforeTransparentRendering) {
  23906. this.onBeforeTransparentRendering();
  23907. }
  23908. // Transparent
  23909. if (this._transparentSubMeshes.length !== 0) {
  23910. this._renderTransparent(this._transparentSubMeshes);
  23911. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23912. }
  23913. // Set back stencil to false in case it changes before the edge renderer.
  23914. engine.setStencilBuffer(false);
  23915. // Edges
  23916. if (this._edgesRenderers.length) {
  23917. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23918. this._edgesRenderers.data[edgesRendererIndex].render();
  23919. }
  23920. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23921. }
  23922. // Restore Stencil state.
  23923. engine.setStencilBuffer(stencilState);
  23924. };
  23925. /**
  23926. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23927. * @param subMeshes The submeshes to render
  23928. */
  23929. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23930. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23931. };
  23932. /**
  23933. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23934. * @param subMeshes The submeshes to render
  23935. */
  23936. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23937. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23938. };
  23939. /**
  23940. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23941. * @param subMeshes The submeshes to render
  23942. */
  23943. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23944. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23945. };
  23946. /**
  23947. * Renders the submeshes in a specified order.
  23948. * @param subMeshes The submeshes to sort before render
  23949. * @param sortCompareFn The comparison function use to sort
  23950. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23951. * @param transparent Specifies to activate blending if true
  23952. */
  23953. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23954. var subIndex = 0;
  23955. var subMesh;
  23956. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23957. for (; subIndex < subMeshes.length; subIndex++) {
  23958. subMesh = subMeshes.data[subIndex];
  23959. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23960. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23961. }
  23962. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23963. if (sortCompareFn) {
  23964. sortedArray.sort(sortCompareFn);
  23965. }
  23966. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23967. subMesh = sortedArray[subIndex];
  23968. if (transparent) {
  23969. var material = subMesh.getMaterial();
  23970. if (material && material.needDepthPrePass) {
  23971. var engine = material.getScene().getEngine();
  23972. engine.setColorWrite(false);
  23973. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23974. subMesh.render(false);
  23975. engine.setColorWrite(true);
  23976. }
  23977. }
  23978. subMesh.render(transparent);
  23979. }
  23980. };
  23981. /**
  23982. * Renders the submeshes in the order they were dispatched (no sort applied).
  23983. * @param subMeshes The submeshes to render
  23984. */
  23985. RenderingGroup.renderUnsorted = function (subMeshes) {
  23986. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23987. var submesh = subMeshes.data[subIndex];
  23988. submesh.render(false);
  23989. }
  23990. };
  23991. /**
  23992. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23993. * are rendered back to front if in the same alpha index.
  23994. *
  23995. * @param a The first submesh
  23996. * @param b The second submesh
  23997. * @returns The result of the comparison
  23998. */
  23999. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  24000. // Alpha index first
  24001. if (a._alphaIndex > b._alphaIndex) {
  24002. return 1;
  24003. }
  24004. if (a._alphaIndex < b._alphaIndex) {
  24005. return -1;
  24006. }
  24007. // Then distance to camera
  24008. return RenderingGroup.backToFrontSortCompare(a, b);
  24009. };
  24010. /**
  24011. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24012. * are rendered back to front.
  24013. *
  24014. * @param a The first submesh
  24015. * @param b The second submesh
  24016. * @returns The result of the comparison
  24017. */
  24018. RenderingGroup.backToFrontSortCompare = function (a, b) {
  24019. // Then distance to camera
  24020. if (a._distanceToCamera < b._distanceToCamera) {
  24021. return 1;
  24022. }
  24023. if (a._distanceToCamera > b._distanceToCamera) {
  24024. return -1;
  24025. }
  24026. return 0;
  24027. };
  24028. /**
  24029. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24030. * are rendered front to back (prevent overdraw).
  24031. *
  24032. * @param a The first submesh
  24033. * @param b The second submesh
  24034. * @returns The result of the comparison
  24035. */
  24036. RenderingGroup.frontToBackSortCompare = function (a, b) {
  24037. // Then distance to camera
  24038. if (a._distanceToCamera < b._distanceToCamera) {
  24039. return -1;
  24040. }
  24041. if (a._distanceToCamera > b._distanceToCamera) {
  24042. return 1;
  24043. }
  24044. return 0;
  24045. };
  24046. /**
  24047. * Resets the different lists of submeshes to prepare a new frame.
  24048. */
  24049. RenderingGroup.prototype.prepare = function () {
  24050. this._opaqueSubMeshes.reset();
  24051. this._transparentSubMeshes.reset();
  24052. this._alphaTestSubMeshes.reset();
  24053. this._depthOnlySubMeshes.reset();
  24054. this._particleSystems.reset();
  24055. this._spriteManagers.reset();
  24056. this._edgesRenderers.reset();
  24057. };
  24058. RenderingGroup.prototype.dispose = function () {
  24059. this._opaqueSubMeshes.dispose();
  24060. this._transparentSubMeshes.dispose();
  24061. this._alphaTestSubMeshes.dispose();
  24062. this._depthOnlySubMeshes.dispose();
  24063. this._particleSystems.dispose();
  24064. this._spriteManagers.dispose();
  24065. this._edgesRenderers.dispose();
  24066. };
  24067. /**
  24068. * Inserts the submesh in its correct queue depending on its material.
  24069. * @param subMesh The submesh to dispatch
  24070. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24071. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24072. */
  24073. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  24074. // Get mesh and materials if not provided
  24075. if (mesh === undefined) {
  24076. mesh = subMesh.getMesh();
  24077. }
  24078. if (material === undefined) {
  24079. material = subMesh.getMaterial();
  24080. }
  24081. if (material === null || material === undefined) {
  24082. return;
  24083. }
  24084. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  24085. this._transparentSubMeshes.push(subMesh);
  24086. }
  24087. else if (material.needAlphaTesting()) { // Alpha test
  24088. if (material.needDepthPrePass) {
  24089. this._depthOnlySubMeshes.push(subMesh);
  24090. }
  24091. this._alphaTestSubMeshes.push(subMesh);
  24092. }
  24093. else {
  24094. if (material.needDepthPrePass) {
  24095. this._depthOnlySubMeshes.push(subMesh);
  24096. }
  24097. this._opaqueSubMeshes.push(subMesh); // Opaque
  24098. }
  24099. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  24100. this._edgesRenderers.push(mesh._edgesRenderer);
  24101. }
  24102. };
  24103. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  24104. this._spriteManagers.push(spriteManager);
  24105. };
  24106. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  24107. this._particleSystems.push(particleSystem);
  24108. };
  24109. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  24110. if (this._particleSystems.length === 0) {
  24111. return;
  24112. }
  24113. // Particles
  24114. var activeCamera = this._scene.activeCamera;
  24115. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  24116. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  24117. var particleSystem = this._particleSystems.data[particleIndex];
  24118. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  24119. continue;
  24120. }
  24121. var emitter = particleSystem.emitter;
  24122. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  24123. this._scene._activeParticles.addCount(particleSystem.render(), false);
  24124. }
  24125. }
  24126. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  24127. };
  24128. RenderingGroup.prototype._renderSprites = function () {
  24129. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  24130. return;
  24131. }
  24132. // Sprites
  24133. var activeCamera = this._scene.activeCamera;
  24134. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  24135. for (var id = 0; id < this._spriteManagers.length; id++) {
  24136. var spriteManager = this._spriteManagers.data[id];
  24137. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  24138. spriteManager.render();
  24139. }
  24140. }
  24141. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  24142. };
  24143. return RenderingGroup;
  24144. }());
  24145. BABYLON.RenderingGroup = RenderingGroup;
  24146. })(BABYLON || (BABYLON = {}));
  24147. //# sourceMappingURL=babylon.renderingGroup.js.map
  24148. var BABYLON;
  24149. (function (BABYLON) {
  24150. /**
  24151. * Groups all the scene component constants in one place to ease maintenance.
  24152. * @hidden
  24153. */
  24154. var SceneComponentConstants = /** @class */ (function () {
  24155. function SceneComponentConstants() {
  24156. }
  24157. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  24158. SceneComponentConstants.NAME_LAYER = "Layer";
  24159. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  24160. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  24161. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  24162. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  24163. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  24164. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  24165. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  24166. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  24167. SceneComponentConstants.NAME_SPRITE = "Sprite";
  24168. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  24169. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  24170. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  24171. SceneComponentConstants.NAME_OCTREE = "Octree";
  24172. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  24173. SceneComponentConstants.NAME_AUDIO = "Audio";
  24174. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  24175. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24176. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  24177. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24178. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  24179. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  24180. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  24181. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  24182. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  24183. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  24184. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  24185. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  24186. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  24187. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  24188. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  24189. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  24190. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  24191. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  24192. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  24193. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  24194. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  24195. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  24196. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  24197. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  24198. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  24199. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  24200. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  24201. return SceneComponentConstants;
  24202. }());
  24203. BABYLON.SceneComponentConstants = SceneComponentConstants;
  24204. /**
  24205. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  24206. * @hidden
  24207. */
  24208. var Stage = /** @class */ (function (_super) {
  24209. __extends(Stage, _super);
  24210. /**
  24211. * Hide ctor from the rest of the world.
  24212. * @param items The items to add.
  24213. */
  24214. function Stage(items) {
  24215. return _super.apply(this, items) || this;
  24216. }
  24217. /**
  24218. * Creates a new Stage.
  24219. * @returns A new instance of a Stage
  24220. */
  24221. Stage.Create = function () {
  24222. return Object.create(Stage.prototype);
  24223. };
  24224. /**
  24225. * Registers a step in an ordered way in the targeted stage.
  24226. * @param index Defines the position to register the step in
  24227. * @param component Defines the component attached to the step
  24228. * @param action Defines the action to launch during the step
  24229. */
  24230. Stage.prototype.registerStep = function (index, component, action) {
  24231. var i = 0;
  24232. var maxIndex = Number.MAX_VALUE;
  24233. for (; i < this.length && i < maxIndex; i++) {
  24234. var step = this[i];
  24235. maxIndex = step.index;
  24236. }
  24237. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  24238. };
  24239. /**
  24240. * Clears all the steps from the stage.
  24241. */
  24242. Stage.prototype.clear = function () {
  24243. this.length = 0;
  24244. };
  24245. return Stage;
  24246. }(Array));
  24247. BABYLON.Stage = Stage;
  24248. })(BABYLON || (BABYLON = {}));
  24249. //# sourceMappingURL=babylon.sceneComponent.js.map
  24250. var BABYLON;
  24251. (function (BABYLON) {
  24252. /**
  24253. * Base class of the scene acting as a container for the different elements composing a scene.
  24254. * This class is dynamically extended by the different components of the scene increasing
  24255. * flexibility and reducing coupling
  24256. */
  24257. var AbstractScene = /** @class */ (function () {
  24258. function AbstractScene() {
  24259. /**
  24260. * Gets the list of root nodes (ie. nodes with no parent)
  24261. */
  24262. this.rootNodes = new Array();
  24263. /** All of the cameras added to this scene
  24264. * @see http://doc.babylonjs.com/babylon101/cameras
  24265. */
  24266. this.cameras = new Array();
  24267. /**
  24268. * All of the lights added to this scene
  24269. * @see http://doc.babylonjs.com/babylon101/lights
  24270. */
  24271. this.lights = new Array();
  24272. /**
  24273. * All of the (abstract) meshes added to this scene
  24274. */
  24275. this.meshes = new Array();
  24276. /**
  24277. * The list of skeletons added to the scene
  24278. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24279. */
  24280. this.skeletons = new Array();
  24281. /**
  24282. * All of the particle systems added to this scene
  24283. * @see http://doc.babylonjs.com/babylon101/particles
  24284. */
  24285. this.particleSystems = new Array();
  24286. /**
  24287. * Gets a list of Animations associated with the scene
  24288. */
  24289. this.animations = [];
  24290. /**
  24291. * All of the animation groups added to this scene
  24292. * @see http://doc.babylonjs.com/how_to/group
  24293. */
  24294. this.animationGroups = new Array();
  24295. /**
  24296. * All of the multi-materials added to this scene
  24297. * @see http://doc.babylonjs.com/how_to/multi_materials
  24298. */
  24299. this.multiMaterials = new Array();
  24300. /**
  24301. * All of the materials added to this scene
  24302. * @see http://doc.babylonjs.com/babylon101/materials
  24303. */
  24304. this.materials = new Array();
  24305. /**
  24306. * The list of morph target managers added to the scene
  24307. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24308. */
  24309. this.morphTargetManagers = new Array();
  24310. /**
  24311. * The list of geometries used in the scene.
  24312. */
  24313. this.geometries = new Array();
  24314. /**
  24315. * All of the tranform nodes added to this scene
  24316. * @see http://doc.babylonjs.com/how_to/transformnode
  24317. */
  24318. this.transformNodes = new Array();
  24319. /**
  24320. * ActionManagers available on the scene.
  24321. */
  24322. this.actionManagers = new Array();
  24323. /**
  24324. * Textures to keep.
  24325. */
  24326. this.textures = new Array();
  24327. }
  24328. /**
  24329. * Adds a parser in the list of available ones
  24330. * @param name Defines the name of the parser
  24331. * @param parser Defines the parser to add
  24332. */
  24333. AbstractScene.AddParser = function (name, parser) {
  24334. this._BabylonFileParsers[name] = parser;
  24335. };
  24336. /**
  24337. * Gets a general parser from the list of avaialble ones
  24338. * @param name Defines the name of the parser
  24339. * @returns the requested parser or null
  24340. */
  24341. AbstractScene.GetParser = function (name) {
  24342. if (this._BabylonFileParsers[name]) {
  24343. return this._BabylonFileParsers[name];
  24344. }
  24345. return null;
  24346. };
  24347. /**
  24348. * Adds n individual parser in the list of available ones
  24349. * @param name Defines the name of the parser
  24350. * @param parser Defines the parser to add
  24351. */
  24352. AbstractScene.AddIndividualParser = function (name, parser) {
  24353. this._IndividualBabylonFileParsers[name] = parser;
  24354. };
  24355. /**
  24356. * Gets an individual parser from the list of avaialble ones
  24357. * @param name Defines the name of the parser
  24358. * @returns the requested parser or null
  24359. */
  24360. AbstractScene.GetIndividualParser = function (name) {
  24361. if (this._IndividualBabylonFileParsers[name]) {
  24362. return this._IndividualBabylonFileParsers[name];
  24363. }
  24364. return null;
  24365. };
  24366. /**
  24367. * Parser json data and populate both a scene and its associated container object
  24368. * @param jsonData Defines the data to parse
  24369. * @param scene Defines the scene to parse the data for
  24370. * @param container Defines the container attached to the parsing sequence
  24371. * @param rootUrl Defines the root url of the data
  24372. */
  24373. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  24374. for (var parserName in this._BabylonFileParsers) {
  24375. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  24376. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  24377. }
  24378. }
  24379. };
  24380. /**
  24381. * Stores the list of available parsers in the application.
  24382. */
  24383. AbstractScene._BabylonFileParsers = {};
  24384. /**
  24385. * Stores the list of available individual parsers in the application.
  24386. */
  24387. AbstractScene._IndividualBabylonFileParsers = {};
  24388. return AbstractScene;
  24389. }());
  24390. BABYLON.AbstractScene = AbstractScene;
  24391. })(BABYLON || (BABYLON = {}));
  24392. //# sourceMappingURL=babylon.abstractScene.js.map
  24393. var BABYLON;
  24394. (function (BABYLON) {
  24395. /** @hidden */
  24396. var ClickInfo = /** @class */ (function () {
  24397. function ClickInfo() {
  24398. this._singleClick = false;
  24399. this._doubleClick = false;
  24400. this._hasSwiped = false;
  24401. this._ignore = false;
  24402. }
  24403. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  24404. get: function () {
  24405. return this._singleClick;
  24406. },
  24407. set: function (b) {
  24408. this._singleClick = b;
  24409. },
  24410. enumerable: true,
  24411. configurable: true
  24412. });
  24413. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  24414. get: function () {
  24415. return this._doubleClick;
  24416. },
  24417. set: function (b) {
  24418. this._doubleClick = b;
  24419. },
  24420. enumerable: true,
  24421. configurable: true
  24422. });
  24423. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  24424. get: function () {
  24425. return this._hasSwiped;
  24426. },
  24427. set: function (b) {
  24428. this._hasSwiped = b;
  24429. },
  24430. enumerable: true,
  24431. configurable: true
  24432. });
  24433. Object.defineProperty(ClickInfo.prototype, "ignore", {
  24434. get: function () {
  24435. return this._ignore;
  24436. },
  24437. set: function (b) {
  24438. this._ignore = b;
  24439. },
  24440. enumerable: true,
  24441. configurable: true
  24442. });
  24443. return ClickInfo;
  24444. }());
  24445. /**
  24446. * This class is used by the onRenderingGroupObservable
  24447. */
  24448. var RenderingGroupInfo = /** @class */ (function () {
  24449. function RenderingGroupInfo() {
  24450. }
  24451. return RenderingGroupInfo;
  24452. }());
  24453. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24454. /**
  24455. * Represents a scene to be rendered by the engine.
  24456. * @see http://doc.babylonjs.com/features/scene
  24457. */
  24458. var Scene = /** @class */ (function (_super) {
  24459. __extends(Scene, _super);
  24460. /**
  24461. * Creates a new Scene
  24462. * @param engine defines the engine to use to render this scene
  24463. */
  24464. function Scene(engine) {
  24465. var _this = _super.call(this) || this;
  24466. // Members
  24467. /**
  24468. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24469. */
  24470. _this.autoClear = true;
  24471. /**
  24472. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24473. */
  24474. _this.autoClearDepthAndStencil = true;
  24475. /**
  24476. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24477. */
  24478. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24479. /**
  24480. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24481. */
  24482. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24483. _this._forceWireframe = false;
  24484. _this._forcePointsCloud = false;
  24485. /**
  24486. * Gets or sets a boolean indicating if animations are enabled
  24487. */
  24488. _this.animationsEnabled = true;
  24489. _this._animationPropertiesOverride = null;
  24490. /**
  24491. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24492. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24493. */
  24494. _this.useConstantAnimationDeltaTime = false;
  24495. /**
  24496. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24497. * Please note that it requires to run a ray cast through the scene on every frame
  24498. */
  24499. _this.constantlyUpdateMeshUnderPointer = false;
  24500. /**
  24501. * Defines the HTML cursor to use when hovering over interactive elements
  24502. */
  24503. _this.hoverCursor = "pointer";
  24504. /**
  24505. * Defines the HTML default cursor to use (empty by default)
  24506. */
  24507. _this.defaultCursor = "";
  24508. /**
  24509. * This is used to call preventDefault() on pointer down
  24510. * in order to block unwanted artifacts like system double clicks
  24511. */
  24512. _this.preventDefaultOnPointerDown = true;
  24513. // Metadata
  24514. /**
  24515. * Gets or sets user defined metadata
  24516. */
  24517. _this.metadata = null;
  24518. /**
  24519. * Use this array to add regular expressions used to disable offline support for specific urls
  24520. */
  24521. _this.disableOfflineSupportExceptionRules = new Array();
  24522. /**
  24523. * An event triggered when the scene is disposed.
  24524. */
  24525. _this.onDisposeObservable = new BABYLON.Observable();
  24526. _this._onDisposeObserver = null;
  24527. /**
  24528. * An event triggered before rendering the scene (right after animations and physics)
  24529. */
  24530. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24531. _this._onBeforeRenderObserver = null;
  24532. /**
  24533. * An event triggered after rendering the scene
  24534. */
  24535. _this.onAfterRenderObservable = new BABYLON.Observable();
  24536. _this._onAfterRenderObserver = null;
  24537. /**
  24538. * An event triggered before animating the scene
  24539. */
  24540. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24541. /**
  24542. * An event triggered after animations processing
  24543. */
  24544. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24545. /**
  24546. * An event triggered before draw calls are ready to be sent
  24547. */
  24548. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24549. /**
  24550. * An event triggered after draw calls have been sent
  24551. */
  24552. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24553. /**
  24554. * An event triggered when the scene is ready
  24555. */
  24556. _this.onReadyObservable = new BABYLON.Observable();
  24557. /**
  24558. * An event triggered before rendering a camera
  24559. */
  24560. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24561. _this._onBeforeCameraRenderObserver = null;
  24562. /**
  24563. * An event triggered after rendering a camera
  24564. */
  24565. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24566. _this._onAfterCameraRenderObserver = null;
  24567. /**
  24568. * An event triggered when active meshes evaluation is about to start
  24569. */
  24570. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24571. /**
  24572. * An event triggered when active meshes evaluation is done
  24573. */
  24574. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24575. /**
  24576. * An event triggered when particles rendering is about to start
  24577. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24578. */
  24579. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24580. /**
  24581. * An event triggered when particles rendering is done
  24582. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24583. */
  24584. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24585. /**
  24586. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24587. */
  24588. _this.onDataLoadedObservable = new BABYLON.Observable();
  24589. /**
  24590. * An event triggered when a camera is created
  24591. */
  24592. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24593. /**
  24594. * An event triggered when a camera is removed
  24595. */
  24596. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24597. /**
  24598. * An event triggered when a light is created
  24599. */
  24600. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24601. /**
  24602. * An event triggered when a light is removed
  24603. */
  24604. _this.onLightRemovedObservable = new BABYLON.Observable();
  24605. /**
  24606. * An event triggered when a geometry is created
  24607. */
  24608. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24609. /**
  24610. * An event triggered when a geometry is removed
  24611. */
  24612. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24613. /**
  24614. * An event triggered when a transform node is created
  24615. */
  24616. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24617. /**
  24618. * An event triggered when a transform node is removed
  24619. */
  24620. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24621. /**
  24622. * An event triggered when a mesh is created
  24623. */
  24624. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24625. /**
  24626. * An event triggered when a mesh is removed
  24627. */
  24628. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24629. /**
  24630. * An event triggered when a material is created
  24631. */
  24632. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  24633. /**
  24634. * An event triggered when a material is removed
  24635. */
  24636. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  24637. /**
  24638. * An event triggered when a texture is created
  24639. */
  24640. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  24641. /**
  24642. * An event triggered when a texture is removed
  24643. */
  24644. _this.onTextureRemovedObservable = new BABYLON.Observable();
  24645. /**
  24646. * An event triggered when render targets are about to be rendered
  24647. * Can happen multiple times per frame.
  24648. */
  24649. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24650. /**
  24651. * An event triggered when render targets were rendered.
  24652. * Can happen multiple times per frame.
  24653. */
  24654. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24655. /**
  24656. * An event triggered before calculating deterministic simulation step
  24657. */
  24658. _this.onBeforeStepObservable = new BABYLON.Observable();
  24659. /**
  24660. * An event triggered after calculating deterministic simulation step
  24661. */
  24662. _this.onAfterStepObservable = new BABYLON.Observable();
  24663. /**
  24664. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24665. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24666. * 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)
  24667. */
  24668. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24669. /**
  24670. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24671. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24672. * 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)
  24673. */
  24674. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24675. /**
  24676. * This Observable will when a mesh has been imported into the scene.
  24677. */
  24678. _this.onMeshImportedObservable = new BABYLON.Observable();
  24679. // Animations
  24680. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24681. /**
  24682. * 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).
  24683. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24684. */
  24685. _this.onPrePointerObservable = new BABYLON.Observable();
  24686. /**
  24687. * Observable event triggered each time an input event is received from the rendering canvas
  24688. */
  24689. _this.onPointerObservable = new BABYLON.Observable();
  24690. _this._meshPickProceed = false;
  24691. _this._currentPickResult = null;
  24692. _this._previousPickResult = null;
  24693. _this._totalPointersPressed = 0;
  24694. _this._doubleClickOccured = false;
  24695. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24696. _this.cameraToUseForPointers = null;
  24697. _this._pointerX = 0;
  24698. _this._pointerY = 0;
  24699. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24700. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24701. _this._startingPointerTime = 0;
  24702. _this._previousStartingPointerTime = 0;
  24703. _this._pointerCaptures = {};
  24704. // Deterministic lockstep
  24705. _this._timeAccumulator = 0;
  24706. _this._currentStepId = 0;
  24707. _this._currentInternalStep = 0;
  24708. // Keyboard
  24709. /**
  24710. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24711. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24712. */
  24713. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24714. /**
  24715. * Observable event triggered each time an keyboard event is received from the hosting window
  24716. */
  24717. _this.onKeyboardObservable = new BABYLON.Observable();
  24718. // Coordinates system
  24719. _this._useRightHandedSystem = false;
  24720. // Fog
  24721. _this._fogEnabled = true;
  24722. _this._fogMode = Scene.FOGMODE_NONE;
  24723. /**
  24724. * Gets or sets the fog color to use
  24725. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24726. * (Default is Color3(0.2, 0.2, 0.3))
  24727. */
  24728. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24729. /**
  24730. * Gets or sets the fog density to use
  24731. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24732. * (Default is 0.1)
  24733. */
  24734. _this.fogDensity = 0.1;
  24735. /**
  24736. * Gets or sets the fog start distance to use
  24737. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24738. * (Default is 0)
  24739. */
  24740. _this.fogStart = 0;
  24741. /**
  24742. * Gets or sets the fog end distance to use
  24743. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24744. * (Default is 1000)
  24745. */
  24746. _this.fogEnd = 1000.0;
  24747. // Lights
  24748. _this._shadowsEnabled = true;
  24749. _this._lightsEnabled = true;
  24750. /** All of the active cameras added to this scene. */
  24751. _this.activeCameras = new Array();
  24752. // Textures
  24753. _this._texturesEnabled = true;
  24754. // Particles
  24755. /**
  24756. * Gets or sets a boolean indicating if particles are enabled on this scene
  24757. */
  24758. _this.particlesEnabled = true;
  24759. // Sprites
  24760. /**
  24761. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24762. */
  24763. _this.spritesEnabled = true;
  24764. // Skeletons
  24765. _this._skeletonsEnabled = true;
  24766. // Lens flares
  24767. /**
  24768. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24769. */
  24770. _this.lensFlaresEnabled = true;
  24771. // Collisions
  24772. /**
  24773. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24774. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24775. */
  24776. _this.collisionsEnabled = true;
  24777. /**
  24778. * Defines the gravity applied to this scene (used only for collisions)
  24779. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24780. */
  24781. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24782. // Postprocesses
  24783. /**
  24784. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24785. */
  24786. _this.postProcessesEnabled = true;
  24787. /**
  24788. * The list of postprocesses added to the scene
  24789. */
  24790. _this.postProcesses = new Array();
  24791. // Customs render targets
  24792. /**
  24793. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24794. */
  24795. _this.renderTargetsEnabled = true;
  24796. /**
  24797. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24798. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24799. */
  24800. _this.dumpNextRenderTargets = false;
  24801. /**
  24802. * The list of user defined render targets added to the scene
  24803. */
  24804. _this.customRenderTargets = new Array();
  24805. /**
  24806. * Gets the list of meshes imported to the scene through SceneLoader
  24807. */
  24808. _this.importedMeshesFiles = new Array();
  24809. // Probes
  24810. /**
  24811. * Gets or sets a boolean indicating if probes are enabled on this scene
  24812. */
  24813. _this.probesEnabled = true;
  24814. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24815. // Procedural textures
  24816. /**
  24817. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24818. */
  24819. _this.proceduralTexturesEnabled = true;
  24820. // Performance counters
  24821. _this._totalVertices = new BABYLON.PerfCounter();
  24822. /** @hidden */
  24823. _this._activeIndices = new BABYLON.PerfCounter();
  24824. /** @hidden */
  24825. _this._activeParticles = new BABYLON.PerfCounter();
  24826. /** @hidden */
  24827. _this._activeBones = new BABYLON.PerfCounter();
  24828. _this._animationTime = 0;
  24829. /**
  24830. * Gets or sets a general scale for animation speed
  24831. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24832. */
  24833. _this.animationTimeScale = 1;
  24834. _this._renderId = 0;
  24835. _this._frameId = 0;
  24836. _this._executeWhenReadyTimeoutId = -1;
  24837. _this._intermediateRendering = false;
  24838. _this._viewUpdateFlag = -1;
  24839. _this._projectionUpdateFlag = -1;
  24840. _this._alternateViewUpdateFlag = -1;
  24841. _this._alternateProjectionUpdateFlag = -1;
  24842. /** @hidden */
  24843. _this._toBeDisposed = new Array(256);
  24844. _this._activeRequests = new Array();
  24845. _this._pendingData = new Array();
  24846. _this._isDisposed = false;
  24847. /**
  24848. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24849. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24850. */
  24851. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24852. _this._activeMeshes = new BABYLON.SmartArray(256);
  24853. _this._processedMaterials = new BABYLON.SmartArray(256);
  24854. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24855. /** @hidden */
  24856. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24857. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24858. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24859. /** @hidden */
  24860. _this._activeAnimatables = new Array();
  24861. _this._transformMatrix = BABYLON.Matrix.Zero();
  24862. _this._useAlternateCameraConfiguration = false;
  24863. _this._alternateRendering = false;
  24864. /**
  24865. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24866. * This is useful if there are more lights that the maximum simulteanous authorized
  24867. */
  24868. _this.requireLightSorting = false;
  24869. /**
  24870. * @hidden
  24871. * Backing store of defined scene components.
  24872. */
  24873. _this._components = [];
  24874. /**
  24875. * @hidden
  24876. * Backing store of defined scene components.
  24877. */
  24878. _this._serializableComponents = [];
  24879. /**
  24880. * List of components to register on the next registration step.
  24881. */
  24882. _this._transientComponents = [];
  24883. /**
  24884. * @hidden
  24885. * Defines the actions happening before camera updates.
  24886. */
  24887. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24888. /**
  24889. * @hidden
  24890. * Defines the actions happening before clear the canvas.
  24891. */
  24892. _this._beforeClearStage = BABYLON.Stage.Create();
  24893. /**
  24894. * @hidden
  24895. * Defines the actions when collecting render targets for the frame.
  24896. */
  24897. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24898. /**
  24899. * @hidden
  24900. * Defines the actions happening for one camera in the frame.
  24901. */
  24902. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  24903. /**
  24904. * @hidden
  24905. * Defines the actions happening during the per mesh ready checks.
  24906. */
  24907. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24908. /**
  24909. * @hidden
  24910. * Defines the actions happening before evaluate active mesh checks.
  24911. */
  24912. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24913. /**
  24914. * @hidden
  24915. * Defines the actions happening during the evaluate sub mesh checks.
  24916. */
  24917. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24918. /**
  24919. * @hidden
  24920. * Defines the actions happening during the active mesh stage.
  24921. */
  24922. _this._activeMeshStage = BABYLON.Stage.Create();
  24923. /**
  24924. * @hidden
  24925. * Defines the actions happening during the per camera render target step.
  24926. */
  24927. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24928. /**
  24929. * @hidden
  24930. * Defines the actions happening just before the active camera is drawing.
  24931. */
  24932. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24933. /**
  24934. * @hidden
  24935. * Defines the actions happening just before a rendering group is drawing.
  24936. */
  24937. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24938. /**
  24939. * @hidden
  24940. * Defines the actions happening just before a mesh is drawing.
  24941. */
  24942. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  24943. /**
  24944. * @hidden
  24945. * Defines the actions happening just after a mesh has been drawn.
  24946. */
  24947. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  24948. /**
  24949. * @hidden
  24950. * Defines the actions happening just after a rendering group has been drawn.
  24951. */
  24952. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24953. /**
  24954. * @hidden
  24955. * Defines the actions happening just after the active camera has been drawn.
  24956. */
  24957. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24958. /**
  24959. * @hidden
  24960. * Defines the actions happening just after rendering all cameras and computing intersections.
  24961. */
  24962. _this._afterRenderStage = BABYLON.Stage.Create();
  24963. /**
  24964. * @hidden
  24965. * Defines the actions happening when a pointer move event happens.
  24966. */
  24967. _this._pointerMoveStage = BABYLON.Stage.Create();
  24968. /**
  24969. * @hidden
  24970. * Defines the actions happening when a pointer down event happens.
  24971. */
  24972. _this._pointerDownStage = BABYLON.Stage.Create();
  24973. /**
  24974. * @hidden
  24975. * Defines the actions happening when a pointer up event happens.
  24976. */
  24977. _this._pointerUpStage = BABYLON.Stage.Create();
  24978. _this._defaultMeshCandidates = {
  24979. data: [],
  24980. length: 0
  24981. };
  24982. _this._defaultSubMeshCandidates = {
  24983. data: [],
  24984. length: 0
  24985. };
  24986. _this._activeMeshesFrozen = false;
  24987. /** @hidden */
  24988. _this._allowPostProcessClearColor = true;
  24989. /**
  24990. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  24991. */
  24992. _this.getDeterministicFrameTime = function () {
  24993. return 1000.0 / 60.0; // frame time in ms
  24994. };
  24995. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24996. _this._blockMaterialDirtyMechanism = false;
  24997. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24998. _this._engine.scenes.push(_this);
  24999. _this._uid = null;
  25000. _this._renderingManager = new BABYLON.RenderingManager(_this);
  25001. if (BABYLON.PostProcessManager) {
  25002. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  25003. }
  25004. if (BABYLON.Tools.IsWindowObjectExist()) {
  25005. _this.attachControl();
  25006. }
  25007. //collision coordinator initialization. For now legacy per default.
  25008. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  25009. // Uniform Buffer
  25010. _this._createUbo();
  25011. // Default Image processing definition
  25012. if (BABYLON.ImageProcessingConfiguration) {
  25013. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  25014. }
  25015. _this.setDefaultCandidateProviders();
  25016. return _this;
  25017. }
  25018. Object.defineProperty(Scene.prototype, "environmentTexture", {
  25019. /**
  25020. * Texture used in all pbr material as the reflection texture.
  25021. * As in the majority of the scene they are the same (exception for multi room and so on),
  25022. * this is easier to reference from here than from all the materials.
  25023. */
  25024. get: function () {
  25025. return this._environmentTexture;
  25026. },
  25027. /**
  25028. * Texture used in all pbr material as the reflection texture.
  25029. * As in the majority of the scene they are the same (exception for multi room and so on),
  25030. * this is easier to set here than in all the materials.
  25031. */
  25032. set: function (value) {
  25033. if (this._environmentTexture === value) {
  25034. return;
  25035. }
  25036. this._environmentTexture = value;
  25037. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25038. },
  25039. enumerable: true,
  25040. configurable: true
  25041. });
  25042. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  25043. /**
  25044. * Default image processing configuration used either in the rendering
  25045. * Forward main pass or through the imageProcessingPostProcess if present.
  25046. * As in the majority of the scene they are the same (exception for multi camera),
  25047. * this is easier to reference from here than from all the materials and post process.
  25048. *
  25049. * No setter as we it is a shared configuration, you can set the values instead.
  25050. */
  25051. get: function () {
  25052. return this._imageProcessingConfiguration;
  25053. },
  25054. enumerable: true,
  25055. configurable: true
  25056. });
  25057. Object.defineProperty(Scene.prototype, "forceWireframe", {
  25058. get: function () {
  25059. return this._forceWireframe;
  25060. },
  25061. /**
  25062. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  25063. */
  25064. set: function (value) {
  25065. if (this._forceWireframe === value) {
  25066. return;
  25067. }
  25068. this._forceWireframe = value;
  25069. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25070. },
  25071. enumerable: true,
  25072. configurable: true
  25073. });
  25074. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  25075. get: function () {
  25076. return this._forcePointsCloud;
  25077. },
  25078. /**
  25079. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  25080. */
  25081. set: function (value) {
  25082. if (this._forcePointsCloud === value) {
  25083. return;
  25084. }
  25085. this._forcePointsCloud = value;
  25086. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25087. },
  25088. enumerable: true,
  25089. configurable: true
  25090. });
  25091. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  25092. /**
  25093. * Gets or sets the animation properties override
  25094. */
  25095. get: function () {
  25096. return this._animationPropertiesOverride;
  25097. },
  25098. set: function (value) {
  25099. this._animationPropertiesOverride = value;
  25100. },
  25101. enumerable: true,
  25102. configurable: true
  25103. });
  25104. Object.defineProperty(Scene.prototype, "onDispose", {
  25105. /** Sets a function to be executed when this scene is disposed. */
  25106. set: function (callback) {
  25107. if (this._onDisposeObserver) {
  25108. this.onDisposeObservable.remove(this._onDisposeObserver);
  25109. }
  25110. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25111. },
  25112. enumerable: true,
  25113. configurable: true
  25114. });
  25115. Object.defineProperty(Scene.prototype, "beforeRender", {
  25116. /** Sets a function to be executed before rendering this scene */
  25117. set: function (callback) {
  25118. if (this._onBeforeRenderObserver) {
  25119. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25120. }
  25121. if (callback) {
  25122. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25123. }
  25124. },
  25125. enumerable: true,
  25126. configurable: true
  25127. });
  25128. Object.defineProperty(Scene.prototype, "afterRender", {
  25129. /** Sets a function to be executed after rendering this scene */
  25130. set: function (callback) {
  25131. if (this._onAfterRenderObserver) {
  25132. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25133. }
  25134. if (callback) {
  25135. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25136. }
  25137. },
  25138. enumerable: true,
  25139. configurable: true
  25140. });
  25141. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  25142. /** Sets a function to be executed before rendering a camera*/
  25143. set: function (callback) {
  25144. if (this._onBeforeCameraRenderObserver) {
  25145. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  25146. }
  25147. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  25148. },
  25149. enumerable: true,
  25150. configurable: true
  25151. });
  25152. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  25153. /** Sets a function to be executed after rendering a camera*/
  25154. set: function (callback) {
  25155. if (this._onAfterCameraRenderObserver) {
  25156. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  25157. }
  25158. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  25159. },
  25160. enumerable: true,
  25161. configurable: true
  25162. });
  25163. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  25164. /**
  25165. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  25166. */
  25167. get: function () {
  25168. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  25169. },
  25170. enumerable: true,
  25171. configurable: true
  25172. });
  25173. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  25174. get: function () {
  25175. return this._useRightHandedSystem;
  25176. },
  25177. /**
  25178. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  25179. */
  25180. set: function (value) {
  25181. if (this._useRightHandedSystem === value) {
  25182. return;
  25183. }
  25184. this._useRightHandedSystem = value;
  25185. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25186. },
  25187. enumerable: true,
  25188. configurable: true
  25189. });
  25190. /**
  25191. * Sets the step Id used by deterministic lock step
  25192. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25193. * @param newStepId defines the step Id
  25194. */
  25195. Scene.prototype.setStepId = function (newStepId) {
  25196. this._currentStepId = newStepId;
  25197. };
  25198. ;
  25199. /**
  25200. * Gets the step Id used by deterministic lock step
  25201. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25202. * @returns the step Id
  25203. */
  25204. Scene.prototype.getStepId = function () {
  25205. return this._currentStepId;
  25206. };
  25207. ;
  25208. /**
  25209. * Gets the internal step used by deterministic lock step
  25210. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25211. * @returns the internal step
  25212. */
  25213. Scene.prototype.getInternalStep = function () {
  25214. return this._currentInternalStep;
  25215. };
  25216. ;
  25217. Object.defineProperty(Scene.prototype, "fogEnabled", {
  25218. get: function () {
  25219. return this._fogEnabled;
  25220. },
  25221. /**
  25222. * Gets or sets a boolean indicating if fog is enabled on this scene
  25223. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25224. * (Default is true)
  25225. */
  25226. set: function (value) {
  25227. if (this._fogEnabled === value) {
  25228. return;
  25229. }
  25230. this._fogEnabled = value;
  25231. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25232. },
  25233. enumerable: true,
  25234. configurable: true
  25235. });
  25236. Object.defineProperty(Scene.prototype, "fogMode", {
  25237. get: function () {
  25238. return this._fogMode;
  25239. },
  25240. /**
  25241. * Gets or sets the fog mode to use
  25242. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25243. * | mode | value |
  25244. * | --- | --- |
  25245. * | FOGMODE_NONE | 0 |
  25246. * | FOGMODE_EXP | 1 |
  25247. * | FOGMODE_EXP2 | 2 |
  25248. * | FOGMODE_LINEAR | 3 |
  25249. */
  25250. set: function (value) {
  25251. if (this._fogMode === value) {
  25252. return;
  25253. }
  25254. this._fogMode = value;
  25255. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25256. },
  25257. enumerable: true,
  25258. configurable: true
  25259. });
  25260. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  25261. get: function () {
  25262. return this._shadowsEnabled;
  25263. },
  25264. /**
  25265. * Gets or sets a boolean indicating if shadows are enabled on this scene
  25266. */
  25267. set: function (value) {
  25268. if (this._shadowsEnabled === value) {
  25269. return;
  25270. }
  25271. this._shadowsEnabled = value;
  25272. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25273. },
  25274. enumerable: true,
  25275. configurable: true
  25276. });
  25277. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  25278. get: function () {
  25279. return this._lightsEnabled;
  25280. },
  25281. /**
  25282. * Gets or sets a boolean indicating if lights are enabled on this scene
  25283. */
  25284. set: function (value) {
  25285. if (this._lightsEnabled === value) {
  25286. return;
  25287. }
  25288. this._lightsEnabled = value;
  25289. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25290. },
  25291. enumerable: true,
  25292. configurable: true
  25293. });
  25294. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  25295. /** The default material used on meshes when no material is affected */
  25296. get: function () {
  25297. if (!this._defaultMaterial) {
  25298. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  25299. }
  25300. return this._defaultMaterial;
  25301. },
  25302. /** The default material used on meshes when no material is affected */
  25303. set: function (value) {
  25304. this._defaultMaterial = value;
  25305. },
  25306. enumerable: true,
  25307. configurable: true
  25308. });
  25309. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  25310. get: function () {
  25311. return this._texturesEnabled;
  25312. },
  25313. /**
  25314. * Gets or sets a boolean indicating if textures are enabled on this scene
  25315. */
  25316. set: function (value) {
  25317. if (this._texturesEnabled === value) {
  25318. return;
  25319. }
  25320. this._texturesEnabled = value;
  25321. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25322. },
  25323. enumerable: true,
  25324. configurable: true
  25325. });
  25326. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  25327. get: function () {
  25328. return this._skeletonsEnabled;
  25329. },
  25330. /**
  25331. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  25332. */
  25333. set: function (value) {
  25334. if (this._skeletonsEnabled === value) {
  25335. return;
  25336. }
  25337. this._skeletonsEnabled = value;
  25338. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  25339. },
  25340. enumerable: true,
  25341. configurable: true
  25342. });
  25343. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  25344. /** @hidden */
  25345. get: function () {
  25346. return this._alternateRendering;
  25347. },
  25348. enumerable: true,
  25349. configurable: true
  25350. });
  25351. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  25352. /**
  25353. * Gets the list of frustum planes (built from the active camera)
  25354. */
  25355. get: function () {
  25356. return this._frustumPlanes;
  25357. },
  25358. enumerable: true,
  25359. configurable: true
  25360. });
  25361. /**
  25362. * Registers the transient components if needed.
  25363. */
  25364. Scene.prototype._registerTransientComponents = function () {
  25365. // Register components that have been associated lately to the scene.
  25366. if (this._transientComponents.length > 0) {
  25367. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25368. var component = _a[_i];
  25369. component.register();
  25370. }
  25371. this._transientComponents = [];
  25372. }
  25373. };
  25374. /**
  25375. * @hidden
  25376. * Add a component to the scene.
  25377. * Note that the ccomponent could be registered on th next frame if this is called after
  25378. * the register component stage.
  25379. * @param component Defines the component to add to the scene
  25380. */
  25381. Scene.prototype._addComponent = function (component) {
  25382. this._components.push(component);
  25383. this._transientComponents.push(component);
  25384. var serializableComponent = component;
  25385. if (serializableComponent.addFromContainer) {
  25386. this._serializableComponents.push(serializableComponent);
  25387. }
  25388. };
  25389. /**
  25390. * @hidden
  25391. * Gets a component from the scene.
  25392. * @param name defines the name of the component to retrieve
  25393. * @returns the component or null if not present
  25394. */
  25395. Scene.prototype._getComponent = function (name) {
  25396. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  25397. var component = _a[_i];
  25398. if (component.name === name) {
  25399. return component;
  25400. }
  25401. }
  25402. return null;
  25403. };
  25404. /**
  25405. * @hidden
  25406. */
  25407. Scene.prototype._getDefaultMeshCandidates = function () {
  25408. this._defaultMeshCandidates.data = this.meshes;
  25409. this._defaultMeshCandidates.length = this.meshes.length;
  25410. return this._defaultMeshCandidates;
  25411. };
  25412. /**
  25413. * @hidden
  25414. */
  25415. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  25416. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  25417. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  25418. return this._defaultSubMeshCandidates;
  25419. };
  25420. /**
  25421. * Sets the default candidate providers for the scene.
  25422. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  25423. * and getCollidingSubMeshCandidates to their default function
  25424. */
  25425. Scene.prototype.setDefaultCandidateProviders = function () {
  25426. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  25427. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25428. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25429. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25430. };
  25431. Object.defineProperty(Scene.prototype, "workerCollisions", {
  25432. /**
  25433. * Gets a boolean indicating if collisions are processed on a web worker
  25434. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  25435. */
  25436. get: function () {
  25437. return this._workerCollisions;
  25438. },
  25439. set: function (enabled) {
  25440. if (!BABYLON.CollisionCoordinatorLegacy) {
  25441. return;
  25442. }
  25443. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  25444. this._workerCollisions = enabled;
  25445. if (this.collisionCoordinator) {
  25446. this.collisionCoordinator.destroy();
  25447. }
  25448. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  25449. this.collisionCoordinator.init(this);
  25450. },
  25451. enumerable: true,
  25452. configurable: true
  25453. });
  25454. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25455. /**
  25456. * Gets the mesh that is currently under the pointer
  25457. */
  25458. get: function () {
  25459. return this._pointerOverMesh;
  25460. },
  25461. enumerable: true,
  25462. configurable: true
  25463. });
  25464. Object.defineProperty(Scene.prototype, "pointerX", {
  25465. /**
  25466. * Gets the current on-screen X position of the pointer
  25467. */
  25468. get: function () {
  25469. return this._pointerX;
  25470. },
  25471. enumerable: true,
  25472. configurable: true
  25473. });
  25474. Object.defineProperty(Scene.prototype, "pointerY", {
  25475. /**
  25476. * Gets the current on-screen Y position of the pointer
  25477. */
  25478. get: function () {
  25479. return this._pointerY;
  25480. },
  25481. enumerable: true,
  25482. configurable: true
  25483. });
  25484. /**
  25485. * Gets the cached material (ie. the latest rendered one)
  25486. * @returns the cached material
  25487. */
  25488. Scene.prototype.getCachedMaterial = function () {
  25489. return this._cachedMaterial;
  25490. };
  25491. /**
  25492. * Gets the cached effect (ie. the latest rendered one)
  25493. * @returns the cached effect
  25494. */
  25495. Scene.prototype.getCachedEffect = function () {
  25496. return this._cachedEffect;
  25497. };
  25498. /**
  25499. * Gets the cached visibility state (ie. the latest rendered one)
  25500. * @returns the cached visibility state
  25501. */
  25502. Scene.prototype.getCachedVisibility = function () {
  25503. return this._cachedVisibility;
  25504. };
  25505. /**
  25506. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25507. * @param material defines the current material
  25508. * @param effect defines the current effect
  25509. * @param visibility defines the current visibility state
  25510. * @returns true if one parameter is not cached
  25511. */
  25512. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25513. if (visibility === void 0) { visibility = 1; }
  25514. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25515. };
  25516. /**
  25517. * Gets the engine associated with the scene
  25518. * @returns an Engine
  25519. */
  25520. Scene.prototype.getEngine = function () {
  25521. return this._engine;
  25522. };
  25523. /**
  25524. * Gets the total number of vertices rendered per frame
  25525. * @returns the total number of vertices rendered per frame
  25526. */
  25527. Scene.prototype.getTotalVertices = function () {
  25528. return this._totalVertices.current;
  25529. };
  25530. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25531. /**
  25532. * Gets the performance counter for total vertices
  25533. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25534. */
  25535. get: function () {
  25536. return this._totalVertices;
  25537. },
  25538. enumerable: true,
  25539. configurable: true
  25540. });
  25541. /**
  25542. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25543. * @returns the total number of active indices rendered per frame
  25544. */
  25545. Scene.prototype.getActiveIndices = function () {
  25546. return this._activeIndices.current;
  25547. };
  25548. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25549. /**
  25550. * Gets the performance counter for active indices
  25551. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25552. */
  25553. get: function () {
  25554. return this._activeIndices;
  25555. },
  25556. enumerable: true,
  25557. configurable: true
  25558. });
  25559. /**
  25560. * Gets the total number of active particles rendered per frame
  25561. * @returns the total number of active particles rendered per frame
  25562. */
  25563. Scene.prototype.getActiveParticles = function () {
  25564. return this._activeParticles.current;
  25565. };
  25566. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25567. /**
  25568. * Gets the performance counter for active particles
  25569. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25570. */
  25571. get: function () {
  25572. return this._activeParticles;
  25573. },
  25574. enumerable: true,
  25575. configurable: true
  25576. });
  25577. /**
  25578. * Gets the total number of active bones rendered per frame
  25579. * @returns the total number of active bones rendered per frame
  25580. */
  25581. Scene.prototype.getActiveBones = function () {
  25582. return this._activeBones.current;
  25583. };
  25584. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25585. /**
  25586. * Gets the performance counter for active bones
  25587. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25588. */
  25589. get: function () {
  25590. return this._activeBones;
  25591. },
  25592. enumerable: true,
  25593. configurable: true
  25594. });
  25595. /** @hidden */
  25596. Scene.prototype.getInterFramePerfCounter = function () {
  25597. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25598. return 0;
  25599. };
  25600. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25601. /** @hidden */
  25602. get: function () {
  25603. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25604. return null;
  25605. },
  25606. enumerable: true,
  25607. configurable: true
  25608. });
  25609. /** @hidden */
  25610. Scene.prototype.getLastFrameDuration = function () {
  25611. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25612. return 0;
  25613. };
  25614. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25615. /** @hidden */
  25616. get: function () {
  25617. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25618. return null;
  25619. },
  25620. enumerable: true,
  25621. configurable: true
  25622. });
  25623. /** @hidden */
  25624. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25625. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25626. return 0;
  25627. };
  25628. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25629. /** @hidden */
  25630. get: function () {
  25631. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25632. return null;
  25633. },
  25634. enumerable: true,
  25635. configurable: true
  25636. });
  25637. /**
  25638. * Gets the array of active meshes
  25639. * @returns an array of AbstractMesh
  25640. */
  25641. Scene.prototype.getActiveMeshes = function () {
  25642. return this._activeMeshes;
  25643. };
  25644. /** @hidden */
  25645. Scene.prototype.getRenderTargetsDuration = function () {
  25646. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25647. return 0;
  25648. };
  25649. /** @hidden */
  25650. Scene.prototype.getRenderDuration = function () {
  25651. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25652. return 0;
  25653. };
  25654. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25655. /** @hidden */
  25656. get: function () {
  25657. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25658. return null;
  25659. },
  25660. enumerable: true,
  25661. configurable: true
  25662. });
  25663. /** @hidden */
  25664. Scene.prototype.getParticlesDuration = function () {
  25665. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25666. return 0;
  25667. };
  25668. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25669. /** @hidden */
  25670. get: function () {
  25671. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25672. return null;
  25673. },
  25674. enumerable: true,
  25675. configurable: true
  25676. });
  25677. /** @hidden */
  25678. Scene.prototype.getSpritesDuration = function () {
  25679. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25680. return 0;
  25681. };
  25682. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25683. /** @hidden */
  25684. get: function () {
  25685. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25686. return null;
  25687. },
  25688. enumerable: true,
  25689. configurable: true
  25690. });
  25691. /**
  25692. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25693. * @returns a number
  25694. */
  25695. Scene.prototype.getAnimationRatio = function () {
  25696. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25697. };
  25698. /**
  25699. * Gets an unique Id for the current render phase
  25700. * @returns a number
  25701. */
  25702. Scene.prototype.getRenderId = function () {
  25703. return this._renderId;
  25704. };
  25705. /**
  25706. * Gets an unique Id for the current frame
  25707. * @returns a number
  25708. */
  25709. Scene.prototype.getFrameId = function () {
  25710. return this._frameId;
  25711. };
  25712. /** Call this function if you want to manually increment the render Id*/
  25713. Scene.prototype.incrementRenderId = function () {
  25714. this._renderId++;
  25715. };
  25716. Scene.prototype._updatePointerPosition = function (evt) {
  25717. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25718. if (!canvasRect) {
  25719. return;
  25720. }
  25721. this._pointerX = evt.clientX - canvasRect.left;
  25722. this._pointerY = evt.clientY - canvasRect.top;
  25723. this._unTranslatedPointerX = this._pointerX;
  25724. this._unTranslatedPointerY = this._pointerY;
  25725. };
  25726. Scene.prototype._createUbo = function () {
  25727. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25728. this._sceneUbo.addUniform("viewProjection", 16);
  25729. this._sceneUbo.addUniform("view", 16);
  25730. };
  25731. Scene.prototype._createAlternateUbo = function () {
  25732. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25733. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25734. this._alternateSceneUbo.addUniform("view", 16);
  25735. };
  25736. // Pointers handling
  25737. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25738. if (pointerInfo.pickInfo) {
  25739. if (!pointerInfo.pickInfo.ray) {
  25740. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25741. }
  25742. }
  25743. };
  25744. /**
  25745. * Use this method to simulate a pointer move on a mesh
  25746. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25747. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25748. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25749. * @returns the current scene
  25750. */
  25751. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25752. var evt = new PointerEvent("pointermove", pointerEventInit);
  25753. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25754. return this;
  25755. }
  25756. return this._processPointerMove(pickResult, evt);
  25757. };
  25758. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25759. var canvas = this._engine.getRenderingCanvas();
  25760. if (!canvas) {
  25761. return this;
  25762. }
  25763. // Restore pointer
  25764. canvas.style.cursor = this.defaultCursor;
  25765. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  25766. if (isMeshPicked) {
  25767. this.setPointerOverMesh(pickResult.pickedMesh);
  25768. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25769. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25770. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25771. }
  25772. else {
  25773. canvas.style.cursor = this.hoverCursor;
  25774. }
  25775. }
  25776. }
  25777. else {
  25778. this.setPointerOverMesh(null);
  25779. }
  25780. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  25781. var step = _a[_i];
  25782. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  25783. }
  25784. if (pickResult) {
  25785. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25786. if (this.onPointerMove) {
  25787. this.onPointerMove(evt, pickResult, type);
  25788. }
  25789. if (this.onPointerObservable.hasObservers()) {
  25790. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25791. this._setRayOnPointerInfo(pi);
  25792. this.onPointerObservable.notifyObservers(pi, type);
  25793. }
  25794. }
  25795. return this;
  25796. };
  25797. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25798. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25799. if (pickResult) {
  25800. pi.ray = pickResult.ray;
  25801. }
  25802. this.onPrePointerObservable.notifyObservers(pi, type);
  25803. if (pi.skipOnPointerObservable) {
  25804. return true;
  25805. }
  25806. else {
  25807. return false;
  25808. }
  25809. };
  25810. /**
  25811. * Use this method to simulate a pointer down on a mesh
  25812. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25813. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25814. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25815. * @returns the current scene
  25816. */
  25817. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25818. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25819. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25820. return this;
  25821. }
  25822. return this._processPointerDown(pickResult, evt);
  25823. };
  25824. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25825. var _this = this;
  25826. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25827. this._pickedDownMesh = pickResult.pickedMesh;
  25828. var actionManager = pickResult.pickedMesh.actionManager;
  25829. if (actionManager) {
  25830. if (actionManager.hasPickTriggers) {
  25831. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25832. switch (evt.button) {
  25833. case 0:
  25834. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25835. break;
  25836. case 1:
  25837. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25838. break;
  25839. case 2:
  25840. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25841. break;
  25842. }
  25843. }
  25844. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25845. window.setTimeout(function () {
  25846. 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);
  25847. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25848. if (_this._totalPointersPressed !== 0 &&
  25849. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25850. !_this._isPointerSwiping()) {
  25851. _this._startingPointerTime = 0;
  25852. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25853. }
  25854. }
  25855. }, Scene.LongPressDelay);
  25856. }
  25857. }
  25858. }
  25859. else {
  25860. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  25861. var step = _a[_i];
  25862. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25863. }
  25864. }
  25865. if (pickResult) {
  25866. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25867. if (this.onPointerDown) {
  25868. this.onPointerDown(evt, pickResult, type);
  25869. }
  25870. if (this.onPointerObservable.hasObservers()) {
  25871. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25872. this._setRayOnPointerInfo(pi);
  25873. this.onPointerObservable.notifyObservers(pi, type);
  25874. }
  25875. }
  25876. return this;
  25877. };
  25878. /**
  25879. * Use this method to simulate a pointer up on a mesh
  25880. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25881. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25882. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25883. * @returns the current scene
  25884. */
  25885. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25886. var evt = new PointerEvent("pointerup", pointerEventInit);
  25887. var clickInfo = new ClickInfo();
  25888. clickInfo.singleClick = true;
  25889. clickInfo.ignore = true;
  25890. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25891. return this;
  25892. }
  25893. return this._processPointerUp(pickResult, evt, clickInfo);
  25894. };
  25895. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25896. if (pickResult && pickResult && pickResult.pickedMesh) {
  25897. this._pickedUpMesh = pickResult.pickedMesh;
  25898. if (this._pickedDownMesh === this._pickedUpMesh) {
  25899. if (this.onPointerPick) {
  25900. this.onPointerPick(evt, pickResult);
  25901. }
  25902. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25903. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25904. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25905. this._setRayOnPointerInfo(pi);
  25906. this.onPointerObservable.notifyObservers(pi, type_1);
  25907. }
  25908. }
  25909. if (pickResult.pickedMesh.actionManager) {
  25910. if (clickInfo.ignore) {
  25911. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25912. }
  25913. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25914. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25915. }
  25916. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25917. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25918. }
  25919. }
  25920. }
  25921. else {
  25922. if (!clickInfo.ignore) {
  25923. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  25924. var step = _a[_i];
  25925. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25926. }
  25927. }
  25928. }
  25929. if (this._pickedDownMesh &&
  25930. this._pickedDownMesh.actionManager &&
  25931. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25932. this._pickedDownMesh !== this._pickedUpMesh) {
  25933. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25934. }
  25935. var type = BABYLON.PointerEventTypes.POINTERUP;
  25936. if (this.onPointerObservable.hasObservers()) {
  25937. if (!clickInfo.ignore) {
  25938. if (!clickInfo.hasSwiped) {
  25939. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25940. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25941. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25942. this._setRayOnPointerInfo(pi);
  25943. this.onPointerObservable.notifyObservers(pi, type_2);
  25944. }
  25945. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25946. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25947. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25948. this._setRayOnPointerInfo(pi);
  25949. this.onPointerObservable.notifyObservers(pi, type_3);
  25950. }
  25951. }
  25952. }
  25953. else {
  25954. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25955. this._setRayOnPointerInfo(pi);
  25956. this.onPointerObservable.notifyObservers(pi, type);
  25957. }
  25958. }
  25959. if (this.onPointerUp) {
  25960. this.onPointerUp(evt, pickResult, type);
  25961. }
  25962. return this;
  25963. };
  25964. /**
  25965. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25966. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25967. * @returns true if the pointer was captured
  25968. */
  25969. Scene.prototype.isPointerCaptured = function (pointerId) {
  25970. if (pointerId === void 0) { pointerId = 0; }
  25971. return this._pointerCaptures[pointerId];
  25972. };
  25973. /** @hidden */
  25974. Scene.prototype._isPointerSwiping = function () {
  25975. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  25976. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  25977. };
  25978. /**
  25979. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25980. * @param attachUp defines if you want to attach events to pointerup
  25981. * @param attachDown defines if you want to attach events to pointerdown
  25982. * @param attachMove defines if you want to attach events to pointermove
  25983. */
  25984. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25985. var _this = this;
  25986. if (attachUp === void 0) { attachUp = true; }
  25987. if (attachDown === void 0) { attachDown = true; }
  25988. if (attachMove === void 0) { attachMove = true; }
  25989. this._initActionManager = function (act, clickInfo) {
  25990. if (!_this._meshPickProceed) {
  25991. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25992. _this._currentPickResult = pickResult;
  25993. if (pickResult) {
  25994. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25995. }
  25996. _this._meshPickProceed = true;
  25997. }
  25998. return act;
  25999. };
  26000. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  26001. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  26002. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  26003. btn !== _this._previousButtonPressed) {
  26004. _this._doubleClickOccured = false;
  26005. clickInfo.singleClick = true;
  26006. clickInfo.ignore = false;
  26007. cb(clickInfo, _this._currentPickResult);
  26008. }
  26009. };
  26010. this._initClickEvent = function (obs1, obs2, evt, cb) {
  26011. var clickInfo = new ClickInfo();
  26012. _this._currentPickResult = null;
  26013. var act = null;
  26014. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  26015. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  26016. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26017. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  26018. act = _this._initActionManager(act, clickInfo);
  26019. if (act)
  26020. checkPicking = act.hasPickTriggers;
  26021. }
  26022. if (checkPicking) {
  26023. var btn = evt.button;
  26024. clickInfo.hasSwiped = _this._isPointerSwiping();
  26025. if (!clickInfo.hasSwiped) {
  26026. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  26027. if (!checkSingleClickImmediately) {
  26028. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  26029. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26030. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26031. act = _this._initActionManager(act, clickInfo);
  26032. if (act)
  26033. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26034. }
  26035. }
  26036. if (checkSingleClickImmediately) {
  26037. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  26038. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  26039. btn !== _this._previousButtonPressed) {
  26040. clickInfo.singleClick = true;
  26041. cb(clickInfo, _this._currentPickResult);
  26042. }
  26043. }
  26044. // at least one double click is required to be check and exclusive double click is enabled
  26045. else {
  26046. // wait that no double click has been raised during the double click delay
  26047. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26048. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  26049. }
  26050. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  26051. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26052. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26053. act = _this._initActionManager(act, clickInfo);
  26054. if (act)
  26055. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26056. }
  26057. if (checkDoubleClick) {
  26058. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  26059. if (btn === _this._previousButtonPressed &&
  26060. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  26061. !_this._doubleClickOccured) {
  26062. // pointer has not moved for 2 clicks, it's a double click
  26063. if (!clickInfo.hasSwiped &&
  26064. !_this._isPointerSwiping()) {
  26065. _this._previousStartingPointerTime = 0;
  26066. _this._doubleClickOccured = true;
  26067. clickInfo.doubleClick = true;
  26068. clickInfo.ignore = false;
  26069. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  26070. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26071. }
  26072. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26073. cb(clickInfo, _this._currentPickResult);
  26074. }
  26075. // if the two successive clicks are too far, it's just two simple clicks
  26076. else {
  26077. _this._doubleClickOccured = false;
  26078. _this._previousStartingPointerTime = _this._startingPointerTime;
  26079. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26080. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26081. _this._previousButtonPressed = btn;
  26082. if (Scene.ExclusiveDoubleClickMode) {
  26083. if (_this._previousDelayedSimpleClickTimeout) {
  26084. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26085. }
  26086. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26087. cb(clickInfo, _this._previousPickResult);
  26088. }
  26089. else {
  26090. cb(clickInfo, _this._currentPickResult);
  26091. }
  26092. }
  26093. }
  26094. // just the first click of the double has been raised
  26095. else {
  26096. _this._doubleClickOccured = false;
  26097. _this._previousStartingPointerTime = _this._startingPointerTime;
  26098. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26099. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26100. _this._previousButtonPressed = btn;
  26101. }
  26102. }
  26103. }
  26104. }
  26105. clickInfo.ignore = true;
  26106. cb(clickInfo, _this._currentPickResult);
  26107. };
  26108. this._onPointerMove = function (evt) {
  26109. _this._updatePointerPosition(evt);
  26110. // PreObservable support
  26111. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  26112. return;
  26113. }
  26114. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26115. return;
  26116. }
  26117. if (!_this.pointerMovePredicate) {
  26118. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  26119. }
  26120. // Meshes
  26121. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  26122. _this._processPointerMove(pickResult, evt);
  26123. };
  26124. this._onPointerDown = function (evt) {
  26125. _this._totalPointersPressed++;
  26126. _this._pickedDownMesh = null;
  26127. _this._meshPickProceed = false;
  26128. _this._updatePointerPosition(evt);
  26129. if (_this.preventDefaultOnPointerDown && canvas) {
  26130. evt.preventDefault();
  26131. canvas.focus();
  26132. }
  26133. // PreObservable support
  26134. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26135. return;
  26136. }
  26137. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26138. return;
  26139. }
  26140. _this._pointerCaptures[evt.pointerId] = true;
  26141. _this._startingPointerPosition.x = _this._pointerX;
  26142. _this._startingPointerPosition.y = _this._pointerY;
  26143. _this._startingPointerTime = Date.now();
  26144. if (!_this.pointerDownPredicate) {
  26145. _this.pointerDownPredicate = function (mesh) {
  26146. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26147. };
  26148. }
  26149. // Meshes
  26150. _this._pickedDownMesh = null;
  26151. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26152. _this._processPointerDown(pickResult, evt);
  26153. };
  26154. this._onPointerUp = function (evt) {
  26155. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  26156. return; // So we need to test it the pointer down was pressed before.
  26157. }
  26158. _this._totalPointersPressed--;
  26159. _this._pickedUpMesh = null;
  26160. _this._meshPickProceed = false;
  26161. _this._updatePointerPosition(evt);
  26162. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  26163. // PreObservable support
  26164. if (_this.onPrePointerObservable.hasObservers()) {
  26165. if (!clickInfo.ignore) {
  26166. if (!clickInfo.hasSwiped) {
  26167. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26168. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  26169. return;
  26170. }
  26171. }
  26172. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26173. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26174. return;
  26175. }
  26176. }
  26177. }
  26178. }
  26179. else {
  26180. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26181. return;
  26182. }
  26183. }
  26184. }
  26185. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26186. return;
  26187. }
  26188. _this._pointerCaptures[evt.pointerId] = false;
  26189. if (!_this.pointerUpPredicate) {
  26190. _this.pointerUpPredicate = function (mesh) {
  26191. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26192. };
  26193. }
  26194. // Meshes
  26195. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  26196. _this._initActionManager(null, clickInfo);
  26197. }
  26198. if (!pickResult) {
  26199. pickResult = _this._currentPickResult;
  26200. }
  26201. _this._processPointerUp(pickResult, evt, clickInfo);
  26202. _this._previousPickResult = _this._currentPickResult;
  26203. });
  26204. };
  26205. this._onKeyDown = function (evt) {
  26206. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  26207. if (_this.onPreKeyboardObservable.hasObservers()) {
  26208. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26209. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26210. if (pi.skipOnPointerObservable) {
  26211. return;
  26212. }
  26213. }
  26214. if (_this.onKeyboardObservable.hasObservers()) {
  26215. var pi = new BABYLON.KeyboardInfo(type, evt);
  26216. _this.onKeyboardObservable.notifyObservers(pi, type);
  26217. }
  26218. if (_this.actionManager) {
  26219. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26220. }
  26221. };
  26222. this._onKeyUp = function (evt) {
  26223. var type = BABYLON.KeyboardEventTypes.KEYUP;
  26224. if (_this.onPreKeyboardObservable.hasObservers()) {
  26225. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26226. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26227. if (pi.skipOnPointerObservable) {
  26228. return;
  26229. }
  26230. }
  26231. if (_this.onKeyboardObservable.hasObservers()) {
  26232. var pi = new BABYLON.KeyboardInfo(type, evt);
  26233. _this.onKeyboardObservable.notifyObservers(pi, type);
  26234. }
  26235. if (_this.actionManager) {
  26236. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26237. }
  26238. };
  26239. var engine = this.getEngine();
  26240. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  26241. if (!canvas) {
  26242. return;
  26243. }
  26244. canvas.addEventListener("keydown", _this._onKeyDown, false);
  26245. canvas.addEventListener("keyup", _this._onKeyUp, false);
  26246. });
  26247. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  26248. if (!canvas) {
  26249. return;
  26250. }
  26251. canvas.removeEventListener("keydown", _this._onKeyDown);
  26252. canvas.removeEventListener("keyup", _this._onKeyUp);
  26253. });
  26254. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26255. var canvas = this._engine.getRenderingCanvas();
  26256. if (!canvas) {
  26257. return;
  26258. }
  26259. if (attachMove) {
  26260. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  26261. // Wheel
  26262. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  26263. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  26264. }
  26265. if (attachDown) {
  26266. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  26267. }
  26268. if (attachUp) {
  26269. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  26270. }
  26271. canvas.tabIndex = 1;
  26272. };
  26273. /** Detaches all event handlers*/
  26274. Scene.prototype.detachControl = function () {
  26275. var engine = this.getEngine();
  26276. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26277. var canvas = engine.getRenderingCanvas();
  26278. if (!canvas) {
  26279. return;
  26280. }
  26281. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  26282. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  26283. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  26284. if (this._onCanvasBlurObserver) {
  26285. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  26286. }
  26287. if (this._onCanvasFocusObserver) {
  26288. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  26289. }
  26290. // Wheel
  26291. canvas.removeEventListener('mousewheel', this._onPointerMove);
  26292. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  26293. // Keyboard
  26294. canvas.removeEventListener("keydown", this._onKeyDown);
  26295. canvas.removeEventListener("keyup", this._onKeyUp);
  26296. // Observables
  26297. this.onKeyboardObservable.clear();
  26298. this.onPreKeyboardObservable.clear();
  26299. this.onPointerObservable.clear();
  26300. this.onPrePointerObservable.clear();
  26301. };
  26302. /**
  26303. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  26304. * Delay loaded resources are not taking in account
  26305. * @return true if all required resources are ready
  26306. */
  26307. Scene.prototype.isReady = function () {
  26308. if (this._isDisposed) {
  26309. return false;
  26310. }
  26311. if (this._pendingData.length > 0) {
  26312. return false;
  26313. }
  26314. var index;
  26315. var engine = this.getEngine();
  26316. // Geometries
  26317. for (index = 0; index < this.geometries.length; index++) {
  26318. var geometry = this.geometries[index];
  26319. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26320. return false;
  26321. }
  26322. }
  26323. // Meshes
  26324. for (index = 0; index < this.meshes.length; index++) {
  26325. var mesh = this.meshes[index];
  26326. if (!mesh.isEnabled()) {
  26327. continue;
  26328. }
  26329. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26330. continue;
  26331. }
  26332. if (!mesh.isReady(true)) {
  26333. return false;
  26334. }
  26335. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  26336. // Is Ready For Mesh
  26337. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  26338. var step = _a[_i];
  26339. if (!step.action(mesh, hardwareInstancedRendering)) {
  26340. return false;
  26341. }
  26342. }
  26343. }
  26344. // Post-processes
  26345. if (this.activeCameras && this.activeCameras.length > 0) {
  26346. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  26347. var camera = _c[_b];
  26348. if (!camera.isReady(true)) {
  26349. return false;
  26350. }
  26351. }
  26352. }
  26353. else if (this.activeCamera) {
  26354. if (!this.activeCamera.isReady(true)) {
  26355. return false;
  26356. }
  26357. }
  26358. // Particles
  26359. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26360. var particleSystem = _e[_d];
  26361. if (!particleSystem.isReady()) {
  26362. return false;
  26363. }
  26364. }
  26365. return true;
  26366. };
  26367. /** Resets all cached information relative to material (including effect and visibility) */
  26368. Scene.prototype.resetCachedMaterial = function () {
  26369. this._cachedMaterial = null;
  26370. this._cachedEffect = null;
  26371. this._cachedVisibility = null;
  26372. };
  26373. /**
  26374. * Registers a function to be called before every frame render
  26375. * @param func defines the function to register
  26376. */
  26377. Scene.prototype.registerBeforeRender = function (func) {
  26378. this.onBeforeRenderObservable.add(func);
  26379. };
  26380. /**
  26381. * Unregisters a function called before every frame render
  26382. * @param func defines the function to unregister
  26383. */
  26384. Scene.prototype.unregisterBeforeRender = function (func) {
  26385. this.onBeforeRenderObservable.removeCallback(func);
  26386. };
  26387. /**
  26388. * Registers a function to be called after every frame render
  26389. * @param func defines the function to register
  26390. */
  26391. Scene.prototype.registerAfterRender = function (func) {
  26392. this.onAfterRenderObservable.add(func);
  26393. };
  26394. /**
  26395. * Unregisters a function called after every frame render
  26396. * @param func defines the function to unregister
  26397. */
  26398. Scene.prototype.unregisterAfterRender = function (func) {
  26399. this.onAfterRenderObservable.removeCallback(func);
  26400. };
  26401. Scene.prototype._executeOnceBeforeRender = function (func) {
  26402. var _this = this;
  26403. var execFunc = function () {
  26404. func();
  26405. setTimeout(function () {
  26406. _this.unregisterBeforeRender(execFunc);
  26407. });
  26408. };
  26409. this.registerBeforeRender(execFunc);
  26410. };
  26411. /**
  26412. * The provided function will run before render once and will be disposed afterwards.
  26413. * A timeout delay can be provided so that the function will be executed in N ms.
  26414. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26415. * @param func The function to be executed.
  26416. * @param timeout optional delay in ms
  26417. */
  26418. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26419. var _this = this;
  26420. if (timeout !== undefined) {
  26421. setTimeout(function () {
  26422. _this._executeOnceBeforeRender(func);
  26423. }, timeout);
  26424. }
  26425. else {
  26426. this._executeOnceBeforeRender(func);
  26427. }
  26428. };
  26429. /** @hidden */
  26430. Scene.prototype._addPendingData = function (data) {
  26431. this._pendingData.push(data);
  26432. };
  26433. /** @hidden */
  26434. Scene.prototype._removePendingData = function (data) {
  26435. var wasLoading = this.isLoading;
  26436. var index = this._pendingData.indexOf(data);
  26437. if (index !== -1) {
  26438. this._pendingData.splice(index, 1);
  26439. }
  26440. if (wasLoading && !this.isLoading) {
  26441. this.onDataLoadedObservable.notifyObservers(this);
  26442. }
  26443. };
  26444. /**
  26445. * Returns the number of items waiting to be loaded
  26446. * @returns the number of items waiting to be loaded
  26447. */
  26448. Scene.prototype.getWaitingItemsCount = function () {
  26449. return this._pendingData.length;
  26450. };
  26451. Object.defineProperty(Scene.prototype, "isLoading", {
  26452. /**
  26453. * Returns a boolean indicating if the scene is still loading data
  26454. */
  26455. get: function () {
  26456. return this._pendingData.length > 0;
  26457. },
  26458. enumerable: true,
  26459. configurable: true
  26460. });
  26461. /**
  26462. * Registers a function to be executed when the scene is ready
  26463. * @param {Function} func - the function to be executed
  26464. */
  26465. Scene.prototype.executeWhenReady = function (func) {
  26466. var _this = this;
  26467. this.onReadyObservable.add(func);
  26468. if (this._executeWhenReadyTimeoutId !== -1) {
  26469. return;
  26470. }
  26471. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26472. _this._checkIsReady();
  26473. }, 150);
  26474. };
  26475. /**
  26476. * Returns a promise that resolves when the scene is ready
  26477. * @returns A promise that resolves when the scene is ready
  26478. */
  26479. Scene.prototype.whenReadyAsync = function () {
  26480. var _this = this;
  26481. return new Promise(function (resolve) {
  26482. _this.executeWhenReady(function () {
  26483. resolve();
  26484. });
  26485. });
  26486. };
  26487. /** @hidden */
  26488. Scene.prototype._checkIsReady = function () {
  26489. var _this = this;
  26490. this._registerTransientComponents();
  26491. if (this.isReady()) {
  26492. this.onReadyObservable.notifyObservers(this);
  26493. this.onReadyObservable.clear();
  26494. this._executeWhenReadyTimeoutId = -1;
  26495. return;
  26496. }
  26497. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26498. _this._checkIsReady();
  26499. }, 150);
  26500. };
  26501. // Animations
  26502. /**
  26503. * Will start the animation sequence of a given target
  26504. * @param target defines the target
  26505. * @param from defines from which frame should animation start
  26506. * @param to defines until which frame should animation run.
  26507. * @param weight defines the weight to apply to the animation (1.0 by default)
  26508. * @param loop defines if the animation loops
  26509. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26510. * @param onAnimationEnd defines the function to be executed when the animation ends
  26511. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26512. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26513. * @returns the animatable object created for this animation
  26514. */
  26515. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  26516. if (weight === void 0) { weight = 1.0; }
  26517. if (speedRatio === void 0) { speedRatio = 1.0; }
  26518. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  26519. returnedAnimatable.weight = weight;
  26520. return returnedAnimatable;
  26521. };
  26522. /**
  26523. * Will start the animation sequence of a given target
  26524. * @param target defines the target
  26525. * @param from defines from which frame should animation start
  26526. * @param to defines until which frame should animation run.
  26527. * @param loop defines if the animation loops
  26528. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26529. * @param onAnimationEnd defines the function to be executed when the animation ends
  26530. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26531. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26532. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26533. * @returns the animatable object created for this animation
  26534. */
  26535. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26536. if (speedRatio === void 0) { speedRatio = 1.0; }
  26537. if (stopCurrent === void 0) { stopCurrent = true; }
  26538. if (from > to && speedRatio > 0) {
  26539. speedRatio *= -1;
  26540. }
  26541. if (stopCurrent) {
  26542. this.stopAnimation(target, undefined, targetMask);
  26543. }
  26544. if (!animatable) {
  26545. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26546. }
  26547. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26548. // Local animations
  26549. if (target.animations && shouldRunTargetAnimations) {
  26550. animatable.appendAnimations(target, target.animations);
  26551. }
  26552. // Children animations
  26553. if (target.getAnimatables) {
  26554. var animatables = target.getAnimatables();
  26555. for (var index = 0; index < animatables.length; index++) {
  26556. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26557. }
  26558. }
  26559. animatable.reset();
  26560. return animatable;
  26561. };
  26562. /**
  26563. * Begin a new animation on a given node
  26564. * @param target defines the target where the animation will take place
  26565. * @param animations defines the list of animations to start
  26566. * @param from defines the initial value
  26567. * @param to defines the final value
  26568. * @param loop defines if you want animation to loop (off by default)
  26569. * @param speedRatio defines the speed ratio to apply to all animations
  26570. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26571. * @returns the list of created animatables
  26572. */
  26573. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26574. if (speedRatio === undefined) {
  26575. speedRatio = 1.0;
  26576. }
  26577. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26578. return animatable;
  26579. };
  26580. /**
  26581. * Begin a new animation on a given node and its hierarchy
  26582. * @param target defines the root node where the animation will take place
  26583. * @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.
  26584. * @param animations defines the list of animations to start
  26585. * @param from defines the initial value
  26586. * @param to defines the final value
  26587. * @param loop defines if you want animation to loop (off by default)
  26588. * @param speedRatio defines the speed ratio to apply to all animations
  26589. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26590. * @returns the list of animatables created for all nodes
  26591. */
  26592. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26593. var children = target.getDescendants(directDescendantsOnly);
  26594. var result = [];
  26595. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26596. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26597. var child = children_1[_i];
  26598. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26599. }
  26600. return result;
  26601. };
  26602. /**
  26603. * Gets the animatable associated with a specific target
  26604. * @param target defines the target of the animatable
  26605. * @returns the required animatable if found
  26606. */
  26607. Scene.prototype.getAnimatableByTarget = function (target) {
  26608. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26609. if (this._activeAnimatables[index].target === target) {
  26610. return this._activeAnimatables[index];
  26611. }
  26612. }
  26613. return null;
  26614. };
  26615. /**
  26616. * Gets all animatables associated with a given target
  26617. * @param target defines the target to look animatables for
  26618. * @returns an array of Animatables
  26619. */
  26620. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26621. var result = [];
  26622. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26623. if (this._activeAnimatables[index].target === target) {
  26624. result.push(this._activeAnimatables[index]);
  26625. }
  26626. }
  26627. return result;
  26628. };
  26629. Object.defineProperty(Scene.prototype, "animatables", {
  26630. /**
  26631. * Gets all animatable attached to the scene
  26632. */
  26633. get: function () {
  26634. return this._activeAnimatables;
  26635. },
  26636. enumerable: true,
  26637. configurable: true
  26638. });
  26639. /**
  26640. * Will stop the animation of the given target
  26641. * @param target - the target
  26642. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26643. * @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)
  26644. */
  26645. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26646. var animatables = this.getAllAnimatablesByTarget(target);
  26647. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26648. var animatable = animatables_1[_i];
  26649. animatable.stop(animationName, targetMask);
  26650. }
  26651. };
  26652. /**
  26653. * Stops and removes all animations that have been applied to the scene
  26654. */
  26655. Scene.prototype.stopAllAnimations = function () {
  26656. if (this._activeAnimatables) {
  26657. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26658. this._activeAnimatables[i].stop();
  26659. }
  26660. this._activeAnimatables = [];
  26661. }
  26662. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26663. var group = _a[_i];
  26664. group.stop();
  26665. }
  26666. };
  26667. Scene.prototype._animate = function () {
  26668. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26669. return;
  26670. }
  26671. // Getting time
  26672. var now = BABYLON.Tools.Now;
  26673. if (!this._animationTimeLast) {
  26674. if (this._pendingData.length > 0) {
  26675. return;
  26676. }
  26677. this._animationTimeLast = now;
  26678. }
  26679. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26680. this._animationTime += deltaTime;
  26681. this._animationTimeLast = now;
  26682. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26683. this._activeAnimatables[index]._animate(this._animationTime);
  26684. }
  26685. // Late animation bindings
  26686. this._processLateAnimationBindings();
  26687. };
  26688. /** @hidden */
  26689. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26690. var target = runtimeAnimation.target;
  26691. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26692. if (!target._lateAnimationHolders) {
  26693. target._lateAnimationHolders = {};
  26694. }
  26695. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26696. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26697. totalWeight: 0,
  26698. animations: [],
  26699. originalValue: originalValue
  26700. };
  26701. }
  26702. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26703. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26704. };
  26705. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26706. var normalizer = 1.0;
  26707. var finalPosition = BABYLON.Tmp.Vector3[0];
  26708. var finalScaling = BABYLON.Tmp.Vector3[1];
  26709. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26710. var startIndex = 0;
  26711. var originalAnimation = holder.animations[0];
  26712. var originalValue = holder.originalValue;
  26713. var scale = 1;
  26714. if (holder.totalWeight < 1.0) {
  26715. // We need to mix the original value in
  26716. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26717. scale = 1.0 - holder.totalWeight;
  26718. }
  26719. else {
  26720. startIndex = 1;
  26721. // We need to normalize the weights
  26722. normalizer = holder.totalWeight;
  26723. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26724. scale = originalAnimation.weight / normalizer;
  26725. if (scale == 1) {
  26726. return originalAnimation.currentValue;
  26727. }
  26728. }
  26729. finalScaling.scaleInPlace(scale);
  26730. finalPosition.scaleInPlace(scale);
  26731. finalQuaternion.scaleInPlace(scale);
  26732. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26733. var runtimeAnimation = holder.animations[animIndex];
  26734. var scale = runtimeAnimation.weight / normalizer;
  26735. var currentPosition = BABYLON.Tmp.Vector3[2];
  26736. var currentScaling = BABYLON.Tmp.Vector3[3];
  26737. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26738. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26739. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26740. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26741. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26742. }
  26743. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26744. return originalAnimation._workValue;
  26745. };
  26746. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26747. var originalAnimation = holder.animations[0];
  26748. var originalValue = holder.originalValue;
  26749. if (holder.animations.length === 1) {
  26750. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26751. return refQuaternion;
  26752. }
  26753. var normalizer = 1.0;
  26754. var quaternions;
  26755. var weights;
  26756. if (holder.totalWeight < 1.0) {
  26757. var scale = 1.0 - holder.totalWeight;
  26758. quaternions = [];
  26759. weights = [];
  26760. quaternions.push(originalValue);
  26761. weights.push(scale);
  26762. }
  26763. else {
  26764. if (holder.animations.length === 2) { // Slerp as soon as we can
  26765. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26766. return refQuaternion;
  26767. }
  26768. quaternions = [];
  26769. weights = [];
  26770. normalizer = holder.totalWeight;
  26771. }
  26772. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26773. var runtimeAnimation = holder.animations[animIndex];
  26774. quaternions.push(runtimeAnimation.currentValue);
  26775. weights.push(runtimeAnimation.weight / normalizer);
  26776. }
  26777. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26778. var cumulativeAmount = 0;
  26779. var cumulativeQuaternion = null;
  26780. for (var index = 0; index < quaternions.length;) {
  26781. if (!cumulativeQuaternion) {
  26782. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26783. cumulativeQuaternion = refQuaternion;
  26784. cumulativeAmount = weights[index] + weights[index + 1];
  26785. index += 2;
  26786. continue;
  26787. }
  26788. cumulativeAmount += weights[index];
  26789. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26790. index++;
  26791. }
  26792. return cumulativeQuaternion;
  26793. };
  26794. Scene.prototype._processLateAnimationBindings = function () {
  26795. if (!this._registeredForLateAnimationBindings.length) {
  26796. return;
  26797. }
  26798. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26799. var target = this._registeredForLateAnimationBindings.data[index];
  26800. for (var path in target._lateAnimationHolders) {
  26801. var holder = target._lateAnimationHolders[path];
  26802. var originalAnimation = holder.animations[0];
  26803. var originalValue = holder.originalValue;
  26804. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26805. var finalValue = target[path];
  26806. if (matrixDecomposeMode) {
  26807. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26808. }
  26809. else {
  26810. var quaternionMode = originalValue.w !== undefined;
  26811. if (quaternionMode) {
  26812. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26813. }
  26814. else {
  26815. var startIndex = 0;
  26816. var normalizer = 1.0;
  26817. if (holder.totalWeight < 1.0) {
  26818. // We need to mix the original value in
  26819. if (originalValue.scale) {
  26820. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26821. }
  26822. else {
  26823. finalValue = originalValue * (1.0 - holder.totalWeight);
  26824. }
  26825. }
  26826. else {
  26827. // We need to normalize the weights
  26828. normalizer = holder.totalWeight;
  26829. var scale_1 = originalAnimation.weight / normalizer;
  26830. if (scale_1 !== 1) {
  26831. if (originalAnimation.currentValue.scale) {
  26832. finalValue = originalAnimation.currentValue.scale(scale_1);
  26833. }
  26834. else {
  26835. finalValue = originalAnimation.currentValue * scale_1;
  26836. }
  26837. }
  26838. else {
  26839. finalValue = originalAnimation.currentValue;
  26840. }
  26841. startIndex = 1;
  26842. }
  26843. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26844. var runtimeAnimation = holder.animations[animIndex];
  26845. var scale = runtimeAnimation.weight / normalizer;
  26846. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26847. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26848. }
  26849. else {
  26850. finalValue += runtimeAnimation.currentValue * scale;
  26851. }
  26852. }
  26853. }
  26854. }
  26855. target[path] = finalValue;
  26856. }
  26857. target._lateAnimationHolders = {};
  26858. }
  26859. this._registeredForLateAnimationBindings.reset();
  26860. };
  26861. // Matrix
  26862. /** @hidden */
  26863. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26864. this._useAlternateCameraConfiguration = active;
  26865. };
  26866. /**
  26867. * Gets the current view matrix
  26868. * @returns a Matrix
  26869. */
  26870. Scene.prototype.getViewMatrix = function () {
  26871. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26872. };
  26873. /**
  26874. * Gets the current projection matrix
  26875. * @returns a Matrix
  26876. */
  26877. Scene.prototype.getProjectionMatrix = function () {
  26878. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26879. };
  26880. /**
  26881. * Gets the current transform matrix
  26882. * @returns a Matrix made of View * Projection
  26883. */
  26884. Scene.prototype.getTransformMatrix = function () {
  26885. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26886. };
  26887. /**
  26888. * Sets the current transform matrix
  26889. * @param view defines the View matrix to use
  26890. * @param projection defines the Projection matrix to use
  26891. */
  26892. Scene.prototype.setTransformMatrix = function (view, projection) {
  26893. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26894. return;
  26895. }
  26896. this._viewUpdateFlag = view.updateFlag;
  26897. this._projectionUpdateFlag = projection.updateFlag;
  26898. this._viewMatrix = view;
  26899. this._projectionMatrix = projection;
  26900. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26901. // Update frustum
  26902. if (!this._frustumPlanes) {
  26903. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26904. }
  26905. else {
  26906. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26907. }
  26908. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26909. var otherCamera = this.activeCamera._alternateCamera;
  26910. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26911. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26912. }
  26913. if (this._sceneUbo.useUbo) {
  26914. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26915. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26916. this._sceneUbo.update();
  26917. }
  26918. };
  26919. /** @hidden */
  26920. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26921. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26922. return;
  26923. }
  26924. this._alternateViewUpdateFlag = view.updateFlag;
  26925. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26926. this._alternateViewMatrix = view;
  26927. this._alternateProjectionMatrix = projection;
  26928. if (!this._alternateTransformMatrix) {
  26929. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26930. }
  26931. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26932. if (!this._alternateSceneUbo) {
  26933. this._createAlternateUbo();
  26934. }
  26935. if (this._alternateSceneUbo.useUbo) {
  26936. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26937. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26938. this._alternateSceneUbo.update();
  26939. }
  26940. };
  26941. /**
  26942. * Gets the uniform buffer used to store scene data
  26943. * @returns a UniformBuffer
  26944. */
  26945. Scene.prototype.getSceneUniformBuffer = function () {
  26946. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26947. };
  26948. /**
  26949. * Gets an unique (relatively to the current scene) Id
  26950. * @returns an unique number for the scene
  26951. */
  26952. Scene.prototype.getUniqueId = function () {
  26953. var result = Scene._uniqueIdCounter;
  26954. Scene._uniqueIdCounter++;
  26955. return result;
  26956. };
  26957. /**
  26958. * Add a mesh to the list of scene's meshes
  26959. * @param newMesh defines the mesh to add
  26960. * @param recursive if all child meshes should also be added to the scene
  26961. */
  26962. Scene.prototype.addMesh = function (newMesh, recursive) {
  26963. var _this = this;
  26964. if (recursive === void 0) { recursive = false; }
  26965. this.meshes.push(newMesh);
  26966. //notify the collision coordinator
  26967. if (this.collisionCoordinator) {
  26968. this.collisionCoordinator.onMeshAdded(newMesh);
  26969. }
  26970. newMesh._resyncLightSources();
  26971. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26972. if (recursive) {
  26973. newMesh.getChildMeshes().forEach(function (m) {
  26974. _this.addMesh(m);
  26975. });
  26976. }
  26977. };
  26978. /**
  26979. * Remove a mesh for the list of scene's meshes
  26980. * @param toRemove defines the mesh to remove
  26981. * @param recursive if all child meshes should also be removed from the scene
  26982. * @returns the index where the mesh was in the mesh list
  26983. */
  26984. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26985. var _this = this;
  26986. if (recursive === void 0) { recursive = false; }
  26987. var index = this.meshes.indexOf(toRemove);
  26988. if (index !== -1) {
  26989. // Remove from the scene if mesh found
  26990. this.meshes.splice(index, 1);
  26991. }
  26992. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26993. if (recursive) {
  26994. toRemove.getChildMeshes().forEach(function (m) {
  26995. _this.removeMesh(m);
  26996. });
  26997. }
  26998. return index;
  26999. };
  27000. /**
  27001. * Add a transform node to the list of scene's transform nodes
  27002. * @param newTransformNode defines the transform node to add
  27003. */
  27004. Scene.prototype.addTransformNode = function (newTransformNode) {
  27005. this.transformNodes.push(newTransformNode);
  27006. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  27007. };
  27008. /**
  27009. * Remove a transform node for the list of scene's transform nodes
  27010. * @param toRemove defines the transform node to remove
  27011. * @returns the index where the transform node was in the transform node list
  27012. */
  27013. Scene.prototype.removeTransformNode = function (toRemove) {
  27014. var index = this.transformNodes.indexOf(toRemove);
  27015. if (index !== -1) {
  27016. // Remove from the scene if found
  27017. this.transformNodes.splice(index, 1);
  27018. }
  27019. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  27020. return index;
  27021. };
  27022. /**
  27023. * Remove a skeleton for the list of scene's skeletons
  27024. * @param toRemove defines the skeleton to remove
  27025. * @returns the index where the skeleton was in the skeleton list
  27026. */
  27027. Scene.prototype.removeSkeleton = function (toRemove) {
  27028. var index = this.skeletons.indexOf(toRemove);
  27029. if (index !== -1) {
  27030. // Remove from the scene if found
  27031. this.skeletons.splice(index, 1);
  27032. }
  27033. return index;
  27034. };
  27035. /**
  27036. * Remove a morph target for the list of scene's morph targets
  27037. * @param toRemove defines the morph target to remove
  27038. * @returns the index where the morph target was in the morph target list
  27039. */
  27040. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  27041. var index = this.morphTargetManagers.indexOf(toRemove);
  27042. if (index !== -1) {
  27043. // Remove from the scene if found
  27044. this.morphTargetManagers.splice(index, 1);
  27045. }
  27046. return index;
  27047. };
  27048. /**
  27049. * Remove a light for the list of scene's lights
  27050. * @param toRemove defines the light to remove
  27051. * @returns the index where the light was in the light list
  27052. */
  27053. Scene.prototype.removeLight = function (toRemove) {
  27054. var index = this.lights.indexOf(toRemove);
  27055. if (index !== -1) {
  27056. // Remove from meshes
  27057. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27058. var mesh = _a[_i];
  27059. mesh._removeLightSource(toRemove);
  27060. }
  27061. // Remove from the scene if mesh found
  27062. this.lights.splice(index, 1);
  27063. this.sortLightsByPriority();
  27064. }
  27065. this.onLightRemovedObservable.notifyObservers(toRemove);
  27066. return index;
  27067. };
  27068. /**
  27069. * Remove a camera for the list of scene's cameras
  27070. * @param toRemove defines the camera to remove
  27071. * @returns the index where the camera was in the camera list
  27072. */
  27073. Scene.prototype.removeCamera = function (toRemove) {
  27074. var index = this.cameras.indexOf(toRemove);
  27075. if (index !== -1) {
  27076. // Remove from the scene if mesh found
  27077. this.cameras.splice(index, 1);
  27078. }
  27079. // Remove from activeCameras
  27080. var index2 = this.activeCameras.indexOf(toRemove);
  27081. if (index2 !== -1) {
  27082. // Remove from the scene if mesh found
  27083. this.activeCameras.splice(index2, 1);
  27084. }
  27085. // Reset the activeCamera
  27086. if (this.activeCamera === toRemove) {
  27087. if (this.cameras.length > 0) {
  27088. this.activeCamera = this.cameras[0];
  27089. }
  27090. else {
  27091. this.activeCamera = null;
  27092. }
  27093. }
  27094. this.onCameraRemovedObservable.notifyObservers(toRemove);
  27095. return index;
  27096. };
  27097. /**
  27098. * Remove a particle system for the list of scene's particle systems
  27099. * @param toRemove defines the particle system to remove
  27100. * @returns the index where the particle system was in the particle system list
  27101. */
  27102. Scene.prototype.removeParticleSystem = function (toRemove) {
  27103. var index = this.particleSystems.indexOf(toRemove);
  27104. if (index !== -1) {
  27105. this.particleSystems.splice(index, 1);
  27106. }
  27107. return index;
  27108. };
  27109. /**
  27110. * Remove a animation for the list of scene's animations
  27111. * @param toRemove defines the animation to remove
  27112. * @returns the index where the animation was in the animation list
  27113. */
  27114. Scene.prototype.removeAnimation = function (toRemove) {
  27115. var index = this.animations.indexOf(toRemove);
  27116. if (index !== -1) {
  27117. this.animations.splice(index, 1);
  27118. }
  27119. return index;
  27120. };
  27121. /**
  27122. * Removes the given animation group from this scene.
  27123. * @param toRemove The animation group to remove
  27124. * @returns The index of the removed animation group
  27125. */
  27126. Scene.prototype.removeAnimationGroup = function (toRemove) {
  27127. var index = this.animationGroups.indexOf(toRemove);
  27128. if (index !== -1) {
  27129. this.animationGroups.splice(index, 1);
  27130. }
  27131. return index;
  27132. };
  27133. /**
  27134. * Removes the given multi-material from this scene.
  27135. * @param toRemove The multi-material to remove
  27136. * @returns The index of the removed multi-material
  27137. */
  27138. Scene.prototype.removeMultiMaterial = function (toRemove) {
  27139. var index = this.multiMaterials.indexOf(toRemove);
  27140. if (index !== -1) {
  27141. this.multiMaterials.splice(index, 1);
  27142. }
  27143. return index;
  27144. };
  27145. /**
  27146. * Removes the given material from this scene.
  27147. * @param toRemove The material to remove
  27148. * @returns The index of the removed material
  27149. */
  27150. Scene.prototype.removeMaterial = function (toRemove) {
  27151. var index = this.materials.indexOf(toRemove);
  27152. if (index !== -1) {
  27153. this.materials.splice(index, 1);
  27154. }
  27155. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  27156. return index;
  27157. };
  27158. /**
  27159. * Removes the given action manager from this scene.
  27160. * @param toRemove The action manager to remove
  27161. * @returns The index of the removed action manager
  27162. */
  27163. Scene.prototype.removeActionManager = function (toRemove) {
  27164. var index = this.actionManagers.indexOf(toRemove);
  27165. if (index !== -1) {
  27166. this.actionManagers.splice(index, 1);
  27167. }
  27168. return index;
  27169. };
  27170. /**
  27171. * Removes the given texture from this scene.
  27172. * @param toRemove The texture to remove
  27173. * @returns The index of the removed texture
  27174. */
  27175. Scene.prototype.removeTexture = function (toRemove) {
  27176. var index = this.textures.indexOf(toRemove);
  27177. if (index !== -1) {
  27178. this.textures.splice(index, 1);
  27179. }
  27180. this.onTextureRemovedObservable.notifyObservers(toRemove);
  27181. return index;
  27182. };
  27183. /**
  27184. * Adds the given light to this scene
  27185. * @param newLight The light to add
  27186. */
  27187. Scene.prototype.addLight = function (newLight) {
  27188. this.lights.push(newLight);
  27189. this.sortLightsByPriority();
  27190. // Add light to all meshes (To support if the light is removed and then readded)
  27191. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27192. var mesh = _a[_i];
  27193. if (mesh._lightSources.indexOf(newLight) === -1) {
  27194. mesh._lightSources.push(newLight);
  27195. mesh._resyncLightSources();
  27196. }
  27197. }
  27198. this.onNewLightAddedObservable.notifyObservers(newLight);
  27199. };
  27200. /**
  27201. * Sorts the list list based on light priorities
  27202. */
  27203. Scene.prototype.sortLightsByPriority = function () {
  27204. if (this.requireLightSorting) {
  27205. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  27206. }
  27207. };
  27208. /**
  27209. * Adds the given camera to this scene
  27210. * @param newCamera The camera to add
  27211. */
  27212. Scene.prototype.addCamera = function (newCamera) {
  27213. this.cameras.push(newCamera);
  27214. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  27215. };
  27216. /**
  27217. * Adds the given skeleton to this scene
  27218. * @param newSkeleton The skeleton to add
  27219. */
  27220. Scene.prototype.addSkeleton = function (newSkeleton) {
  27221. this.skeletons.push(newSkeleton);
  27222. };
  27223. /**
  27224. * Adds the given particle system to this scene
  27225. * @param newParticleSystem The particle system to add
  27226. */
  27227. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  27228. this.particleSystems.push(newParticleSystem);
  27229. };
  27230. /**
  27231. * Adds the given animation to this scene
  27232. * @param newAnimation The animation to add
  27233. */
  27234. Scene.prototype.addAnimation = function (newAnimation) {
  27235. this.animations.push(newAnimation);
  27236. };
  27237. /**
  27238. * Adds the given animation group to this scene.
  27239. * @param newAnimationGroup The animation group to add
  27240. */
  27241. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  27242. this.animationGroups.push(newAnimationGroup);
  27243. };
  27244. /**
  27245. * Adds the given multi-material to this scene
  27246. * @param newMultiMaterial The multi-material to add
  27247. */
  27248. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  27249. this.multiMaterials.push(newMultiMaterial);
  27250. };
  27251. /**
  27252. * Adds the given material to this scene
  27253. * @param newMaterial The material to add
  27254. */
  27255. Scene.prototype.addMaterial = function (newMaterial) {
  27256. this.materials.push(newMaterial);
  27257. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  27258. };
  27259. /**
  27260. * Adds the given morph target to this scene
  27261. * @param newMorphTargetManager The morph target to add
  27262. */
  27263. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  27264. this.morphTargetManagers.push(newMorphTargetManager);
  27265. };
  27266. /**
  27267. * Adds the given geometry to this scene
  27268. * @param newGeometry The geometry to add
  27269. */
  27270. Scene.prototype.addGeometry = function (newGeometry) {
  27271. this.geometries.push(newGeometry);
  27272. };
  27273. /**
  27274. * Adds the given action manager to this scene
  27275. * @param newActionManager The action manager to add
  27276. */
  27277. Scene.prototype.addActionManager = function (newActionManager) {
  27278. this.actionManagers.push(newActionManager);
  27279. };
  27280. /**
  27281. * Adds the given texture to this scene.
  27282. * @param newTexture The texture to add
  27283. */
  27284. Scene.prototype.addTexture = function (newTexture) {
  27285. this.textures.push(newTexture);
  27286. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  27287. };
  27288. /**
  27289. * Switch active camera
  27290. * @param newCamera defines the new active camera
  27291. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  27292. */
  27293. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  27294. if (attachControl === void 0) { attachControl = true; }
  27295. var canvas = this._engine.getRenderingCanvas();
  27296. if (!canvas) {
  27297. return;
  27298. }
  27299. if (this.activeCamera) {
  27300. this.activeCamera.detachControl(canvas);
  27301. }
  27302. this.activeCamera = newCamera;
  27303. if (attachControl) {
  27304. newCamera.attachControl(canvas);
  27305. }
  27306. };
  27307. /**
  27308. * sets the active camera of the scene using its ID
  27309. * @param id defines the camera's ID
  27310. * @return the new active camera or null if none found.
  27311. */
  27312. Scene.prototype.setActiveCameraByID = function (id) {
  27313. var camera = this.getCameraByID(id);
  27314. if (camera) {
  27315. this.activeCamera = camera;
  27316. return camera;
  27317. }
  27318. return null;
  27319. };
  27320. /**
  27321. * sets the active camera of the scene using its name
  27322. * @param name defines the camera's name
  27323. * @returns the new active camera or null if none found.
  27324. */
  27325. Scene.prototype.setActiveCameraByName = function (name) {
  27326. var camera = this.getCameraByName(name);
  27327. if (camera) {
  27328. this.activeCamera = camera;
  27329. return camera;
  27330. }
  27331. return null;
  27332. };
  27333. /**
  27334. * get an animation group using its name
  27335. * @param name defines the material's name
  27336. * @return the animation group or null if none found.
  27337. */
  27338. Scene.prototype.getAnimationGroupByName = function (name) {
  27339. for (var index = 0; index < this.animationGroups.length; index++) {
  27340. if (this.animationGroups[index].name === name) {
  27341. return this.animationGroups[index];
  27342. }
  27343. }
  27344. return null;
  27345. };
  27346. /**
  27347. * get a material using its id
  27348. * @param id defines the material's ID
  27349. * @return the material or null if none found.
  27350. */
  27351. Scene.prototype.getMaterialByID = function (id) {
  27352. for (var index = 0; index < this.materials.length; index++) {
  27353. if (this.materials[index].id === id) {
  27354. return this.materials[index];
  27355. }
  27356. }
  27357. return null;
  27358. };
  27359. /**
  27360. * Gets a material using its name
  27361. * @param name defines the material's name
  27362. * @return the material or null if none found.
  27363. */
  27364. Scene.prototype.getMaterialByName = function (name) {
  27365. for (var index = 0; index < this.materials.length; index++) {
  27366. if (this.materials[index].name === name) {
  27367. return this.materials[index];
  27368. }
  27369. }
  27370. return null;
  27371. };
  27372. /**
  27373. * Gets a camera using its id
  27374. * @param id defines the id to look for
  27375. * @returns the camera or null if not found
  27376. */
  27377. Scene.prototype.getCameraByID = function (id) {
  27378. for (var index = 0; index < this.cameras.length; index++) {
  27379. if (this.cameras[index].id === id) {
  27380. return this.cameras[index];
  27381. }
  27382. }
  27383. return null;
  27384. };
  27385. /**
  27386. * Gets a camera using its unique id
  27387. * @param uniqueId defines the unique id to look for
  27388. * @returns the camera or null if not found
  27389. */
  27390. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27391. for (var index = 0; index < this.cameras.length; index++) {
  27392. if (this.cameras[index].uniqueId === uniqueId) {
  27393. return this.cameras[index];
  27394. }
  27395. }
  27396. return null;
  27397. };
  27398. /**
  27399. * Gets a camera using its name
  27400. * @param name defines the camera's name
  27401. * @return the camera or null if none found.
  27402. */
  27403. Scene.prototype.getCameraByName = function (name) {
  27404. for (var index = 0; index < this.cameras.length; index++) {
  27405. if (this.cameras[index].name === name) {
  27406. return this.cameras[index];
  27407. }
  27408. }
  27409. return null;
  27410. };
  27411. /**
  27412. * Gets a bone using its id
  27413. * @param id defines the bone's id
  27414. * @return the bone or null if not found
  27415. */
  27416. Scene.prototype.getBoneByID = function (id) {
  27417. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27418. var skeleton = this.skeletons[skeletonIndex];
  27419. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27420. if (skeleton.bones[boneIndex].id === id) {
  27421. return skeleton.bones[boneIndex];
  27422. }
  27423. }
  27424. }
  27425. return null;
  27426. };
  27427. /**
  27428. * Gets a bone using its id
  27429. * @param name defines the bone's name
  27430. * @return the bone or null if not found
  27431. */
  27432. Scene.prototype.getBoneByName = function (name) {
  27433. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27434. var skeleton = this.skeletons[skeletonIndex];
  27435. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27436. if (skeleton.bones[boneIndex].name === name) {
  27437. return skeleton.bones[boneIndex];
  27438. }
  27439. }
  27440. }
  27441. return null;
  27442. };
  27443. /**
  27444. * Gets a light node using its name
  27445. * @param name defines the the light's name
  27446. * @return the light or null if none found.
  27447. */
  27448. Scene.prototype.getLightByName = function (name) {
  27449. for (var index = 0; index < this.lights.length; index++) {
  27450. if (this.lights[index].name === name) {
  27451. return this.lights[index];
  27452. }
  27453. }
  27454. return null;
  27455. };
  27456. /**
  27457. * Gets a light node using its id
  27458. * @param id defines the light's id
  27459. * @return the light or null if none found.
  27460. */
  27461. Scene.prototype.getLightByID = function (id) {
  27462. for (var index = 0; index < this.lights.length; index++) {
  27463. if (this.lights[index].id === id) {
  27464. return this.lights[index];
  27465. }
  27466. }
  27467. return null;
  27468. };
  27469. /**
  27470. * Gets a light node using its scene-generated unique ID
  27471. * @param uniqueId defines the light's unique id
  27472. * @return the light or null if none found.
  27473. */
  27474. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27475. for (var index = 0; index < this.lights.length; index++) {
  27476. if (this.lights[index].uniqueId === uniqueId) {
  27477. return this.lights[index];
  27478. }
  27479. }
  27480. return null;
  27481. };
  27482. /**
  27483. * Gets a particle system by id
  27484. * @param id defines the particle system id
  27485. * @return the corresponding system or null if none found
  27486. */
  27487. Scene.prototype.getParticleSystemByID = function (id) {
  27488. for (var index = 0; index < this.particleSystems.length; index++) {
  27489. if (this.particleSystems[index].id === id) {
  27490. return this.particleSystems[index];
  27491. }
  27492. }
  27493. return null;
  27494. };
  27495. /**
  27496. * Gets a geometry using its ID
  27497. * @param id defines the geometry's id
  27498. * @return the geometry or null if none found.
  27499. */
  27500. Scene.prototype.getGeometryByID = function (id) {
  27501. for (var index = 0; index < this.geometries.length; index++) {
  27502. if (this.geometries[index].id === id) {
  27503. return this.geometries[index];
  27504. }
  27505. }
  27506. return null;
  27507. };
  27508. /**
  27509. * Add a new geometry to this scene
  27510. * @param geometry defines the geometry to be added to the scene.
  27511. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27512. * @return a boolean defining if the geometry was added or not
  27513. */
  27514. Scene.prototype.pushGeometry = function (geometry, force) {
  27515. if (!force && this.getGeometryByID(geometry.id)) {
  27516. return false;
  27517. }
  27518. this.geometries.push(geometry);
  27519. //notify the collision coordinator
  27520. if (this.collisionCoordinator) {
  27521. this.collisionCoordinator.onGeometryAdded(geometry);
  27522. }
  27523. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27524. return true;
  27525. };
  27526. /**
  27527. * Removes an existing geometry
  27528. * @param geometry defines the geometry to be removed from the scene
  27529. * @return a boolean defining if the geometry was removed or not
  27530. */
  27531. Scene.prototype.removeGeometry = function (geometry) {
  27532. var index = this.geometries.indexOf(geometry);
  27533. if (index > -1) {
  27534. this.geometries.splice(index, 1);
  27535. //notify the collision coordinator
  27536. if (this.collisionCoordinator) {
  27537. this.collisionCoordinator.onGeometryDeleted(geometry);
  27538. }
  27539. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27540. return true;
  27541. }
  27542. return false;
  27543. };
  27544. /**
  27545. * Gets the list of geometries attached to the scene
  27546. * @returns an array of Geometry
  27547. */
  27548. Scene.prototype.getGeometries = function () {
  27549. return this.geometries;
  27550. };
  27551. /**
  27552. * Gets the first added mesh found of a given ID
  27553. * @param id defines the id to search for
  27554. * @return the mesh found or null if not found at all
  27555. */
  27556. Scene.prototype.getMeshByID = function (id) {
  27557. for (var index = 0; index < this.meshes.length; index++) {
  27558. if (this.meshes[index].id === id) {
  27559. return this.meshes[index];
  27560. }
  27561. }
  27562. return null;
  27563. };
  27564. /**
  27565. * Gets a list of meshes using their id
  27566. * @param id defines the id to search for
  27567. * @returns a list of meshes
  27568. */
  27569. Scene.prototype.getMeshesByID = function (id) {
  27570. return this.meshes.filter(function (m) {
  27571. return m.id === id;
  27572. });
  27573. };
  27574. /**
  27575. * Gets the first added transform node found of a given ID
  27576. * @param id defines the id to search for
  27577. * @return the found transform node or null if not found at all.
  27578. */
  27579. Scene.prototype.getTransformNodeByID = function (id) {
  27580. for (var index = 0; index < this.transformNodes.length; index++) {
  27581. if (this.transformNodes[index].id === id) {
  27582. return this.transformNodes[index];
  27583. }
  27584. }
  27585. return null;
  27586. };
  27587. /**
  27588. * Gets a list of transform nodes using their id
  27589. * @param id defines the id to search for
  27590. * @returns a list of transform nodes
  27591. */
  27592. Scene.prototype.getTransformNodesByID = function (id) {
  27593. return this.transformNodes.filter(function (m) {
  27594. return m.id === id;
  27595. });
  27596. };
  27597. /**
  27598. * Gets a mesh with its auto-generated unique id
  27599. * @param uniqueId defines the unique id to search for
  27600. * @return the found mesh or null if not found at all.
  27601. */
  27602. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27603. for (var index = 0; index < this.meshes.length; index++) {
  27604. if (this.meshes[index].uniqueId === uniqueId) {
  27605. return this.meshes[index];
  27606. }
  27607. }
  27608. return null;
  27609. };
  27610. /**
  27611. * Gets a the last added mesh using a given id
  27612. * @param id defines the id to search for
  27613. * @return the found mesh or null if not found at all.
  27614. */
  27615. Scene.prototype.getLastMeshByID = function (id) {
  27616. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27617. if (this.meshes[index].id === id) {
  27618. return this.meshes[index];
  27619. }
  27620. }
  27621. return null;
  27622. };
  27623. /**
  27624. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27625. * @param id defines the id to search for
  27626. * @return the found node or null if not found at all
  27627. */
  27628. Scene.prototype.getLastEntryByID = function (id) {
  27629. var index;
  27630. for (index = this.meshes.length - 1; index >= 0; index--) {
  27631. if (this.meshes[index].id === id) {
  27632. return this.meshes[index];
  27633. }
  27634. }
  27635. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27636. if (this.transformNodes[index].id === id) {
  27637. return this.transformNodes[index];
  27638. }
  27639. }
  27640. for (index = this.cameras.length - 1; index >= 0; index--) {
  27641. if (this.cameras[index].id === id) {
  27642. return this.cameras[index];
  27643. }
  27644. }
  27645. for (index = this.lights.length - 1; index >= 0; index--) {
  27646. if (this.lights[index].id === id) {
  27647. return this.lights[index];
  27648. }
  27649. }
  27650. return null;
  27651. };
  27652. /**
  27653. * Gets a node (Mesh, Camera, Light) using a given id
  27654. * @param id defines the id to search for
  27655. * @return the found node or null if not found at all
  27656. */
  27657. Scene.prototype.getNodeByID = function (id) {
  27658. var mesh = this.getMeshByID(id);
  27659. if (mesh) {
  27660. return mesh;
  27661. }
  27662. var light = this.getLightByID(id);
  27663. if (light) {
  27664. return light;
  27665. }
  27666. var camera = this.getCameraByID(id);
  27667. if (camera) {
  27668. return camera;
  27669. }
  27670. var bone = this.getBoneByID(id);
  27671. return bone;
  27672. };
  27673. /**
  27674. * Gets a node (Mesh, Camera, Light) using a given name
  27675. * @param name defines the name to search for
  27676. * @return the found node or null if not found at all.
  27677. */
  27678. Scene.prototype.getNodeByName = function (name) {
  27679. var mesh = this.getMeshByName(name);
  27680. if (mesh) {
  27681. return mesh;
  27682. }
  27683. var light = this.getLightByName(name);
  27684. if (light) {
  27685. return light;
  27686. }
  27687. var camera = this.getCameraByName(name);
  27688. if (camera) {
  27689. return camera;
  27690. }
  27691. var bone = this.getBoneByName(name);
  27692. return bone;
  27693. };
  27694. /**
  27695. * Gets a mesh using a given name
  27696. * @param name defines the name to search for
  27697. * @return the found mesh or null if not found at all.
  27698. */
  27699. Scene.prototype.getMeshByName = function (name) {
  27700. for (var index = 0; index < this.meshes.length; index++) {
  27701. if (this.meshes[index].name === name) {
  27702. return this.meshes[index];
  27703. }
  27704. }
  27705. return null;
  27706. };
  27707. /**
  27708. * Gets a transform node using a given name
  27709. * @param name defines the name to search for
  27710. * @return the found transform node or null if not found at all.
  27711. */
  27712. Scene.prototype.getTransformNodeByName = function (name) {
  27713. for (var index = 0; index < this.transformNodes.length; index++) {
  27714. if (this.transformNodes[index].name === name) {
  27715. return this.transformNodes[index];
  27716. }
  27717. }
  27718. return null;
  27719. };
  27720. /**
  27721. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27722. * @param id defines the id to search for
  27723. * @return the found skeleton or null if not found at all.
  27724. */
  27725. Scene.prototype.getLastSkeletonByID = function (id) {
  27726. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27727. if (this.skeletons[index].id === id) {
  27728. return this.skeletons[index];
  27729. }
  27730. }
  27731. return null;
  27732. };
  27733. /**
  27734. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27735. * @param id defines the id to search for
  27736. * @return the found skeleton or null if not found at all.
  27737. */
  27738. Scene.prototype.getSkeletonById = function (id) {
  27739. for (var index = 0; index < this.skeletons.length; index++) {
  27740. if (this.skeletons[index].id === id) {
  27741. return this.skeletons[index];
  27742. }
  27743. }
  27744. return null;
  27745. };
  27746. /**
  27747. * Gets a skeleton using a given name
  27748. * @param name defines the name to search for
  27749. * @return the found skeleton or null if not found at all.
  27750. */
  27751. Scene.prototype.getSkeletonByName = function (name) {
  27752. for (var index = 0; index < this.skeletons.length; index++) {
  27753. if (this.skeletons[index].name === name) {
  27754. return this.skeletons[index];
  27755. }
  27756. }
  27757. return null;
  27758. };
  27759. /**
  27760. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27761. * @param id defines the id to search for
  27762. * @return the found morph target manager or null if not found at all.
  27763. */
  27764. Scene.prototype.getMorphTargetManagerById = function (id) {
  27765. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27766. if (this.morphTargetManagers[index].uniqueId === id) {
  27767. return this.morphTargetManagers[index];
  27768. }
  27769. }
  27770. return null;
  27771. };
  27772. /**
  27773. * Gets a boolean indicating if the given mesh is active
  27774. * @param mesh defines the mesh to look for
  27775. * @returns true if the mesh is in the active list
  27776. */
  27777. Scene.prototype.isActiveMesh = function (mesh) {
  27778. return (this._activeMeshes.indexOf(mesh) !== -1);
  27779. };
  27780. Object.defineProperty(Scene.prototype, "uid", {
  27781. /**
  27782. * Return a unique id as a string which can serve as an identifier for the scene
  27783. */
  27784. get: function () {
  27785. if (!this._uid) {
  27786. this._uid = BABYLON.Tools.RandomId();
  27787. }
  27788. return this._uid;
  27789. },
  27790. enumerable: true,
  27791. configurable: true
  27792. });
  27793. /**
  27794. * Add an externaly attached data from its key.
  27795. * This method call will fail and return false, if such key already exists.
  27796. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27797. * @param key the unique key that identifies the data
  27798. * @param data the data object to associate to the key for this Engine instance
  27799. * @return true if no such key were already present and the data was added successfully, false otherwise
  27800. */
  27801. Scene.prototype.addExternalData = function (key, data) {
  27802. if (!this._externalData) {
  27803. this._externalData = new BABYLON.StringDictionary();
  27804. }
  27805. return this._externalData.add(key, data);
  27806. };
  27807. /**
  27808. * Get an externaly attached data from its key
  27809. * @param key the unique key that identifies the data
  27810. * @return the associated data, if present (can be null), or undefined if not present
  27811. */
  27812. Scene.prototype.getExternalData = function (key) {
  27813. if (!this._externalData) {
  27814. return null;
  27815. }
  27816. return this._externalData.get(key);
  27817. };
  27818. /**
  27819. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27820. * @param key the unique key that identifies the data
  27821. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27822. * @return the associated data, can be null if the factory returned null.
  27823. */
  27824. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27825. if (!this._externalData) {
  27826. this._externalData = new BABYLON.StringDictionary();
  27827. }
  27828. return this._externalData.getOrAddWithFactory(key, factory);
  27829. };
  27830. /**
  27831. * Remove an externaly attached data from the Engine instance
  27832. * @param key the unique key that identifies the data
  27833. * @return true if the data was successfully removed, false if it doesn't exist
  27834. */
  27835. Scene.prototype.removeExternalData = function (key) {
  27836. return this._externalData.remove(key);
  27837. };
  27838. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27839. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27840. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27841. var step = _a[_i];
  27842. step.action(mesh, subMesh);
  27843. }
  27844. var material = subMesh.getMaterial();
  27845. if (material !== null && material !== undefined) {
  27846. // Render targets
  27847. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  27848. if (this._processedMaterials.indexOf(material) === -1) {
  27849. this._processedMaterials.push(material);
  27850. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27851. }
  27852. }
  27853. // Dispatch
  27854. this._activeIndices.addCount(subMesh.indexCount, false);
  27855. this._renderingManager.dispatch(subMesh, mesh, material);
  27856. }
  27857. }
  27858. };
  27859. /**
  27860. * Clear the processed materials smart array preventing retention point in material dispose.
  27861. */
  27862. Scene.prototype.freeProcessedMaterials = function () {
  27863. this._processedMaterials.dispose();
  27864. };
  27865. /**
  27866. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27867. */
  27868. Scene.prototype.freeActiveMeshes = function () {
  27869. this._activeMeshes.dispose();
  27870. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27871. this.activeCamera._activeMeshes.dispose();
  27872. }
  27873. if (this.activeCameras) {
  27874. for (var i = 0; i < this.activeCameras.length; i++) {
  27875. var activeCamera = this.activeCameras[i];
  27876. if (activeCamera && activeCamera._activeMeshes) {
  27877. activeCamera._activeMeshes.dispose();
  27878. }
  27879. }
  27880. }
  27881. };
  27882. /**
  27883. * Clear the info related to rendering groups preventing retention points during dispose.
  27884. */
  27885. Scene.prototype.freeRenderingGroups = function () {
  27886. if (this._renderingManager) {
  27887. this._renderingManager.freeRenderingGroups();
  27888. }
  27889. if (this.textures) {
  27890. for (var i = 0; i < this.textures.length; i++) {
  27891. var texture = this.textures[i];
  27892. if (texture && texture.renderList) {
  27893. texture.freeRenderingGroups();
  27894. }
  27895. }
  27896. }
  27897. };
  27898. /** @hidden */
  27899. Scene.prototype._isInIntermediateRendering = function () {
  27900. return this._intermediateRendering;
  27901. };
  27902. /**
  27903. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27904. * @returns the current scene
  27905. */
  27906. Scene.prototype.freezeActiveMeshes = function () {
  27907. if (!this.activeCamera) {
  27908. return this;
  27909. }
  27910. if (!this._frustumPlanes) {
  27911. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27912. }
  27913. this._evaluateActiveMeshes();
  27914. this._activeMeshesFrozen = true;
  27915. return this;
  27916. };
  27917. /**
  27918. * Use this function to restart evaluating active meshes on every frame
  27919. * @returns the current scene
  27920. */
  27921. Scene.prototype.unfreezeActiveMeshes = function () {
  27922. this._activeMeshesFrozen = false;
  27923. return this;
  27924. };
  27925. Scene.prototype._evaluateActiveMeshes = function () {
  27926. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27927. return;
  27928. }
  27929. if (!this.activeCamera) {
  27930. return;
  27931. }
  27932. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27933. this.activeCamera._activeMeshes.reset();
  27934. this._activeMeshes.reset();
  27935. this._renderingManager.reset();
  27936. this._processedMaterials.reset();
  27937. this._activeParticleSystems.reset();
  27938. this._activeSkeletons.reset();
  27939. this._softwareSkinnedMeshes.reset();
  27940. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27941. var step = _a[_i];
  27942. step.action();
  27943. }
  27944. // Determine mesh candidates
  27945. var meshes = this.getActiveMeshCandidates();
  27946. // Check each mesh
  27947. var len = meshes.length;
  27948. for (var i = 0; i < len; i++) {
  27949. var mesh = meshes.data[i];
  27950. if (mesh.isBlocked) {
  27951. continue;
  27952. }
  27953. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27954. if (!mesh.isReady() || !mesh.isEnabled()) {
  27955. continue;
  27956. }
  27957. mesh.computeWorldMatrix();
  27958. // Intersections
  27959. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27960. this._meshesForIntersections.pushNoDuplicate(mesh);
  27961. }
  27962. // Switch to current LOD
  27963. var meshLOD = mesh.getLOD(this.activeCamera);
  27964. if (meshLOD === undefined || meshLOD === null) {
  27965. continue;
  27966. }
  27967. mesh._preActivate();
  27968. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27969. this._activeMeshes.push(mesh);
  27970. this.activeCamera._activeMeshes.push(mesh);
  27971. mesh._activate(this._renderId);
  27972. if (meshLOD !== mesh) {
  27973. meshLOD._activate(this._renderId);
  27974. }
  27975. this._activeMesh(mesh, meshLOD);
  27976. }
  27977. }
  27978. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27979. // Particle systems
  27980. if (this.particlesEnabled) {
  27981. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27982. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27983. var particleSystem = this.particleSystems[particleIndex];
  27984. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27985. continue;
  27986. }
  27987. var emitter = particleSystem.emitter;
  27988. if (!emitter.position || emitter.isEnabled()) {
  27989. this._activeParticleSystems.push(particleSystem);
  27990. particleSystem.animate();
  27991. this._renderingManager.dispatchParticles(particleSystem);
  27992. }
  27993. }
  27994. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27995. }
  27996. };
  27997. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27998. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27999. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  28000. mesh.skeleton.prepare();
  28001. }
  28002. if (!mesh.computeBonesUsingShaders) {
  28003. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  28004. }
  28005. }
  28006. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  28007. var step = _a[_i];
  28008. step.action(sourceMesh, mesh);
  28009. }
  28010. if (mesh !== undefined && mesh !== null
  28011. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  28012. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  28013. var len = subMeshes.length;
  28014. for (var i = 0; i < len; i++) {
  28015. var subMesh = subMeshes.data[i];
  28016. this._evaluateSubMesh(subMesh, mesh);
  28017. }
  28018. }
  28019. };
  28020. /**
  28021. * Update the transform matrix to update from the current active camera
  28022. * @param force defines a boolean used to force the update even if cache is up to date
  28023. */
  28024. Scene.prototype.updateTransformMatrix = function (force) {
  28025. if (!this.activeCamera) {
  28026. return;
  28027. }
  28028. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  28029. };
  28030. /**
  28031. * 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)
  28032. * @param alternateCamera defines the camera to use
  28033. */
  28034. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  28035. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  28036. };
  28037. Scene.prototype._renderForCamera = function (camera, rigParent) {
  28038. if (camera && camera._skipRendering) {
  28039. return;
  28040. }
  28041. var engine = this._engine;
  28042. this.activeCamera = camera;
  28043. if (!this.activeCamera)
  28044. throw new Error("Active camera not set");
  28045. // Viewport
  28046. engine.setViewport(this.activeCamera.viewport);
  28047. // Camera
  28048. this.resetCachedMaterial();
  28049. this._renderId++;
  28050. this.updateTransformMatrix();
  28051. if (camera._alternateCamera) {
  28052. this.updateAlternateTransformMatrix(camera._alternateCamera);
  28053. this._alternateRendering = true;
  28054. }
  28055. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  28056. // Meshes
  28057. this._evaluateActiveMeshes();
  28058. // Software skinning
  28059. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  28060. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  28061. mesh.applySkeleton(mesh.skeleton);
  28062. }
  28063. // Render targets
  28064. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28065. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  28066. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  28067. }
  28068. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  28069. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  28070. }
  28071. // Collects render targets from external components.
  28072. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  28073. var step = _a[_i];
  28074. step.action(this._renderTargets);
  28075. }
  28076. if (this.renderTargetsEnabled) {
  28077. this._intermediateRendering = true;
  28078. if (this._renderTargets.length > 0) {
  28079. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28080. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  28081. var renderTarget = this._renderTargets.data[renderIndex];
  28082. if (renderTarget._shouldRender()) {
  28083. this._renderId++;
  28084. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  28085. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  28086. }
  28087. }
  28088. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28089. this._renderId++;
  28090. }
  28091. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  28092. var step = _c[_b];
  28093. step.action(this.activeCamera);
  28094. }
  28095. this._intermediateRendering = false;
  28096. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  28097. }
  28098. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28099. // Prepare Frame
  28100. if (this.postProcessManager) {
  28101. this.postProcessManager._prepareFrame();
  28102. }
  28103. // Before Camera Draw
  28104. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  28105. var step = _e[_d];
  28106. step.action(this.activeCamera);
  28107. }
  28108. // Render
  28109. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  28110. this._renderingManager.render(null, null, true, true);
  28111. this.onAfterDrawPhaseObservable.notifyObservers(this);
  28112. // After Camera Draw
  28113. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  28114. var step = _g[_f];
  28115. step.action(this.activeCamera);
  28116. }
  28117. // Finalize frame
  28118. if (this.postProcessManager) {
  28119. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  28120. }
  28121. // Reset some special arrays
  28122. this._renderTargets.reset();
  28123. this._alternateRendering = false;
  28124. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  28125. };
  28126. Scene.prototype._processSubCameras = function (camera) {
  28127. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  28128. this._renderForCamera(camera);
  28129. return;
  28130. }
  28131. // rig cameras
  28132. for (var index = 0; index < camera._rigCameras.length; index++) {
  28133. this._renderForCamera(camera._rigCameras[index], camera);
  28134. }
  28135. this.activeCamera = camera;
  28136. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28137. };
  28138. Scene.prototype._checkIntersections = function () {
  28139. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  28140. var sourceMesh = this._meshesForIntersections.data[index];
  28141. if (!sourceMesh.actionManager) {
  28142. continue;
  28143. }
  28144. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  28145. var action = sourceMesh.actionManager.actions[actionIndex];
  28146. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28147. var parameters = action.getTriggerParameter();
  28148. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  28149. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  28150. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  28151. if (areIntersecting && currentIntersectionInProgress === -1) {
  28152. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  28153. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28154. sourceMesh._intersectionsInProgress.push(otherMesh);
  28155. }
  28156. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28157. sourceMesh._intersectionsInProgress.push(otherMesh);
  28158. }
  28159. }
  28160. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  28161. //They intersected, and now they don't.
  28162. //is this trigger an exit trigger? execute an event.
  28163. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28164. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28165. }
  28166. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  28167. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  28168. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  28169. return otherMesh === parameterMesh;
  28170. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28171. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  28172. }
  28173. }
  28174. }
  28175. }
  28176. }
  28177. };
  28178. /** @hidden */
  28179. Scene.prototype._advancePhysicsEngineStep = function (step) {
  28180. // Do nothing. Code will be replaced if physics engine component is referenced
  28181. };
  28182. /**
  28183. * Render the scene
  28184. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  28185. */
  28186. Scene.prototype.render = function (updateCameras) {
  28187. if (updateCameras === void 0) { updateCameras = true; }
  28188. if (this.isDisposed) {
  28189. return;
  28190. }
  28191. this._frameId++;
  28192. // Register components that have been associated lately to the scene.
  28193. this._registerTransientComponents();
  28194. this._activeParticles.fetchNewFrame();
  28195. this._totalVertices.fetchNewFrame();
  28196. this._activeIndices.fetchNewFrame();
  28197. this._activeBones.fetchNewFrame();
  28198. this._meshesForIntersections.reset();
  28199. this.resetCachedMaterial();
  28200. this.onBeforeAnimationsObservable.notifyObservers(this);
  28201. // Actions
  28202. if (this.actionManager) {
  28203. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  28204. }
  28205. if (this._engine.isDeterministicLockStep()) {
  28206. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  28207. var defaultFPS = (60.0 / 1000.0);
  28208. var defaultFrameTime = this.getDeterministicFrameTime();
  28209. var stepsTaken = 0;
  28210. var maxSubSteps = this._engine.getLockstepMaxSteps();
  28211. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  28212. internalSteps = Math.min(internalSteps, maxSubSteps);
  28213. do {
  28214. this.onBeforeStepObservable.notifyObservers(this);
  28215. // Animations
  28216. this._animationRatio = defaultFrameTime * defaultFPS;
  28217. this._animate();
  28218. this.onAfterAnimationsObservable.notifyObservers(this);
  28219. // Physics
  28220. this._advancePhysicsEngineStep(defaultFrameTime);
  28221. this.onAfterStepObservable.notifyObservers(this);
  28222. this._currentStepId++;
  28223. stepsTaken++;
  28224. deltaTime -= defaultFrameTime;
  28225. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28226. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28227. }
  28228. else {
  28229. // Animations
  28230. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28231. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28232. this._animate();
  28233. this.onAfterAnimationsObservable.notifyObservers(this);
  28234. // Physics
  28235. this._advancePhysicsEngineStep(deltaTime);
  28236. }
  28237. // Before camera update steps
  28238. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  28239. var step = _a[_i];
  28240. step.action();
  28241. }
  28242. // Update Cameras
  28243. if (updateCameras) {
  28244. if (this.activeCameras.length > 0) {
  28245. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28246. var camera = this.activeCameras[cameraIndex];
  28247. camera.update();
  28248. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28249. // rig cameras
  28250. for (var index = 0; index < camera._rigCameras.length; index++) {
  28251. camera._rigCameras[index].update();
  28252. }
  28253. }
  28254. }
  28255. }
  28256. else if (this.activeCamera) {
  28257. this.activeCamera.update();
  28258. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28259. // rig cameras
  28260. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28261. this.activeCamera._rigCameras[index].update();
  28262. }
  28263. }
  28264. }
  28265. }
  28266. // Before render
  28267. this.onBeforeRenderObservable.notifyObservers(this);
  28268. // Customs render targets
  28269. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28270. var engine = this.getEngine();
  28271. var currentActiveCamera = this.activeCamera;
  28272. if (this.renderTargetsEnabled) {
  28273. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28274. this._intermediateRendering = true;
  28275. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28276. var renderTarget = this.customRenderTargets[customIndex];
  28277. if (renderTarget._shouldRender()) {
  28278. this._renderId++;
  28279. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28280. if (!this.activeCamera)
  28281. throw new Error("Active camera not set");
  28282. // Viewport
  28283. engine.setViewport(this.activeCamera.viewport);
  28284. // Camera
  28285. this.updateTransformMatrix();
  28286. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28287. }
  28288. }
  28289. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28290. this._intermediateRendering = false;
  28291. this._renderId++;
  28292. }
  28293. // Restore back buffer
  28294. if (this.customRenderTargets.length > 0) {
  28295. engine.restoreDefaultFramebuffer();
  28296. }
  28297. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28298. this.activeCamera = currentActiveCamera;
  28299. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  28300. var step = _c[_b];
  28301. step.action();
  28302. }
  28303. // Clear
  28304. if (this.autoClearDepthAndStencil || this.autoClear) {
  28305. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28306. }
  28307. // Collects render targets from external components.
  28308. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  28309. var step = _e[_d];
  28310. step.action(this._renderTargets);
  28311. }
  28312. // Multi-cameras?
  28313. if (this.activeCameras.length > 0) {
  28314. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28315. if (cameraIndex > 0) {
  28316. this._engine.clear(null, false, true, true);
  28317. }
  28318. this._processSubCameras(this.activeCameras[cameraIndex]);
  28319. }
  28320. }
  28321. else {
  28322. if (!this.activeCamera) {
  28323. throw new Error("No camera defined");
  28324. }
  28325. this._processSubCameras(this.activeCamera);
  28326. }
  28327. // Intersection checks
  28328. this._checkIntersections();
  28329. // Executes the after render stage actions.
  28330. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  28331. var step = _g[_f];
  28332. step.action();
  28333. }
  28334. // After render
  28335. if (this.afterRender) {
  28336. this.afterRender();
  28337. }
  28338. this.onAfterRenderObservable.notifyObservers(this);
  28339. // Cleaning
  28340. if (this._toBeDisposed.length) {
  28341. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28342. var data = this._toBeDisposed[index];
  28343. if (data) {
  28344. data.dispose();
  28345. }
  28346. }
  28347. this._toBeDisposed = [];
  28348. }
  28349. if (this.dumpNextRenderTargets) {
  28350. this.dumpNextRenderTargets = false;
  28351. }
  28352. this._activeBones.addCount(0, true);
  28353. this._activeIndices.addCount(0, true);
  28354. this._activeParticles.addCount(0, true);
  28355. };
  28356. /**
  28357. * Freeze all materials
  28358. * A frozen material will not be updatable but should be faster to render
  28359. */
  28360. Scene.prototype.freezeMaterials = function () {
  28361. for (var i = 0; i < this.materials.length; i++) {
  28362. this.materials[i].freeze();
  28363. }
  28364. };
  28365. /**
  28366. * Unfreeze all materials
  28367. * A frozen material will not be updatable but should be faster to render
  28368. */
  28369. Scene.prototype.unfreezeMaterials = function () {
  28370. for (var i = 0; i < this.materials.length; i++) {
  28371. this.materials[i].unfreeze();
  28372. }
  28373. };
  28374. /**
  28375. * Releases all held ressources
  28376. */
  28377. Scene.prototype.dispose = function () {
  28378. this.beforeRender = null;
  28379. this.afterRender = null;
  28380. this.skeletons = [];
  28381. this.morphTargetManagers = [];
  28382. this._transientComponents = [];
  28383. this._isReadyForMeshStage.clear();
  28384. this._beforeEvaluateActiveMeshStage.clear();
  28385. this._evaluateSubMeshStage.clear();
  28386. this._activeMeshStage.clear();
  28387. this._cameraDrawRenderTargetStage.clear();
  28388. this._beforeCameraDrawStage.clear();
  28389. this._beforeRenderingGroupDrawStage.clear();
  28390. this._beforeRenderingMeshStage.clear();
  28391. this._afterRenderingMeshStage.clear();
  28392. this._afterRenderingGroupDrawStage.clear();
  28393. this._afterCameraDrawStage.clear();
  28394. this._afterRenderStage.clear();
  28395. this._beforeCameraUpdateStage.clear();
  28396. this._beforeClearStage.clear();
  28397. this._gatherRenderTargetsStage.clear();
  28398. this._gatherActiveCameraRenderTargetsStage.clear();
  28399. this._pointerMoveStage.clear();
  28400. this._pointerDownStage.clear();
  28401. this._pointerUpStage.clear();
  28402. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28403. var component = _a[_i];
  28404. component.dispose();
  28405. }
  28406. this.importedMeshesFiles = new Array();
  28407. this.stopAllAnimations();
  28408. this.resetCachedMaterial();
  28409. // Smart arrays
  28410. if (this.activeCamera) {
  28411. this.activeCamera._activeMeshes.dispose();
  28412. this.activeCamera = null;
  28413. }
  28414. this._activeMeshes.dispose();
  28415. this._renderingManager.dispose();
  28416. this._processedMaterials.dispose();
  28417. this._activeParticleSystems.dispose();
  28418. this._activeSkeletons.dispose();
  28419. this._softwareSkinnedMeshes.dispose();
  28420. this._renderTargets.dispose();
  28421. this._registeredForLateAnimationBindings.dispose();
  28422. this._meshesForIntersections.dispose();
  28423. this._toBeDisposed = [];
  28424. // Abort active requests
  28425. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28426. var request = _c[_b];
  28427. request.abort();
  28428. }
  28429. // Events
  28430. this.onDisposeObservable.notifyObservers(this);
  28431. this.onDisposeObservable.clear();
  28432. this.onBeforeRenderObservable.clear();
  28433. this.onAfterRenderObservable.clear();
  28434. this.onBeforeRenderTargetsRenderObservable.clear();
  28435. this.onAfterRenderTargetsRenderObservable.clear();
  28436. this.onAfterStepObservable.clear();
  28437. this.onBeforeStepObservable.clear();
  28438. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28439. this.onAfterActiveMeshesEvaluationObservable.clear();
  28440. this.onBeforeParticlesRenderingObservable.clear();
  28441. this.onAfterParticlesRenderingObservable.clear();
  28442. this.onBeforeDrawPhaseObservable.clear();
  28443. this.onAfterDrawPhaseObservable.clear();
  28444. this.onBeforeAnimationsObservable.clear();
  28445. this.onAfterAnimationsObservable.clear();
  28446. this.onDataLoadedObservable.clear();
  28447. this.onBeforeRenderingGroupObservable.clear();
  28448. this.onAfterRenderingGroupObservable.clear();
  28449. this.onMeshImportedObservable.clear();
  28450. this.onBeforeCameraRenderObservable.clear();
  28451. this.onAfterCameraRenderObservable.clear();
  28452. this.onReadyObservable.clear();
  28453. this.onNewCameraAddedObservable.clear();
  28454. this.onCameraRemovedObservable.clear();
  28455. this.onNewLightAddedObservable.clear();
  28456. this.onLightRemovedObservable.clear();
  28457. this.onNewGeometryAddedObservable.clear();
  28458. this.onGeometryRemovedObservable.clear();
  28459. this.onNewTransformNodeAddedObservable.clear();
  28460. this.onTransformNodeRemovedObservable.clear();
  28461. this.onNewMeshAddedObservable.clear();
  28462. this.onMeshRemovedObservable.clear();
  28463. this.onNewMaterialAddedObservable.clear();
  28464. this.onMaterialRemovedObservable.clear();
  28465. this.onNewTextureAddedObservable.clear();
  28466. this.onTextureRemovedObservable.clear();
  28467. this.onPrePointerObservable.clear();
  28468. this.onPointerObservable.clear();
  28469. this.onPreKeyboardObservable.clear();
  28470. this.onKeyboardObservable.clear();
  28471. this.detachControl();
  28472. // Detach cameras
  28473. var canvas = this._engine.getRenderingCanvas();
  28474. if (canvas) {
  28475. var index;
  28476. for (index = 0; index < this.cameras.length; index++) {
  28477. this.cameras[index].detachControl(canvas);
  28478. }
  28479. }
  28480. // Release animation groups
  28481. while (this.animationGroups.length) {
  28482. this.animationGroups[0].dispose();
  28483. }
  28484. // Release lights
  28485. while (this.lights.length) {
  28486. this.lights[0].dispose();
  28487. }
  28488. // Release meshes
  28489. while (this.meshes.length) {
  28490. this.meshes[0].dispose(true);
  28491. }
  28492. while (this.transformNodes.length) {
  28493. this.removeTransformNode(this.transformNodes[0]);
  28494. }
  28495. // Release cameras
  28496. while (this.cameras.length) {
  28497. this.cameras[0].dispose();
  28498. }
  28499. // Release materials
  28500. if (this.defaultMaterial) {
  28501. this.defaultMaterial.dispose();
  28502. }
  28503. while (this.multiMaterials.length) {
  28504. this.multiMaterials[0].dispose();
  28505. }
  28506. while (this.materials.length) {
  28507. this.materials[0].dispose();
  28508. }
  28509. // Release particles
  28510. while (this.particleSystems.length) {
  28511. this.particleSystems[0].dispose();
  28512. }
  28513. // Release postProcesses
  28514. while (this.postProcesses.length) {
  28515. this.postProcesses[0].dispose();
  28516. }
  28517. // Release textures
  28518. while (this.textures.length) {
  28519. this.textures[0].dispose();
  28520. }
  28521. // Release UBO
  28522. this._sceneUbo.dispose();
  28523. if (this._alternateSceneUbo) {
  28524. this._alternateSceneUbo.dispose();
  28525. }
  28526. // Post-processes
  28527. this.postProcessManager.dispose();
  28528. // Remove from engine
  28529. index = this._engine.scenes.indexOf(this);
  28530. if (index > -1) {
  28531. this._engine.scenes.splice(index, 1);
  28532. }
  28533. this._engine.wipeCaches(true);
  28534. this._isDisposed = true;
  28535. };
  28536. Object.defineProperty(Scene.prototype, "isDisposed", {
  28537. /**
  28538. * Gets if the scene is already disposed
  28539. */
  28540. get: function () {
  28541. return this._isDisposed;
  28542. },
  28543. enumerable: true,
  28544. configurable: true
  28545. });
  28546. /**
  28547. * Call this function to reduce memory footprint of the scene.
  28548. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28549. */
  28550. Scene.prototype.clearCachedVertexData = function () {
  28551. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28552. var mesh = this.meshes[meshIndex];
  28553. var geometry = mesh.geometry;
  28554. if (geometry) {
  28555. geometry._indices = [];
  28556. for (var vbName in geometry._vertexBuffers) {
  28557. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28558. continue;
  28559. }
  28560. geometry._vertexBuffers[vbName]._buffer._data = null;
  28561. }
  28562. }
  28563. }
  28564. };
  28565. /**
  28566. * This function will remove the local cached buffer data from texture.
  28567. * It will save memory but will prevent the texture from being rebuilt
  28568. */
  28569. Scene.prototype.cleanCachedTextureBuffer = function () {
  28570. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28571. var baseTexture = _a[_i];
  28572. var buffer = baseTexture._buffer;
  28573. if (buffer) {
  28574. baseTexture._buffer = null;
  28575. }
  28576. }
  28577. };
  28578. /**
  28579. * Get the world extend vectors with an optional filter
  28580. *
  28581. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28582. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28583. */
  28584. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28585. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28586. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28587. filterPredicate = filterPredicate || (function () { return true; });
  28588. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28589. mesh.computeWorldMatrix(true);
  28590. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28591. return;
  28592. }
  28593. var boundingInfo = mesh.getBoundingInfo();
  28594. var minBox = boundingInfo.boundingBox.minimumWorld;
  28595. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28596. BABYLON.Tools.CheckExtends(minBox, min, max);
  28597. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28598. });
  28599. return {
  28600. min: min,
  28601. max: max
  28602. };
  28603. };
  28604. // Picking
  28605. /**
  28606. * Creates a ray that can be used to pick in the scene
  28607. * @param x defines the x coordinate of the origin (on-screen)
  28608. * @param y defines the y coordinate of the origin (on-screen)
  28609. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28610. * @param camera defines the camera to use for the picking
  28611. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28612. * @returns a Ray
  28613. */
  28614. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28615. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28616. var result = BABYLON.Ray.Zero();
  28617. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28618. return result;
  28619. };
  28620. /**
  28621. * Creates a ray that can be used to pick in the scene
  28622. * @param x defines the x coordinate of the origin (on-screen)
  28623. * @param y defines the y coordinate of the origin (on-screen)
  28624. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28625. * @param result defines the ray where to store the picking ray
  28626. * @param camera defines the camera to use for the picking
  28627. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28628. * @returns the current scene
  28629. */
  28630. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28631. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28632. var engine = this._engine;
  28633. if (!camera) {
  28634. if (!this.activeCamera)
  28635. throw new Error("Active camera not set");
  28636. camera = this.activeCamera;
  28637. }
  28638. var cameraViewport = camera.viewport;
  28639. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28640. // Moving coordinates to local viewport world
  28641. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28642. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28643. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28644. return this;
  28645. };
  28646. /**
  28647. * Creates a ray that can be used to pick in the scene
  28648. * @param x defines the x coordinate of the origin (on-screen)
  28649. * @param y defines the y coordinate of the origin (on-screen)
  28650. * @param camera defines the camera to use for the picking
  28651. * @returns a Ray
  28652. */
  28653. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28654. var result = BABYLON.Ray.Zero();
  28655. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28656. return result;
  28657. };
  28658. /**
  28659. * Creates a ray that can be used to pick in the scene
  28660. * @param x defines the x coordinate of the origin (on-screen)
  28661. * @param y defines the y coordinate of the origin (on-screen)
  28662. * @param result defines the ray where to store the picking ray
  28663. * @param camera defines the camera to use for the picking
  28664. * @returns the current scene
  28665. */
  28666. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28667. if (!BABYLON.PickingInfo) {
  28668. return this;
  28669. }
  28670. var engine = this._engine;
  28671. if (!camera) {
  28672. if (!this.activeCamera)
  28673. throw new Error("Active camera not set");
  28674. camera = this.activeCamera;
  28675. }
  28676. var cameraViewport = camera.viewport;
  28677. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28678. var identity = BABYLON.Matrix.Identity();
  28679. // Moving coordinates to local viewport world
  28680. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28681. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28682. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28683. return this;
  28684. };
  28685. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28686. if (!BABYLON.PickingInfo) {
  28687. return null;
  28688. }
  28689. var pickingInfo = null;
  28690. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28691. var mesh = this.meshes[meshIndex];
  28692. if (predicate) {
  28693. if (!predicate(mesh)) {
  28694. continue;
  28695. }
  28696. }
  28697. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28698. continue;
  28699. }
  28700. var world = mesh.getWorldMatrix();
  28701. var ray = rayFunction(world);
  28702. var result = mesh.intersects(ray, fastCheck);
  28703. if (!result || !result.hit)
  28704. continue;
  28705. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28706. continue;
  28707. pickingInfo = result;
  28708. if (fastCheck) {
  28709. break;
  28710. }
  28711. }
  28712. return pickingInfo || new BABYLON.PickingInfo();
  28713. };
  28714. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28715. if (!BABYLON.PickingInfo) {
  28716. return null;
  28717. }
  28718. var pickingInfos = new Array();
  28719. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28720. var mesh = this.meshes[meshIndex];
  28721. if (predicate) {
  28722. if (!predicate(mesh)) {
  28723. continue;
  28724. }
  28725. }
  28726. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28727. continue;
  28728. }
  28729. var world = mesh.getWorldMatrix();
  28730. var ray = rayFunction(world);
  28731. var result = mesh.intersects(ray, false);
  28732. if (!result || !result.hit)
  28733. continue;
  28734. pickingInfos.push(result);
  28735. }
  28736. return pickingInfos;
  28737. };
  28738. /** Launch a ray to try to pick a mesh in the scene
  28739. * @param x position on screen
  28740. * @param y position on screen
  28741. * @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
  28742. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28743. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28744. * @returns a PickingInfo
  28745. */
  28746. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28747. var _this = this;
  28748. if (!BABYLON.PickingInfo) {
  28749. return null;
  28750. }
  28751. var result = this._internalPick(function (world) {
  28752. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28753. return _this._tempPickingRay;
  28754. }, predicate, fastCheck);
  28755. if (result) {
  28756. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28757. }
  28758. return result;
  28759. };
  28760. /** Use the given ray to pick a mesh in the scene
  28761. * @param ray The ray to use to pick meshes
  28762. * @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
  28763. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28764. * @returns a PickingInfo
  28765. */
  28766. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28767. var _this = this;
  28768. var result = this._internalPick(function (world) {
  28769. if (!_this._pickWithRayInverseMatrix) {
  28770. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28771. }
  28772. world.invertToRef(_this._pickWithRayInverseMatrix);
  28773. if (!_this._cachedRayForTransform) {
  28774. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28775. }
  28776. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28777. return _this._cachedRayForTransform;
  28778. }, predicate, fastCheck);
  28779. if (result) {
  28780. result.ray = ray;
  28781. }
  28782. return result;
  28783. };
  28784. /**
  28785. * Launch a ray to try to pick a mesh in the scene
  28786. * @param x X position on screen
  28787. * @param y Y position on screen
  28788. * @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
  28789. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28790. * @returns an array of PickingInfo
  28791. */
  28792. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28793. var _this = this;
  28794. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28795. };
  28796. /**
  28797. * Launch a ray to try to pick a mesh in the scene
  28798. * @param ray Ray to use
  28799. * @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
  28800. * @returns an array of PickingInfo
  28801. */
  28802. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28803. var _this = this;
  28804. return this._internalMultiPick(function (world) {
  28805. if (!_this._pickWithRayInverseMatrix) {
  28806. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28807. }
  28808. world.invertToRef(_this._pickWithRayInverseMatrix);
  28809. if (!_this._cachedRayForTransform) {
  28810. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28811. }
  28812. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28813. return _this._cachedRayForTransform;
  28814. }, predicate);
  28815. };
  28816. /**
  28817. * Force the value of meshUnderPointer
  28818. * @param mesh defines the mesh to use
  28819. */
  28820. Scene.prototype.setPointerOverMesh = function (mesh) {
  28821. if (this._pointerOverMesh === mesh) {
  28822. return;
  28823. }
  28824. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28825. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28826. }
  28827. this._pointerOverMesh = mesh;
  28828. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28829. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28830. }
  28831. };
  28832. /**
  28833. * Gets the mesh under the pointer
  28834. * @returns a Mesh or null if no mesh is under the pointer
  28835. */
  28836. Scene.prototype.getPointerOverMesh = function () {
  28837. return this._pointerOverMesh;
  28838. };
  28839. // Misc.
  28840. /** @hidden */
  28841. Scene.prototype._rebuildGeometries = function () {
  28842. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28843. var geometry = _a[_i];
  28844. geometry._rebuild();
  28845. }
  28846. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28847. var mesh = _c[_b];
  28848. mesh._rebuild();
  28849. }
  28850. if (this.postProcessManager) {
  28851. this.postProcessManager._rebuild();
  28852. }
  28853. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28854. var component = _e[_d];
  28855. component.rebuild();
  28856. }
  28857. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28858. var system = _g[_f];
  28859. system.rebuild();
  28860. }
  28861. };
  28862. /** @hidden */
  28863. Scene.prototype._rebuildTextures = function () {
  28864. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28865. var texture = _a[_i];
  28866. texture._rebuild();
  28867. }
  28868. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28869. };
  28870. // Tags
  28871. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28872. if (tagsQuery === undefined) {
  28873. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28874. return list;
  28875. }
  28876. var listByTags = [];
  28877. forEach = forEach || (function (item) { return; });
  28878. for (var i in list) {
  28879. var item = list[i];
  28880. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28881. listByTags.push(item);
  28882. forEach(item);
  28883. }
  28884. }
  28885. return listByTags;
  28886. };
  28887. /**
  28888. * Get a list of meshes by tags
  28889. * @param tagsQuery defines the tags query to use
  28890. * @param forEach defines a predicate used to filter results
  28891. * @returns an array of Mesh
  28892. */
  28893. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28894. return this._getByTags(this.meshes, tagsQuery, forEach);
  28895. };
  28896. /**
  28897. * Get a list of cameras by tags
  28898. * @param tagsQuery defines the tags query to use
  28899. * @param forEach defines a predicate used to filter results
  28900. * @returns an array of Camera
  28901. */
  28902. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28903. return this._getByTags(this.cameras, tagsQuery, forEach);
  28904. };
  28905. /**
  28906. * Get a list of lights by tags
  28907. * @param tagsQuery defines the tags query to use
  28908. * @param forEach defines a predicate used to filter results
  28909. * @returns an array of Light
  28910. */
  28911. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28912. return this._getByTags(this.lights, tagsQuery, forEach);
  28913. };
  28914. /**
  28915. * Get a list of materials by tags
  28916. * @param tagsQuery defines the tags query to use
  28917. * @param forEach defines a predicate used to filter results
  28918. * @returns an array of Material
  28919. */
  28920. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28921. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28922. };
  28923. /**
  28924. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28925. * This allowed control for front to back rendering or reversly depending of the special needs.
  28926. *
  28927. * @param renderingGroupId The rendering group id corresponding to its index
  28928. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28929. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28930. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28931. */
  28932. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28933. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28934. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28935. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28936. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28937. };
  28938. /**
  28939. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28940. *
  28941. * @param renderingGroupId The rendering group id corresponding to its index
  28942. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28943. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28944. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28945. */
  28946. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28947. if (depth === void 0) { depth = true; }
  28948. if (stencil === void 0) { stencil = true; }
  28949. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28950. };
  28951. /**
  28952. * Gets the current auto clear configuration for one rendering group of the rendering
  28953. * manager.
  28954. * @param index the rendering group index to get the information for
  28955. * @returns The auto clear setup for the requested rendering group
  28956. */
  28957. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28958. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28959. };
  28960. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  28961. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  28962. get: function () {
  28963. return this._blockMaterialDirtyMechanism;
  28964. },
  28965. set: function (value) {
  28966. if (this._blockMaterialDirtyMechanism === value) {
  28967. return;
  28968. }
  28969. this._blockMaterialDirtyMechanism = value;
  28970. if (!value) { // Do a complete update
  28971. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  28972. }
  28973. },
  28974. enumerable: true,
  28975. configurable: true
  28976. });
  28977. /**
  28978. * Will flag all materials as dirty to trigger new shader compilation
  28979. * @param flag defines the flag used to specify which material part must be marked as dirty
  28980. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28981. */
  28982. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28983. if (this._blockMaterialDirtyMechanism) {
  28984. return;
  28985. }
  28986. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28987. var material = _a[_i];
  28988. if (predicate && !predicate(material)) {
  28989. continue;
  28990. }
  28991. material.markAsDirty(flag);
  28992. }
  28993. };
  28994. /** @hidden */
  28995. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28996. var _this = this;
  28997. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28998. this._activeRequests.push(request);
  28999. request.onCompleteObservable.add(function (request) {
  29000. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29001. });
  29002. return request;
  29003. };
  29004. /** @hidden */
  29005. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29006. var _this = this;
  29007. return new Promise(function (resolve, reject) {
  29008. _this._loadFile(url, function (data) {
  29009. resolve(data);
  29010. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29011. reject(exception);
  29012. });
  29013. });
  29014. };
  29015. // Statics
  29016. Scene._uniqueIdCounter = 0;
  29017. /** The fog is deactivated */
  29018. Scene.FOGMODE_NONE = 0;
  29019. /** The fog density is following an exponential function */
  29020. Scene.FOGMODE_EXP = 1;
  29021. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  29022. Scene.FOGMODE_EXP2 = 2;
  29023. /** The fog density is following a linear function. */
  29024. Scene.FOGMODE_LINEAR = 3;
  29025. /**
  29026. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29027. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29028. */
  29029. Scene.MinDeltaTime = 1.0;
  29030. /**
  29031. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29032. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29033. */
  29034. Scene.MaxDeltaTime = 1000.0;
  29035. /** The distance in pixel that you have to move to prevent some events */
  29036. Scene.DragMovementThreshold = 10; // in pixels
  29037. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29038. Scene.LongPressDelay = 500; // in milliseconds
  29039. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29040. Scene.DoubleClickDelay = 300; // in milliseconds
  29041. /** If you need to check double click without raising a single click at first click, enable this flag */
  29042. Scene.ExclusiveDoubleClickMode = false;
  29043. return Scene;
  29044. }(BABYLON.AbstractScene));
  29045. BABYLON.Scene = Scene;
  29046. })(BABYLON || (BABYLON = {}));
  29047. //# sourceMappingURL=babylon.scene.js.map
  29048. var BABYLON;
  29049. (function (BABYLON) {
  29050. /**
  29051. * Set of assets to keep when moving a scene into an asset container.
  29052. */
  29053. var KeepAssets = /** @class */ (function (_super) {
  29054. __extends(KeepAssets, _super);
  29055. function KeepAssets() {
  29056. return _super !== null && _super.apply(this, arguments) || this;
  29057. }
  29058. return KeepAssets;
  29059. }(BABYLON.AbstractScene));
  29060. BABYLON.KeepAssets = KeepAssets;
  29061. /**
  29062. * Container with a set of assets that can be added or removed from a scene.
  29063. */
  29064. var AssetContainer = /** @class */ (function (_super) {
  29065. __extends(AssetContainer, _super);
  29066. /**
  29067. * Instantiates an AssetContainer.
  29068. * @param scene The scene the AssetContainer belongs to.
  29069. */
  29070. function AssetContainer(scene) {
  29071. var _this = _super.call(this) || this;
  29072. _this.scene = scene;
  29073. return _this;
  29074. }
  29075. /**
  29076. * Adds all the assets from the container to the scene.
  29077. */
  29078. AssetContainer.prototype.addAllToScene = function () {
  29079. var _this = this;
  29080. this.cameras.forEach(function (o) {
  29081. _this.scene.addCamera(o);
  29082. });
  29083. this.lights.forEach(function (o) {
  29084. _this.scene.addLight(o);
  29085. });
  29086. this.meshes.forEach(function (o) {
  29087. _this.scene.addMesh(o);
  29088. });
  29089. this.skeletons.forEach(function (o) {
  29090. _this.scene.addSkeleton(o);
  29091. });
  29092. this.animations.forEach(function (o) {
  29093. _this.scene.addAnimation(o);
  29094. });
  29095. this.animationGroups.forEach(function (o) {
  29096. _this.scene.addAnimationGroup(o);
  29097. });
  29098. this.multiMaterials.forEach(function (o) {
  29099. _this.scene.addMultiMaterial(o);
  29100. });
  29101. this.materials.forEach(function (o) {
  29102. _this.scene.addMaterial(o);
  29103. });
  29104. this.morphTargetManagers.forEach(function (o) {
  29105. _this.scene.addMorphTargetManager(o);
  29106. });
  29107. this.geometries.forEach(function (o) {
  29108. _this.scene.addGeometry(o);
  29109. });
  29110. this.transformNodes.forEach(function (o) {
  29111. _this.scene.addTransformNode(o);
  29112. });
  29113. this.actionManagers.forEach(function (o) {
  29114. _this.scene.addActionManager(o);
  29115. });
  29116. this.textures.forEach(function (o) {
  29117. _this.scene.addTexture(o);
  29118. });
  29119. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29120. var component = _a[_i];
  29121. component.addFromContainer(this.scene);
  29122. }
  29123. };
  29124. /**
  29125. * Removes all the assets in the container from the scene
  29126. */
  29127. AssetContainer.prototype.removeAllFromScene = function () {
  29128. var _this = this;
  29129. this.cameras.forEach(function (o) {
  29130. _this.scene.removeCamera(o);
  29131. });
  29132. this.lights.forEach(function (o) {
  29133. _this.scene.removeLight(o);
  29134. });
  29135. this.meshes.forEach(function (o) {
  29136. _this.scene.removeMesh(o);
  29137. });
  29138. this.skeletons.forEach(function (o) {
  29139. _this.scene.removeSkeleton(o);
  29140. });
  29141. this.animations.forEach(function (o) {
  29142. _this.scene.removeAnimation(o);
  29143. });
  29144. this.animationGroups.forEach(function (o) {
  29145. _this.scene.removeAnimationGroup(o);
  29146. });
  29147. this.multiMaterials.forEach(function (o) {
  29148. _this.scene.removeMultiMaterial(o);
  29149. });
  29150. this.materials.forEach(function (o) {
  29151. _this.scene.removeMaterial(o);
  29152. });
  29153. this.morphTargetManagers.forEach(function (o) {
  29154. _this.scene.removeMorphTargetManager(o);
  29155. });
  29156. this.geometries.forEach(function (o) {
  29157. _this.scene.removeGeometry(o);
  29158. });
  29159. this.transformNodes.forEach(function (o) {
  29160. _this.scene.removeTransformNode(o);
  29161. });
  29162. this.actionManagers.forEach(function (o) {
  29163. _this.scene.removeActionManager(o);
  29164. });
  29165. this.textures.forEach(function (o) {
  29166. _this.scene.removeTexture(o);
  29167. });
  29168. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29169. var component = _a[_i];
  29170. component.removeFromContainer(this.scene);
  29171. }
  29172. };
  29173. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29174. if (!sourceAssets) {
  29175. return;
  29176. }
  29177. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29178. var asset = sourceAssets_1[_i];
  29179. var move = true;
  29180. if (keepAssets) {
  29181. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29182. var keepAsset = keepAssets_1[_a];
  29183. if (asset === keepAsset) {
  29184. move = false;
  29185. break;
  29186. }
  29187. }
  29188. }
  29189. if (move) {
  29190. targetAssets.push(asset);
  29191. }
  29192. }
  29193. };
  29194. /**
  29195. * Removes all the assets contained in the scene and adds them to the container.
  29196. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29197. */
  29198. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29199. if (keepAssets === undefined) {
  29200. keepAssets = new KeepAssets();
  29201. }
  29202. for (var key in this) {
  29203. if (this.hasOwnProperty(key)) {
  29204. this[key] = this[key] || [];
  29205. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29206. }
  29207. }
  29208. this.removeAllFromScene();
  29209. };
  29210. /**
  29211. * 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.
  29212. * @returns the root mesh
  29213. */
  29214. AssetContainer.prototype.createRootMesh = function () {
  29215. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29216. this.meshes.forEach(function (m) {
  29217. if (!m.parent) {
  29218. rootMesh.addChild(m);
  29219. }
  29220. });
  29221. this.meshes.unshift(rootMesh);
  29222. return rootMesh;
  29223. };
  29224. return AssetContainer;
  29225. }(BABYLON.AbstractScene));
  29226. BABYLON.AssetContainer = AssetContainer;
  29227. })(BABYLON || (BABYLON = {}));
  29228. //# sourceMappingURL=babylon.assetContainer.js.map
  29229. var BABYLON;
  29230. (function (BABYLON) {
  29231. var Buffer = /** @class */ (function () {
  29232. /**
  29233. * Constructor
  29234. * @param engine the engine
  29235. * @param data the data to use for this buffer
  29236. * @param updatable whether the data is updatable
  29237. * @param stride the stride (optional)
  29238. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29239. * @param instanced whether the buffer is instanced (optional)
  29240. * @param useBytes set to true if the stride in in bytes (optional)
  29241. */
  29242. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29243. if (stride === void 0) { stride = 0; }
  29244. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29245. if (instanced === void 0) { instanced = false; }
  29246. if (useBytes === void 0) { useBytes = false; }
  29247. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29248. this._engine = engine.getScene().getEngine();
  29249. }
  29250. else {
  29251. this._engine = engine;
  29252. }
  29253. this._updatable = updatable;
  29254. this._instanced = instanced;
  29255. this._data = data;
  29256. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29257. if (!postponeInternalCreation) { // by default
  29258. this.create();
  29259. }
  29260. }
  29261. /**
  29262. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29263. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29264. * @param offset defines offset in the buffer (0 by default)
  29265. * @param size defines the size in floats of attributes (position is 3 for instance)
  29266. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29267. * @param instanced defines if the vertex buffer contains indexed data
  29268. * @param useBytes defines if the offset and stride are in bytes
  29269. * @returns the new vertex buffer
  29270. */
  29271. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29272. if (useBytes === void 0) { useBytes = false; }
  29273. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29274. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29275. // a lot of these parameters are ignored as they are overriden by the buffer
  29276. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29277. };
  29278. // Properties
  29279. Buffer.prototype.isUpdatable = function () {
  29280. return this._updatable;
  29281. };
  29282. Buffer.prototype.getData = function () {
  29283. return this._data;
  29284. };
  29285. Buffer.prototype.getBuffer = function () {
  29286. return this._buffer;
  29287. };
  29288. /**
  29289. * Gets the stride in float32 units (i.e. byte stride / 4).
  29290. * May not be an integer if the byte stride is not divisible by 4.
  29291. * DEPRECATED. Use byteStride instead.
  29292. * @returns the stride in float32 units
  29293. */
  29294. Buffer.prototype.getStrideSize = function () {
  29295. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29296. };
  29297. // Methods
  29298. Buffer.prototype.create = function (data) {
  29299. if (data === void 0) { data = null; }
  29300. if (!data && this._buffer) {
  29301. return; // nothing to do
  29302. }
  29303. data = data || this._data;
  29304. if (!data) {
  29305. return;
  29306. }
  29307. if (!this._buffer) { // create buffer
  29308. if (this._updatable) {
  29309. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29310. this._data = data;
  29311. }
  29312. else {
  29313. this._buffer = this._engine.createVertexBuffer(data);
  29314. }
  29315. }
  29316. else if (this._updatable) { // update buffer
  29317. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29318. this._data = data;
  29319. }
  29320. };
  29321. /** @hidden */
  29322. Buffer.prototype._rebuild = function () {
  29323. this._buffer = null;
  29324. this.create(this._data);
  29325. };
  29326. Buffer.prototype.update = function (data) {
  29327. this.create(data);
  29328. };
  29329. /**
  29330. * Updates the data directly.
  29331. * @param data the new data
  29332. * @param offset the new offset
  29333. * @param vertexCount the vertex count (optional)
  29334. * @param useBytes set to true if the offset is in bytes
  29335. */
  29336. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29337. if (useBytes === void 0) { useBytes = false; }
  29338. if (!this._buffer) {
  29339. return;
  29340. }
  29341. if (this._updatable) { // update buffer
  29342. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29343. this._data = null;
  29344. }
  29345. };
  29346. Buffer.prototype.dispose = function () {
  29347. if (!this._buffer) {
  29348. return;
  29349. }
  29350. if (this._engine._releaseBuffer(this._buffer)) {
  29351. this._buffer = null;
  29352. }
  29353. };
  29354. return Buffer;
  29355. }());
  29356. BABYLON.Buffer = Buffer;
  29357. })(BABYLON || (BABYLON = {}));
  29358. //# sourceMappingURL=babylon.buffer.js.map
  29359. var BABYLON;
  29360. (function (BABYLON) {
  29361. var VertexBuffer = /** @class */ (function () {
  29362. /**
  29363. * Constructor
  29364. * @param engine the engine
  29365. * @param data the data to use for this vertex buffer
  29366. * @param kind the vertex buffer kind
  29367. * @param updatable whether the data is updatable
  29368. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29369. * @param stride the stride (optional)
  29370. * @param instanced whether the buffer is instanced (optional)
  29371. * @param offset the offset of the data (optional)
  29372. * @param size the number of components (optional)
  29373. * @param type the type of the component (optional)
  29374. * @param normalized whether the data contains normalized data (optional)
  29375. * @param useBytes set to true if stride and offset are in bytes (optional)
  29376. */
  29377. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29378. if (normalized === void 0) { normalized = false; }
  29379. if (useBytes === void 0) { useBytes = false; }
  29380. if (data instanceof BABYLON.Buffer) {
  29381. this._buffer = data;
  29382. this._ownsBuffer = false;
  29383. }
  29384. else {
  29385. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29386. this._ownsBuffer = true;
  29387. }
  29388. this._kind = kind;
  29389. if (type == undefined) {
  29390. var data_1 = this.getData();
  29391. this.type = VertexBuffer.FLOAT;
  29392. if (data_1 instanceof Int8Array)
  29393. this.type = VertexBuffer.BYTE;
  29394. else if (data_1 instanceof Uint8Array)
  29395. this.type = VertexBuffer.UNSIGNED_BYTE;
  29396. else if (data_1 instanceof Int16Array)
  29397. this.type = VertexBuffer.SHORT;
  29398. else if (data_1 instanceof Uint16Array)
  29399. this.type = VertexBuffer.UNSIGNED_SHORT;
  29400. else if (data_1 instanceof Int32Array)
  29401. this.type = VertexBuffer.INT;
  29402. else if (data_1 instanceof Uint32Array)
  29403. this.type = VertexBuffer.UNSIGNED_INT;
  29404. }
  29405. else {
  29406. this.type = type;
  29407. }
  29408. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29409. if (useBytes) {
  29410. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29411. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29412. this.byteOffset = offset || 0;
  29413. }
  29414. else {
  29415. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29416. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29417. this.byteOffset = (offset || 0) * typeByteLength;
  29418. }
  29419. this.normalized = normalized;
  29420. this._instanced = instanced !== undefined ? instanced : false;
  29421. this._instanceDivisor = instanced ? 1 : 0;
  29422. }
  29423. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29424. /**
  29425. * Gets or sets the instance divisor when in instanced mode
  29426. */
  29427. get: function () {
  29428. return this._instanceDivisor;
  29429. },
  29430. set: function (value) {
  29431. this._instanceDivisor = value;
  29432. if (value == 0) {
  29433. this._instanced = false;
  29434. }
  29435. else {
  29436. this._instanced = true;
  29437. }
  29438. },
  29439. enumerable: true,
  29440. configurable: true
  29441. });
  29442. /** @hidden */
  29443. VertexBuffer.prototype._rebuild = function () {
  29444. if (!this._buffer) {
  29445. return;
  29446. }
  29447. this._buffer._rebuild();
  29448. };
  29449. /**
  29450. * Returns the kind of the VertexBuffer (string).
  29451. */
  29452. VertexBuffer.prototype.getKind = function () {
  29453. return this._kind;
  29454. };
  29455. // Properties
  29456. /**
  29457. * Boolean : is the VertexBuffer updatable ?
  29458. */
  29459. VertexBuffer.prototype.isUpdatable = function () {
  29460. return this._buffer.isUpdatable();
  29461. };
  29462. /**
  29463. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29464. */
  29465. VertexBuffer.prototype.getData = function () {
  29466. return this._buffer.getData();
  29467. };
  29468. /**
  29469. * Returns the WebGLBuffer associated to the VertexBuffer.
  29470. */
  29471. VertexBuffer.prototype.getBuffer = function () {
  29472. return this._buffer.getBuffer();
  29473. };
  29474. /**
  29475. * Returns the stride as a multiple of the type byte length.
  29476. * DEPRECATED. Use byteStride instead.
  29477. */
  29478. VertexBuffer.prototype.getStrideSize = function () {
  29479. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29480. };
  29481. /**
  29482. * Returns the offset as a multiple of the type byte length.
  29483. * DEPRECATED. Use byteOffset instead.
  29484. */
  29485. VertexBuffer.prototype.getOffset = function () {
  29486. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29487. };
  29488. /**
  29489. * Returns the number of components per vertex attribute (integer).
  29490. */
  29491. VertexBuffer.prototype.getSize = function () {
  29492. return this._size;
  29493. };
  29494. /**
  29495. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29496. */
  29497. VertexBuffer.prototype.getIsInstanced = function () {
  29498. return this._instanced;
  29499. };
  29500. /**
  29501. * Returns the instancing divisor, zero for non-instanced (integer).
  29502. */
  29503. VertexBuffer.prototype.getInstanceDivisor = function () {
  29504. return this._instanceDivisor;
  29505. };
  29506. // Methods
  29507. /**
  29508. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29509. * Returns the created WebGLBuffer.
  29510. */
  29511. VertexBuffer.prototype.create = function (data) {
  29512. return this._buffer.create(data);
  29513. };
  29514. /**
  29515. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29516. * This function will create a new buffer if the current one is not updatable
  29517. * Returns the updated WebGLBuffer.
  29518. */
  29519. VertexBuffer.prototype.update = function (data) {
  29520. return this._buffer.update(data);
  29521. };
  29522. /**
  29523. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29524. * Returns the directly updated WebGLBuffer.
  29525. * @param data the new data
  29526. * @param offset the new offset
  29527. * @param useBytes set to true if the offset is in bytes
  29528. */
  29529. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29530. if (useBytes === void 0) { useBytes = false; }
  29531. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29532. };
  29533. /**
  29534. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29535. */
  29536. VertexBuffer.prototype.dispose = function () {
  29537. if (this._ownsBuffer) {
  29538. this._buffer.dispose();
  29539. }
  29540. };
  29541. /**
  29542. * Enumerates each value of this vertex buffer as numbers.
  29543. * @param count the number of values to enumerate
  29544. * @param callback the callback function called for each value
  29545. */
  29546. VertexBuffer.prototype.forEach = function (count, callback) {
  29547. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29548. };
  29549. Object.defineProperty(VertexBuffer, "PositionKind", {
  29550. get: function () {
  29551. return VertexBuffer._PositionKind;
  29552. },
  29553. enumerable: true,
  29554. configurable: true
  29555. });
  29556. Object.defineProperty(VertexBuffer, "NormalKind", {
  29557. get: function () {
  29558. return VertexBuffer._NormalKind;
  29559. },
  29560. enumerable: true,
  29561. configurable: true
  29562. });
  29563. Object.defineProperty(VertexBuffer, "TangentKind", {
  29564. get: function () {
  29565. return VertexBuffer._TangentKind;
  29566. },
  29567. enumerable: true,
  29568. configurable: true
  29569. });
  29570. Object.defineProperty(VertexBuffer, "UVKind", {
  29571. get: function () {
  29572. return VertexBuffer._UVKind;
  29573. },
  29574. enumerable: true,
  29575. configurable: true
  29576. });
  29577. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29578. get: function () {
  29579. return VertexBuffer._UV2Kind;
  29580. },
  29581. enumerable: true,
  29582. configurable: true
  29583. });
  29584. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29585. get: function () {
  29586. return VertexBuffer._UV3Kind;
  29587. },
  29588. enumerable: true,
  29589. configurable: true
  29590. });
  29591. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29592. get: function () {
  29593. return VertexBuffer._UV4Kind;
  29594. },
  29595. enumerable: true,
  29596. configurable: true
  29597. });
  29598. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29599. get: function () {
  29600. return VertexBuffer._UV5Kind;
  29601. },
  29602. enumerable: true,
  29603. configurable: true
  29604. });
  29605. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29606. get: function () {
  29607. return VertexBuffer._UV6Kind;
  29608. },
  29609. enumerable: true,
  29610. configurable: true
  29611. });
  29612. Object.defineProperty(VertexBuffer, "ColorKind", {
  29613. get: function () {
  29614. return VertexBuffer._ColorKind;
  29615. },
  29616. enumerable: true,
  29617. configurable: true
  29618. });
  29619. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29620. get: function () {
  29621. return VertexBuffer._MatricesIndicesKind;
  29622. },
  29623. enumerable: true,
  29624. configurable: true
  29625. });
  29626. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29627. get: function () {
  29628. return VertexBuffer._MatricesWeightsKind;
  29629. },
  29630. enumerable: true,
  29631. configurable: true
  29632. });
  29633. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29634. get: function () {
  29635. return VertexBuffer._MatricesIndicesExtraKind;
  29636. },
  29637. enumerable: true,
  29638. configurable: true
  29639. });
  29640. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29641. get: function () {
  29642. return VertexBuffer._MatricesWeightsExtraKind;
  29643. },
  29644. enumerable: true,
  29645. configurable: true
  29646. });
  29647. /**
  29648. * Deduces the stride given a kind.
  29649. * @param kind The kind string to deduce
  29650. * @returns The deduced stride
  29651. */
  29652. VertexBuffer.DeduceStride = function (kind) {
  29653. switch (kind) {
  29654. case VertexBuffer.UVKind:
  29655. case VertexBuffer.UV2Kind:
  29656. case VertexBuffer.UV3Kind:
  29657. case VertexBuffer.UV4Kind:
  29658. case VertexBuffer.UV5Kind:
  29659. case VertexBuffer.UV6Kind:
  29660. return 2;
  29661. case VertexBuffer.NormalKind:
  29662. case VertexBuffer.PositionKind:
  29663. return 3;
  29664. case VertexBuffer.ColorKind:
  29665. case VertexBuffer.MatricesIndicesKind:
  29666. case VertexBuffer.MatricesIndicesExtraKind:
  29667. case VertexBuffer.MatricesWeightsKind:
  29668. case VertexBuffer.MatricesWeightsExtraKind:
  29669. case VertexBuffer.TangentKind:
  29670. return 4;
  29671. default:
  29672. throw new Error("Invalid kind '" + kind + "'");
  29673. }
  29674. };
  29675. /**
  29676. * Gets the byte length of the given type.
  29677. * @param type the type
  29678. * @returns the number of bytes
  29679. */
  29680. VertexBuffer.GetTypeByteLength = function (type) {
  29681. switch (type) {
  29682. case VertexBuffer.BYTE:
  29683. case VertexBuffer.UNSIGNED_BYTE:
  29684. return 1;
  29685. case VertexBuffer.SHORT:
  29686. case VertexBuffer.UNSIGNED_SHORT:
  29687. return 2;
  29688. case VertexBuffer.INT:
  29689. case VertexBuffer.FLOAT:
  29690. return 4;
  29691. default:
  29692. throw new Error("Invalid type '" + type + "'");
  29693. }
  29694. };
  29695. /**
  29696. * Enumerates each value of the given parameters as numbers.
  29697. * @param data the data to enumerate
  29698. * @param byteOffset the byte offset of the data
  29699. * @param byteStride the byte stride of the data
  29700. * @param componentCount the number of components per element
  29701. * @param componentType the type of the component
  29702. * @param count the total number of components
  29703. * @param normalized whether the data is normalized
  29704. * @param callback the callback function called for each value
  29705. */
  29706. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29707. if (data instanceof Array) {
  29708. var offset = byteOffset / 4;
  29709. var stride = byteStride / 4;
  29710. for (var index = 0; index < count; index += componentCount) {
  29711. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29712. callback(data[offset + componentIndex], index + componentIndex);
  29713. }
  29714. offset += stride;
  29715. }
  29716. }
  29717. else {
  29718. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29719. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29720. for (var index = 0; index < count; index += componentCount) {
  29721. var componentByteOffset = byteOffset;
  29722. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29723. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29724. callback(value, index + componentIndex);
  29725. componentByteOffset += componentByteLength;
  29726. }
  29727. byteOffset += byteStride;
  29728. }
  29729. }
  29730. };
  29731. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29732. switch (type) {
  29733. case VertexBuffer.BYTE: {
  29734. var value = dataView.getInt8(byteOffset);
  29735. if (normalized) {
  29736. value = Math.max(value / 127, -1);
  29737. }
  29738. return value;
  29739. }
  29740. case VertexBuffer.UNSIGNED_BYTE: {
  29741. var value = dataView.getUint8(byteOffset);
  29742. if (normalized) {
  29743. value = value / 255;
  29744. }
  29745. return value;
  29746. }
  29747. case VertexBuffer.SHORT: {
  29748. var value = dataView.getInt16(byteOffset, true);
  29749. if (normalized) {
  29750. value = Math.max(value / 16383, -1);
  29751. }
  29752. return value;
  29753. }
  29754. case VertexBuffer.UNSIGNED_SHORT: {
  29755. var value = dataView.getUint16(byteOffset, true);
  29756. if (normalized) {
  29757. value = value / 65535;
  29758. }
  29759. return value;
  29760. }
  29761. case VertexBuffer.FLOAT: {
  29762. return dataView.getFloat32(byteOffset, true);
  29763. }
  29764. default: {
  29765. throw new Error("Invalid component type " + type);
  29766. }
  29767. }
  29768. };
  29769. /**
  29770. * The byte type.
  29771. */
  29772. VertexBuffer.BYTE = 5120;
  29773. /**
  29774. * The unsigned byte type.
  29775. */
  29776. VertexBuffer.UNSIGNED_BYTE = 5121;
  29777. /**
  29778. * The short type.
  29779. */
  29780. VertexBuffer.SHORT = 5122;
  29781. /**
  29782. * The unsigned short type.
  29783. */
  29784. VertexBuffer.UNSIGNED_SHORT = 5123;
  29785. /**
  29786. * The integer type.
  29787. */
  29788. VertexBuffer.INT = 5124;
  29789. /**
  29790. * The unsigned integer type.
  29791. */
  29792. VertexBuffer.UNSIGNED_INT = 5125;
  29793. /**
  29794. * The float type.
  29795. */
  29796. VertexBuffer.FLOAT = 5126;
  29797. // Enums
  29798. VertexBuffer._PositionKind = "position";
  29799. VertexBuffer._NormalKind = "normal";
  29800. VertexBuffer._TangentKind = "tangent";
  29801. VertexBuffer._UVKind = "uv";
  29802. VertexBuffer._UV2Kind = "uv2";
  29803. VertexBuffer._UV3Kind = "uv3";
  29804. VertexBuffer._UV4Kind = "uv4";
  29805. VertexBuffer._UV5Kind = "uv5";
  29806. VertexBuffer._UV6Kind = "uv6";
  29807. VertexBuffer._ColorKind = "color";
  29808. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29809. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29810. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29811. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29812. return VertexBuffer;
  29813. }());
  29814. BABYLON.VertexBuffer = VertexBuffer;
  29815. })(BABYLON || (BABYLON = {}));
  29816. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29817. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29818. var BABYLON;
  29819. (function (BABYLON) {
  29820. /**
  29821. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29822. */
  29823. var DummyInternalTextureTracker = /** @class */ (function () {
  29824. function DummyInternalTextureTracker() {
  29825. /**
  29826. * Gets or set the previous tracker in the list
  29827. */
  29828. this.previous = null;
  29829. /**
  29830. * Gets or set the next tracker in the list
  29831. */
  29832. this.next = null;
  29833. }
  29834. return DummyInternalTextureTracker;
  29835. }());
  29836. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29837. })(BABYLON || (BABYLON = {}));
  29838. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29839. var BABYLON;
  29840. (function (BABYLON) {
  29841. /**
  29842. * Class used to store data associated with WebGL texture data for the engine
  29843. * This class should not be used directly
  29844. */
  29845. var InternalTexture = /** @class */ (function () {
  29846. /**
  29847. * Creates a new InternalTexture
  29848. * @param engine defines the engine to use
  29849. * @param dataSource defines the type of data that will be used
  29850. */
  29851. function InternalTexture(engine, dataSource) {
  29852. /**
  29853. * Observable called when the texture is loaded
  29854. */
  29855. this.onLoadedObservable = new BABYLON.Observable();
  29856. /**
  29857. * Gets or set the previous tracker in the list
  29858. */
  29859. this.previous = null;
  29860. /**
  29861. * Gets or set the next tracker in the list
  29862. */
  29863. this.next = null;
  29864. // Private
  29865. /** @hidden */
  29866. this._initialSlot = -1;
  29867. /** @hidden */
  29868. this._designatedSlot = -1;
  29869. /** @hidden */
  29870. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29871. /** @hidden */
  29872. this._comparisonFunction = 0;
  29873. /** @hidden */
  29874. this._sphericalPolynomial = null;
  29875. /** @hidden */
  29876. this._lodGenerationScale = 0;
  29877. /** @hidden */
  29878. this._lodGenerationOffset = 0;
  29879. /** @hidden */
  29880. this._isRGBD = false;
  29881. /** @hidden */
  29882. this._references = 1;
  29883. this._engine = engine;
  29884. this._dataSource = dataSource;
  29885. this._webGLTexture = engine._createTexture();
  29886. }
  29887. /**
  29888. * Gets the Engine the texture belongs to.
  29889. * @returns The babylon engine
  29890. */
  29891. InternalTexture.prototype.getEngine = function () {
  29892. return this._engine;
  29893. };
  29894. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29895. /**
  29896. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29897. */
  29898. get: function () {
  29899. return this._dataSource;
  29900. },
  29901. enumerable: true,
  29902. configurable: true
  29903. });
  29904. /**
  29905. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29906. */
  29907. InternalTexture.prototype.incrementReferences = function () {
  29908. this._references++;
  29909. };
  29910. /**
  29911. * Change the size of the texture (not the size of the content)
  29912. * @param width defines the new width
  29913. * @param height defines the new height
  29914. * @param depth defines the new depth (1 by default)
  29915. */
  29916. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29917. if (depth === void 0) { depth = 1; }
  29918. this.width = width;
  29919. this.height = height;
  29920. this.depth = depth;
  29921. this.baseWidth = width;
  29922. this.baseHeight = height;
  29923. this.baseDepth = depth;
  29924. this._size = width * height * depth;
  29925. };
  29926. /** @hidden */
  29927. InternalTexture.prototype._rebuild = function () {
  29928. var _this = this;
  29929. var proxy;
  29930. this.isReady = false;
  29931. this._cachedCoordinatesMode = null;
  29932. this._cachedWrapU = null;
  29933. this._cachedWrapV = null;
  29934. this._cachedAnisotropicFilteringLevel = null;
  29935. switch (this._dataSource) {
  29936. case InternalTexture.DATASOURCE_TEMP:
  29937. return;
  29938. case InternalTexture.DATASOURCE_URL:
  29939. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29940. _this.isReady = true;
  29941. }, null, this._buffer, undefined, this.format);
  29942. proxy._swapAndDie(this);
  29943. return;
  29944. case InternalTexture.DATASOURCE_RAW:
  29945. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29946. proxy._swapAndDie(this);
  29947. this.isReady = true;
  29948. return;
  29949. case InternalTexture.DATASOURCE_RAW3D:
  29950. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29951. proxy._swapAndDie(this);
  29952. this.isReady = true;
  29953. return;
  29954. case InternalTexture.DATASOURCE_DYNAMIC:
  29955. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29956. proxy._swapAndDie(this);
  29957. // The engine will make sure to update content so no need to flag it as isReady = true
  29958. return;
  29959. case InternalTexture.DATASOURCE_RENDERTARGET:
  29960. var options = new BABYLON.RenderTargetCreationOptions();
  29961. options.generateDepthBuffer = this._generateDepthBuffer;
  29962. options.generateMipMaps = this.generateMipMaps;
  29963. options.generateStencilBuffer = this._generateStencilBuffer;
  29964. options.samplingMode = this.samplingMode;
  29965. options.type = this.type;
  29966. if (this.isCube) {
  29967. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29968. }
  29969. else {
  29970. var size = {
  29971. width: this.width,
  29972. height: this.height
  29973. };
  29974. proxy = this._engine.createRenderTargetTexture(size, options);
  29975. }
  29976. proxy._swapAndDie(this);
  29977. this.isReady = true;
  29978. return;
  29979. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29980. var depthTextureOptions = {
  29981. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29982. comparisonFunction: this._comparisonFunction,
  29983. generateStencil: this._generateStencilBuffer,
  29984. isCube: this.isCube
  29985. };
  29986. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29987. proxy._swapAndDie(this);
  29988. this.isReady = true;
  29989. return;
  29990. case InternalTexture.DATASOURCE_CUBE:
  29991. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29992. _this.isReady = true;
  29993. }, null, this.format, this._extension);
  29994. proxy._swapAndDie(this);
  29995. return;
  29996. case InternalTexture.DATASOURCE_CUBERAW:
  29997. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29998. proxy._swapAndDie(this);
  29999. this.isReady = true;
  30000. return;
  30001. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30002. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30003. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30004. _this.isReady = true;
  30005. });
  30006. proxy._swapAndDie(this);
  30007. return;
  30008. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30009. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30010. if (proxy) {
  30011. proxy._swapAndDie(_this);
  30012. }
  30013. _this.isReady = true;
  30014. }, null, this.format, this._extension);
  30015. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30016. return;
  30017. }
  30018. };
  30019. /** @hidden */
  30020. InternalTexture.prototype._swapAndDie = function (target) {
  30021. target._webGLTexture = this._webGLTexture;
  30022. if (this._framebuffer) {
  30023. target._framebuffer = this._framebuffer;
  30024. }
  30025. if (this._depthStencilBuffer) {
  30026. target._depthStencilBuffer = this._depthStencilBuffer;
  30027. }
  30028. if (this._lodTextureHigh) {
  30029. if (target._lodTextureHigh) {
  30030. target._lodTextureHigh.dispose();
  30031. }
  30032. target._lodTextureHigh = this._lodTextureHigh;
  30033. }
  30034. if (this._lodTextureMid) {
  30035. if (target._lodTextureMid) {
  30036. target._lodTextureMid.dispose();
  30037. }
  30038. target._lodTextureMid = this._lodTextureMid;
  30039. }
  30040. if (this._lodTextureLow) {
  30041. if (target._lodTextureLow) {
  30042. target._lodTextureLow.dispose();
  30043. }
  30044. target._lodTextureLow = this._lodTextureLow;
  30045. }
  30046. var cache = this._engine.getLoadedTexturesCache();
  30047. var index = cache.indexOf(this);
  30048. if (index !== -1) {
  30049. cache.splice(index, 1);
  30050. }
  30051. };
  30052. /**
  30053. * Dispose the current allocated resources
  30054. */
  30055. InternalTexture.prototype.dispose = function () {
  30056. if (!this._webGLTexture) {
  30057. return;
  30058. }
  30059. this._references--;
  30060. if (this._references === 0) {
  30061. this._engine._releaseTexture(this);
  30062. this._webGLTexture = null;
  30063. this.previous = null;
  30064. this.next = null;
  30065. }
  30066. };
  30067. /**
  30068. * The source of the texture data is unknown
  30069. */
  30070. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30071. /**
  30072. * Texture data comes from an URL
  30073. */
  30074. InternalTexture.DATASOURCE_URL = 1;
  30075. /**
  30076. * Texture data is only used for temporary storage
  30077. */
  30078. InternalTexture.DATASOURCE_TEMP = 2;
  30079. /**
  30080. * Texture data comes from raw data (ArrayBuffer)
  30081. */
  30082. InternalTexture.DATASOURCE_RAW = 3;
  30083. /**
  30084. * Texture content is dynamic (video or dynamic texture)
  30085. */
  30086. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30087. /**
  30088. * Texture content is generated by rendering to it
  30089. */
  30090. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30091. /**
  30092. * Texture content is part of a multi render target process
  30093. */
  30094. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30095. /**
  30096. * Texture data comes from a cube data file
  30097. */
  30098. InternalTexture.DATASOURCE_CUBE = 7;
  30099. /**
  30100. * Texture data comes from a raw cube data
  30101. */
  30102. InternalTexture.DATASOURCE_CUBERAW = 8;
  30103. /**
  30104. * Texture data come from a prefiltered cube data file
  30105. */
  30106. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30107. /**
  30108. * Texture content is raw 3D data
  30109. */
  30110. InternalTexture.DATASOURCE_RAW3D = 10;
  30111. /**
  30112. * Texture content is a depth texture
  30113. */
  30114. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30115. /**
  30116. * Texture data comes from a raw cube data encoded with RGBD
  30117. */
  30118. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30119. return InternalTexture;
  30120. }());
  30121. BABYLON.InternalTexture = InternalTexture;
  30122. })(BABYLON || (BABYLON = {}));
  30123. //# sourceMappingURL=babylon.internalTexture.js.map
  30124. var BABYLON;
  30125. (function (BABYLON) {
  30126. var BaseTexture = /** @class */ (function () {
  30127. function BaseTexture(scene) {
  30128. this._hasAlpha = false;
  30129. this.getAlphaFromRGB = false;
  30130. this.level = 1;
  30131. this.coordinatesIndex = 0;
  30132. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30133. /**
  30134. * | Value | Type | Description |
  30135. * | ----- | ------------------ | ----------- |
  30136. * | 0 | CLAMP_ADDRESSMODE | |
  30137. * | 1 | WRAP_ADDRESSMODE | |
  30138. * | 2 | MIRROR_ADDRESSMODE | |
  30139. */
  30140. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30141. /**
  30142. * | Value | Type | Description |
  30143. * | ----- | ------------------ | ----------- |
  30144. * | 0 | CLAMP_ADDRESSMODE | |
  30145. * | 1 | WRAP_ADDRESSMODE | |
  30146. * | 2 | MIRROR_ADDRESSMODE | |
  30147. */
  30148. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30149. /**
  30150. * | Value | Type | Description |
  30151. * | ----- | ------------------ | ----------- |
  30152. * | 0 | CLAMP_ADDRESSMODE | |
  30153. * | 1 | WRAP_ADDRESSMODE | |
  30154. * | 2 | MIRROR_ADDRESSMODE | |
  30155. */
  30156. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30157. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30158. this.isCube = false;
  30159. this.is3D = false;
  30160. this.gammaSpace = true;
  30161. this.invertZ = false;
  30162. this.lodLevelInAlpha = false;
  30163. this.isRenderTarget = false;
  30164. this.animations = new Array();
  30165. /**
  30166. * An event triggered when the texture is disposed.
  30167. */
  30168. this.onDisposeObservable = new BABYLON.Observable();
  30169. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30170. this._cachedSize = BABYLON.Size.Zero();
  30171. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30172. if (this._scene) {
  30173. this._scene.textures.push(this);
  30174. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  30175. }
  30176. this._uid = null;
  30177. }
  30178. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30179. get: function () {
  30180. return this._hasAlpha;
  30181. },
  30182. set: function (value) {
  30183. if (this._hasAlpha === value) {
  30184. return;
  30185. }
  30186. this._hasAlpha = value;
  30187. if (this._scene) {
  30188. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30189. }
  30190. },
  30191. enumerable: true,
  30192. configurable: true
  30193. });
  30194. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30195. get: function () {
  30196. return this._coordinatesMode;
  30197. },
  30198. /**
  30199. * How a texture is mapped.
  30200. *
  30201. * | Value | Type | Description |
  30202. * | ----- | ----------------------------------- | ----------- |
  30203. * | 0 | EXPLICIT_MODE | |
  30204. * | 1 | SPHERICAL_MODE | |
  30205. * | 2 | PLANAR_MODE | |
  30206. * | 3 | CUBIC_MODE | |
  30207. * | 4 | PROJECTION_MODE | |
  30208. * | 5 | SKYBOX_MODE | |
  30209. * | 6 | INVCUBIC_MODE | |
  30210. * | 7 | EQUIRECTANGULAR_MODE | |
  30211. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30212. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30213. */
  30214. set: function (value) {
  30215. if (this._coordinatesMode === value) {
  30216. return;
  30217. }
  30218. this._coordinatesMode = value;
  30219. if (this._scene) {
  30220. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30221. }
  30222. },
  30223. enumerable: true,
  30224. configurable: true
  30225. });
  30226. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30227. /**
  30228. * Gets whether or not the texture contains RGBD data.
  30229. */
  30230. get: function () {
  30231. return this._texture != null && this._texture._isRGBD;
  30232. },
  30233. enumerable: true,
  30234. configurable: true
  30235. });
  30236. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30237. get: function () {
  30238. if (this._texture)
  30239. return this._texture._lodGenerationOffset;
  30240. return 0.0;
  30241. },
  30242. set: function (value) {
  30243. if (this._texture)
  30244. this._texture._lodGenerationOffset = value;
  30245. },
  30246. enumerable: true,
  30247. configurable: true
  30248. });
  30249. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30250. get: function () {
  30251. if (this._texture)
  30252. return this._texture._lodGenerationScale;
  30253. return 0.0;
  30254. },
  30255. set: function (value) {
  30256. if (this._texture)
  30257. this._texture._lodGenerationScale = value;
  30258. },
  30259. enumerable: true,
  30260. configurable: true
  30261. });
  30262. Object.defineProperty(BaseTexture.prototype, "uid", {
  30263. get: function () {
  30264. if (!this._uid) {
  30265. this._uid = BABYLON.Tools.RandomId();
  30266. }
  30267. return this._uid;
  30268. },
  30269. enumerable: true,
  30270. configurable: true
  30271. });
  30272. BaseTexture.prototype.toString = function () {
  30273. return this.name;
  30274. };
  30275. BaseTexture.prototype.getClassName = function () {
  30276. return "BaseTexture";
  30277. };
  30278. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30279. set: function (callback) {
  30280. if (this._onDisposeObserver) {
  30281. this.onDisposeObservable.remove(this._onDisposeObserver);
  30282. }
  30283. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30284. },
  30285. enumerable: true,
  30286. configurable: true
  30287. });
  30288. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30289. get: function () {
  30290. return true;
  30291. },
  30292. enumerable: true,
  30293. configurable: true
  30294. });
  30295. BaseTexture.prototype.getScene = function () {
  30296. return this._scene;
  30297. };
  30298. BaseTexture.prototype.getTextureMatrix = function () {
  30299. return BABYLON.Matrix.IdentityReadOnly;
  30300. };
  30301. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30302. return BABYLON.Matrix.IdentityReadOnly;
  30303. };
  30304. BaseTexture.prototype.getInternalTexture = function () {
  30305. return this._texture;
  30306. };
  30307. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30308. return !this.isBlocking || this.isReady();
  30309. };
  30310. BaseTexture.prototype.isReady = function () {
  30311. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30312. this.delayLoad();
  30313. return false;
  30314. }
  30315. if (this._texture) {
  30316. return this._texture.isReady;
  30317. }
  30318. return false;
  30319. };
  30320. BaseTexture.prototype.getSize = function () {
  30321. if (this._texture) {
  30322. if (this._texture.width) {
  30323. this._cachedSize.width = this._texture.width;
  30324. this._cachedSize.height = this._texture.height;
  30325. return this._cachedSize;
  30326. }
  30327. if (this._texture._size) {
  30328. this._cachedSize.width = this._texture._size;
  30329. this._cachedSize.height = this._texture._size;
  30330. return this._cachedSize;
  30331. }
  30332. }
  30333. return this._cachedSize;
  30334. };
  30335. BaseTexture.prototype.getBaseSize = function () {
  30336. if (!this.isReady() || !this._texture)
  30337. return BABYLON.Size.Zero();
  30338. if (this._texture._size) {
  30339. return new BABYLON.Size(this._texture._size, this._texture._size);
  30340. }
  30341. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30342. };
  30343. BaseTexture.prototype.scale = function (ratio) {
  30344. };
  30345. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30346. get: function () {
  30347. return false;
  30348. },
  30349. enumerable: true,
  30350. configurable: true
  30351. });
  30352. /** @hidden */
  30353. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30354. if (!this._scene) {
  30355. return null;
  30356. }
  30357. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30358. for (var index = 0; index < texturesCache.length; index++) {
  30359. var texturesCacheEntry = texturesCache[index];
  30360. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30361. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30362. texturesCacheEntry.incrementReferences();
  30363. return texturesCacheEntry;
  30364. }
  30365. }
  30366. }
  30367. return null;
  30368. };
  30369. /** @hidden */
  30370. BaseTexture.prototype._rebuild = function () {
  30371. };
  30372. BaseTexture.prototype.delayLoad = function () {
  30373. };
  30374. BaseTexture.prototype.clone = function () {
  30375. return null;
  30376. };
  30377. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30378. get: function () {
  30379. if (!this._texture) {
  30380. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30381. }
  30382. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30383. },
  30384. enumerable: true,
  30385. configurable: true
  30386. });
  30387. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30388. get: function () {
  30389. if (!this._texture) {
  30390. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30391. }
  30392. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30393. },
  30394. enumerable: true,
  30395. configurable: true
  30396. });
  30397. /**
  30398. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30399. * This will returns an RGBA array buffer containing either in values (0-255) or
  30400. * float values (0-1) depending of the underlying buffer type.
  30401. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  30402. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  30403. * @param buffer defines a user defined buffer to fill with data (can be null)
  30404. * @returns The Array buffer containing the pixels data.
  30405. */
  30406. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  30407. if (faceIndex === void 0) { faceIndex = 0; }
  30408. if (level === void 0) { level = 0; }
  30409. if (buffer === void 0) { buffer = null; }
  30410. if (!this._texture) {
  30411. return null;
  30412. }
  30413. var size = this.getSize();
  30414. var width = size.width;
  30415. var height = size.height;
  30416. var scene = this.getScene();
  30417. if (!scene) {
  30418. return null;
  30419. }
  30420. var engine = scene.getEngine();
  30421. if (level != 0) {
  30422. width = width / Math.pow(2, level);
  30423. height = height / Math.pow(2, level);
  30424. width = Math.round(width);
  30425. height = Math.round(height);
  30426. }
  30427. if (this._texture.isCube) {
  30428. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  30429. }
  30430. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  30431. };
  30432. BaseTexture.prototype.releaseInternalTexture = function () {
  30433. if (this._texture) {
  30434. this._texture.dispose();
  30435. this._texture = null;
  30436. }
  30437. };
  30438. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30439. get: function () {
  30440. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30441. return null;
  30442. }
  30443. if (!this._texture._sphericalPolynomial) {
  30444. this._texture._sphericalPolynomial =
  30445. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30446. }
  30447. return this._texture._sphericalPolynomial;
  30448. },
  30449. set: function (value) {
  30450. if (this._texture) {
  30451. this._texture._sphericalPolynomial = value;
  30452. }
  30453. },
  30454. enumerable: true,
  30455. configurable: true
  30456. });
  30457. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30458. get: function () {
  30459. if (this._texture) {
  30460. return this._texture._lodTextureHigh;
  30461. }
  30462. return null;
  30463. },
  30464. enumerable: true,
  30465. configurable: true
  30466. });
  30467. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30468. get: function () {
  30469. if (this._texture) {
  30470. return this._texture._lodTextureMid;
  30471. }
  30472. return null;
  30473. },
  30474. enumerable: true,
  30475. configurable: true
  30476. });
  30477. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30478. get: function () {
  30479. if (this._texture) {
  30480. return this._texture._lodTextureLow;
  30481. }
  30482. return null;
  30483. },
  30484. enumerable: true,
  30485. configurable: true
  30486. });
  30487. BaseTexture.prototype.dispose = function () {
  30488. if (!this._scene) {
  30489. return;
  30490. }
  30491. // Animations
  30492. this._scene.stopAnimation(this);
  30493. // Remove from scene
  30494. this._scene._removePendingData(this);
  30495. var index = this._scene.textures.indexOf(this);
  30496. if (index >= 0) {
  30497. this._scene.textures.splice(index, 1);
  30498. }
  30499. this._scene.onTextureRemovedObservable.notifyObservers(this);
  30500. if (this._texture === undefined) {
  30501. return;
  30502. }
  30503. // Release
  30504. this.releaseInternalTexture();
  30505. // Callback
  30506. this.onDisposeObservable.notifyObservers(this);
  30507. this.onDisposeObservable.clear();
  30508. };
  30509. BaseTexture.prototype.serialize = function () {
  30510. if (!this.name) {
  30511. return null;
  30512. }
  30513. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30514. // Animations
  30515. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30516. return serializationObject;
  30517. };
  30518. BaseTexture.WhenAllReady = function (textures, callback) {
  30519. var numRemaining = textures.length;
  30520. if (numRemaining === 0) {
  30521. callback();
  30522. return;
  30523. }
  30524. var _loop_1 = function () {
  30525. texture = textures[i];
  30526. if (texture.isReady()) {
  30527. if (--numRemaining === 0) {
  30528. callback();
  30529. }
  30530. }
  30531. else {
  30532. onLoadObservable = texture.onLoadObservable;
  30533. var onLoadCallback_1 = function () {
  30534. onLoadObservable.removeCallback(onLoadCallback_1);
  30535. if (--numRemaining === 0) {
  30536. callback();
  30537. }
  30538. };
  30539. onLoadObservable.add(onLoadCallback_1);
  30540. }
  30541. };
  30542. var texture, onLoadObservable;
  30543. for (var i = 0; i < textures.length; i++) {
  30544. _loop_1();
  30545. }
  30546. };
  30547. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30548. __decorate([
  30549. BABYLON.serialize()
  30550. ], BaseTexture.prototype, "name", void 0);
  30551. __decorate([
  30552. BABYLON.serialize("hasAlpha")
  30553. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30554. __decorate([
  30555. BABYLON.serialize()
  30556. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30557. __decorate([
  30558. BABYLON.serialize()
  30559. ], BaseTexture.prototype, "level", void 0);
  30560. __decorate([
  30561. BABYLON.serialize()
  30562. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30563. __decorate([
  30564. BABYLON.serialize("coordinatesMode")
  30565. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30566. __decorate([
  30567. BABYLON.serialize()
  30568. ], BaseTexture.prototype, "wrapU", void 0);
  30569. __decorate([
  30570. BABYLON.serialize()
  30571. ], BaseTexture.prototype, "wrapV", void 0);
  30572. __decorate([
  30573. BABYLON.serialize()
  30574. ], BaseTexture.prototype, "wrapR", void 0);
  30575. __decorate([
  30576. BABYLON.serialize()
  30577. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30578. __decorate([
  30579. BABYLON.serialize()
  30580. ], BaseTexture.prototype, "isCube", void 0);
  30581. __decorate([
  30582. BABYLON.serialize()
  30583. ], BaseTexture.prototype, "is3D", void 0);
  30584. __decorate([
  30585. BABYLON.serialize()
  30586. ], BaseTexture.prototype, "gammaSpace", void 0);
  30587. __decorate([
  30588. BABYLON.serialize()
  30589. ], BaseTexture.prototype, "invertZ", void 0);
  30590. __decorate([
  30591. BABYLON.serialize()
  30592. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30593. __decorate([
  30594. BABYLON.serialize()
  30595. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30596. __decorate([
  30597. BABYLON.serialize()
  30598. ], BaseTexture.prototype, "lodGenerationScale", null);
  30599. __decorate([
  30600. BABYLON.serialize()
  30601. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30602. return BaseTexture;
  30603. }());
  30604. BABYLON.BaseTexture = BaseTexture;
  30605. })(BABYLON || (BABYLON = {}));
  30606. //# sourceMappingURL=babylon.baseTexture.js.map
  30607. var BABYLON;
  30608. (function (BABYLON) {
  30609. var Texture = /** @class */ (function (_super) {
  30610. __extends(Texture, _super);
  30611. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30612. if (noMipmap === void 0) { noMipmap = false; }
  30613. if (invertY === void 0) { invertY = true; }
  30614. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30615. if (onLoad === void 0) { onLoad = null; }
  30616. if (onError === void 0) { onError = null; }
  30617. if (buffer === void 0) { buffer = null; }
  30618. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30619. var _this = _super.call(this, scene) || this;
  30620. _this.uOffset = 0;
  30621. _this.vOffset = 0;
  30622. _this.uScale = 1.0;
  30623. _this.vScale = 1.0;
  30624. _this.uAng = 0;
  30625. _this.vAng = 0;
  30626. _this.wAng = 0;
  30627. /**
  30628. * Defines the center of rotation (U)
  30629. */
  30630. _this.uRotationCenter = 0.5;
  30631. /**
  30632. * Defines the center of rotation (V)
  30633. */
  30634. _this.vRotationCenter = 0.5;
  30635. /**
  30636. * Defines the center of rotation (W)
  30637. */
  30638. _this.wRotationCenter = 0.5;
  30639. _this._isBlocking = true;
  30640. _this.name = url || "";
  30641. _this.url = url;
  30642. _this._noMipmap = noMipmap;
  30643. _this._invertY = invertY;
  30644. _this._samplingMode = samplingMode;
  30645. _this._buffer = buffer;
  30646. _this._deleteBuffer = deleteBuffer;
  30647. if (format) {
  30648. _this._format = format;
  30649. }
  30650. scene = _this.getScene();
  30651. if (!scene) {
  30652. return _this;
  30653. }
  30654. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30655. var load = function () {
  30656. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30657. _this.onLoadObservable.notifyObservers(_this);
  30658. }
  30659. if (onLoad) {
  30660. onLoad();
  30661. }
  30662. if (!_this.isBlocking && scene) {
  30663. scene.resetCachedMaterial();
  30664. }
  30665. };
  30666. if (!_this.url) {
  30667. _this._delayedOnLoad = load;
  30668. _this._delayedOnError = onError;
  30669. return _this;
  30670. }
  30671. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30672. if (!_this._texture) {
  30673. if (!scene.useDelayedTextureLoading) {
  30674. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30675. if (deleteBuffer) {
  30676. delete _this._buffer;
  30677. }
  30678. }
  30679. else {
  30680. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30681. _this._delayedOnLoad = load;
  30682. _this._delayedOnError = onError;
  30683. }
  30684. }
  30685. else {
  30686. if (_this._texture.isReady) {
  30687. BABYLON.Tools.SetImmediate(function () { return load(); });
  30688. }
  30689. else {
  30690. _this._texture.onLoadedObservable.add(load);
  30691. }
  30692. }
  30693. return _this;
  30694. }
  30695. Object.defineProperty(Texture.prototype, "noMipmap", {
  30696. get: function () {
  30697. return this._noMipmap;
  30698. },
  30699. enumerable: true,
  30700. configurable: true
  30701. });
  30702. Object.defineProperty(Texture.prototype, "isBlocking", {
  30703. get: function () {
  30704. return this._isBlocking;
  30705. },
  30706. set: function (value) {
  30707. this._isBlocking = value;
  30708. },
  30709. enumerable: true,
  30710. configurable: true
  30711. });
  30712. Object.defineProperty(Texture.prototype, "samplingMode", {
  30713. get: function () {
  30714. return this._samplingMode;
  30715. },
  30716. enumerable: true,
  30717. configurable: true
  30718. });
  30719. /**
  30720. * Update the url (and optional buffer) of this texture if url was null during construction.
  30721. * @param url the url of the texture
  30722. * @param buffer the buffer of the texture (defaults to null)
  30723. */
  30724. Texture.prototype.updateURL = function (url, buffer) {
  30725. if (buffer === void 0) { buffer = null; }
  30726. if (this.url) {
  30727. throw new Error("URL is already set");
  30728. }
  30729. this.url = url;
  30730. this._buffer = buffer;
  30731. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30732. this.delayLoad();
  30733. };
  30734. Texture.prototype.delayLoad = function () {
  30735. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30736. return;
  30737. }
  30738. var scene = this.getScene();
  30739. if (!scene) {
  30740. return;
  30741. }
  30742. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30743. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30744. if (!this._texture) {
  30745. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30746. if (this._deleteBuffer) {
  30747. delete this._buffer;
  30748. }
  30749. }
  30750. else {
  30751. if (this._delayedOnLoad) {
  30752. if (this._texture.isReady) {
  30753. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30754. }
  30755. else {
  30756. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30757. }
  30758. }
  30759. }
  30760. this._delayedOnLoad = null;
  30761. this._delayedOnError = null;
  30762. };
  30763. /**
  30764. * Default is Trilinear mode.
  30765. *
  30766. * | Value | Type | Description |
  30767. * | ----- | ------------------ | ----------- |
  30768. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30769. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30770. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30771. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30772. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30773. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30774. * | 7 | NEAREST_LINEAR | |
  30775. * | 8 | NEAREST_NEAREST | |
  30776. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30777. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30778. * | 11 | LINEAR_LINEAR | |
  30779. * | 12 | LINEAR_NEAREST | |
  30780. *
  30781. * > _mag_: magnification filter (close to the viewer)
  30782. * > _min_: minification filter (far from the viewer)
  30783. * > _mip_: filter used between mip map levels
  30784. *
  30785. */
  30786. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30787. if (!this._texture) {
  30788. return;
  30789. }
  30790. var scene = this.getScene();
  30791. if (!scene) {
  30792. return;
  30793. }
  30794. this._samplingMode = samplingMode;
  30795. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30796. };
  30797. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30798. x *= this.uScale;
  30799. y *= this.vScale;
  30800. x -= this.uRotationCenter * this.uScale;
  30801. y -= this.vRotationCenter * this.vScale;
  30802. z -= this.wRotationCenter;
  30803. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30804. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30805. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30806. t.z += this.wRotationCenter;
  30807. };
  30808. Texture.prototype.getTextureMatrix = function () {
  30809. var _this = this;
  30810. if (this.uOffset === this._cachedUOffset &&
  30811. this.vOffset === this._cachedVOffset &&
  30812. this.uScale === this._cachedUScale &&
  30813. this.vScale === this._cachedVScale &&
  30814. this.uAng === this._cachedUAng &&
  30815. this.vAng === this._cachedVAng &&
  30816. this.wAng === this._cachedWAng) {
  30817. return this._cachedTextureMatrix;
  30818. }
  30819. this._cachedUOffset = this.uOffset;
  30820. this._cachedVOffset = this.vOffset;
  30821. this._cachedUScale = this.uScale;
  30822. this._cachedVScale = this.vScale;
  30823. this._cachedUAng = this.uAng;
  30824. this._cachedVAng = this.vAng;
  30825. this._cachedWAng = this.wAng;
  30826. if (!this._cachedTextureMatrix) {
  30827. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30828. this._rowGenerationMatrix = new BABYLON.Matrix();
  30829. this._t0 = BABYLON.Vector3.Zero();
  30830. this._t1 = BABYLON.Vector3.Zero();
  30831. this._t2 = BABYLON.Vector3.Zero();
  30832. }
  30833. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30834. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30835. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30836. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30837. this._t1.subtractInPlace(this._t0);
  30838. this._t2.subtractInPlace(this._t0);
  30839. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30840. this._cachedTextureMatrix.m[0] = this._t1.x;
  30841. this._cachedTextureMatrix.m[1] = this._t1.y;
  30842. this._cachedTextureMatrix.m[2] = this._t1.z;
  30843. this._cachedTextureMatrix.m[4] = this._t2.x;
  30844. this._cachedTextureMatrix.m[5] = this._t2.y;
  30845. this._cachedTextureMatrix.m[6] = this._t2.z;
  30846. this._cachedTextureMatrix.m[8] = this._t0.x;
  30847. this._cachedTextureMatrix.m[9] = this._t0.y;
  30848. this._cachedTextureMatrix.m[10] = this._t0.z;
  30849. var scene = this.getScene();
  30850. if (!scene) {
  30851. return this._cachedTextureMatrix;
  30852. }
  30853. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30854. return mat.hasTexture(_this);
  30855. });
  30856. return this._cachedTextureMatrix;
  30857. };
  30858. Texture.prototype.getReflectionTextureMatrix = function () {
  30859. var _this = this;
  30860. var scene = this.getScene();
  30861. if (!scene) {
  30862. return this._cachedTextureMatrix;
  30863. }
  30864. if (this.uOffset === this._cachedUOffset &&
  30865. this.vOffset === this._cachedVOffset &&
  30866. this.uScale === this._cachedUScale &&
  30867. this.vScale === this._cachedVScale &&
  30868. this.coordinatesMode === this._cachedCoordinatesMode) {
  30869. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30870. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30871. return this._cachedTextureMatrix;
  30872. }
  30873. }
  30874. else {
  30875. return this._cachedTextureMatrix;
  30876. }
  30877. }
  30878. if (!this._cachedTextureMatrix) {
  30879. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30880. }
  30881. if (!this._projectionModeMatrix) {
  30882. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30883. }
  30884. this._cachedUOffset = this.uOffset;
  30885. this._cachedVOffset = this.vOffset;
  30886. this._cachedUScale = this.uScale;
  30887. this._cachedVScale = this.vScale;
  30888. this._cachedCoordinatesMode = this.coordinatesMode;
  30889. switch (this.coordinatesMode) {
  30890. case Texture.PLANAR_MODE:
  30891. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30892. this._cachedTextureMatrix[0] = this.uScale;
  30893. this._cachedTextureMatrix[5] = this.vScale;
  30894. this._cachedTextureMatrix[12] = this.uOffset;
  30895. this._cachedTextureMatrix[13] = this.vOffset;
  30896. break;
  30897. case Texture.PROJECTION_MODE:
  30898. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30899. this._projectionModeMatrix.m[0] = 0.5;
  30900. this._projectionModeMatrix.m[5] = -0.5;
  30901. this._projectionModeMatrix.m[10] = 0.0;
  30902. this._projectionModeMatrix.m[12] = 0.5;
  30903. this._projectionModeMatrix.m[13] = 0.5;
  30904. this._projectionModeMatrix.m[14] = 1.0;
  30905. this._projectionModeMatrix.m[15] = 1.0;
  30906. var projectionMatrix = scene.getProjectionMatrix();
  30907. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30908. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30909. break;
  30910. default:
  30911. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30912. break;
  30913. }
  30914. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30915. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30916. });
  30917. return this._cachedTextureMatrix;
  30918. };
  30919. Texture.prototype.clone = function () {
  30920. var _this = this;
  30921. return BABYLON.SerializationHelper.Clone(function () {
  30922. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30923. }, this);
  30924. };
  30925. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30926. get: function () {
  30927. if (!this._onLoadObservable) {
  30928. this._onLoadObservable = new BABYLON.Observable();
  30929. }
  30930. return this._onLoadObservable;
  30931. },
  30932. enumerable: true,
  30933. configurable: true
  30934. });
  30935. Texture.prototype.serialize = function () {
  30936. var serializationObject = _super.prototype.serialize.call(this);
  30937. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30938. serializationObject.base64String = this._buffer;
  30939. serializationObject.name = serializationObject.name.replace("data:", "");
  30940. }
  30941. serializationObject.invertY = this._invertY;
  30942. serializationObject.samplingMode = this.samplingMode;
  30943. return serializationObject;
  30944. };
  30945. Texture.prototype.getClassName = function () {
  30946. return "Texture";
  30947. };
  30948. Texture.prototype.dispose = function () {
  30949. _super.prototype.dispose.call(this);
  30950. if (this._onLoadObservable) {
  30951. this._onLoadObservable.clear();
  30952. this._onLoadObservable = null;
  30953. }
  30954. this._delayedOnLoad = null;
  30955. this._delayedOnError = null;
  30956. };
  30957. // Statics
  30958. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30959. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30960. if (onLoad === void 0) { onLoad = null; }
  30961. if (onError === void 0) { onError = null; }
  30962. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30963. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30964. };
  30965. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30966. if (parsedTexture.customType) {
  30967. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30968. // Update Sampling Mode
  30969. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30970. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30971. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30972. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30973. }
  30974. }
  30975. return parsedCustomTexture;
  30976. }
  30977. if (parsedTexture.isCube) {
  30978. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30979. }
  30980. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30981. return null;
  30982. }
  30983. var texture = BABYLON.SerializationHelper.Parse(function () {
  30984. var generateMipMaps = true;
  30985. if (parsedTexture.noMipmap) {
  30986. generateMipMaps = false;
  30987. }
  30988. if (parsedTexture.mirrorPlane) {
  30989. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30990. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30991. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30992. return mirrorTexture;
  30993. }
  30994. else if (parsedTexture.isRenderTarget) {
  30995. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30996. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30997. return renderTargetTexture;
  30998. }
  30999. else {
  31000. var texture;
  31001. if (parsedTexture.base64String) {
  31002. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31003. }
  31004. else {
  31005. var url = rootUrl + parsedTexture.name;
  31006. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31007. url = parsedTexture.url;
  31008. }
  31009. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31010. }
  31011. return texture;
  31012. }
  31013. }, parsedTexture, scene);
  31014. // Update Sampling Mode
  31015. if (parsedTexture.samplingMode) {
  31016. var sampling = parsedTexture.samplingMode;
  31017. if (texture._samplingMode !== sampling) {
  31018. texture.updateSamplingMode(sampling);
  31019. }
  31020. }
  31021. // Animations
  31022. if (parsedTexture.animations) {
  31023. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31024. var parsedAnimation = parsedTexture.animations[animationIndex];
  31025. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31026. }
  31027. }
  31028. return texture;
  31029. };
  31030. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31031. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31032. if (noMipmap === void 0) { noMipmap = false; }
  31033. if (invertY === void 0) { invertY = true; }
  31034. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31035. if (onLoad === void 0) { onLoad = null; }
  31036. if (onError === void 0) { onError = null; }
  31037. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31038. if (name.substr(0, 5) !== "data:") {
  31039. name = "data:" + name;
  31040. }
  31041. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31042. };
  31043. // Constants
  31044. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  31045. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  31046. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  31047. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  31048. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  31049. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  31050. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  31051. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  31052. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  31053. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  31054. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  31055. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  31056. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  31057. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  31058. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  31059. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  31060. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  31061. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  31062. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  31063. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  31064. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  31065. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  31066. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  31067. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  31068. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  31069. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  31070. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  31071. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  31072. /**
  31073. * 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
  31074. */
  31075. Texture.UseSerializedUrlIfAny = false;
  31076. __decorate([
  31077. BABYLON.serialize()
  31078. ], Texture.prototype, "url", void 0);
  31079. __decorate([
  31080. BABYLON.serialize()
  31081. ], Texture.prototype, "uOffset", void 0);
  31082. __decorate([
  31083. BABYLON.serialize()
  31084. ], Texture.prototype, "vOffset", void 0);
  31085. __decorate([
  31086. BABYLON.serialize()
  31087. ], Texture.prototype, "uScale", void 0);
  31088. __decorate([
  31089. BABYLON.serialize()
  31090. ], Texture.prototype, "vScale", void 0);
  31091. __decorate([
  31092. BABYLON.serialize()
  31093. ], Texture.prototype, "uAng", void 0);
  31094. __decorate([
  31095. BABYLON.serialize()
  31096. ], Texture.prototype, "vAng", void 0);
  31097. __decorate([
  31098. BABYLON.serialize()
  31099. ], Texture.prototype, "wAng", void 0);
  31100. __decorate([
  31101. BABYLON.serialize()
  31102. ], Texture.prototype, "uRotationCenter", void 0);
  31103. __decorate([
  31104. BABYLON.serialize()
  31105. ], Texture.prototype, "vRotationCenter", void 0);
  31106. __decorate([
  31107. BABYLON.serialize()
  31108. ], Texture.prototype, "wRotationCenter", void 0);
  31109. __decorate([
  31110. BABYLON.serialize()
  31111. ], Texture.prototype, "isBlocking", null);
  31112. return Texture;
  31113. }(BABYLON.BaseTexture));
  31114. BABYLON.Texture = Texture;
  31115. })(BABYLON || (BABYLON = {}));
  31116. //# sourceMappingURL=babylon.texture.js.map
  31117. var BABYLON;
  31118. (function (BABYLON) {
  31119. /**
  31120. * @hidden
  31121. **/
  31122. var _InstancesBatch = /** @class */ (function () {
  31123. function _InstancesBatch() {
  31124. this.mustReturn = false;
  31125. this.visibleInstances = new Array();
  31126. this.renderSelf = new Array();
  31127. }
  31128. return _InstancesBatch;
  31129. }());
  31130. BABYLON._InstancesBatch = _InstancesBatch;
  31131. /**
  31132. * Class used to represent renderable models
  31133. */
  31134. var Mesh = /** @class */ (function (_super) {
  31135. __extends(Mesh, _super);
  31136. /**
  31137. * @constructor
  31138. * @param name The value used by scene.getMeshByName() to do a lookup.
  31139. * @param scene The scene to add this mesh to.
  31140. * @param parent The parent of this mesh, if it has one
  31141. * @param source An optional Mesh from which geometry is shared, cloned.
  31142. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31143. * When false, achieved by calling a clone(), also passing False.
  31144. * This will make creation of children, recursive.
  31145. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31146. */
  31147. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31148. if (scene === void 0) { scene = null; }
  31149. if (parent === void 0) { parent = null; }
  31150. if (source === void 0) { source = null; }
  31151. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31152. var _this = _super.call(this, name, scene) || this;
  31153. // Members
  31154. /**
  31155. * Gets the delay loading state of the mesh (when delay loading is turned on)
  31156. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  31157. */
  31158. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31159. /**
  31160. * Gets the list of instances created from this mesh
  31161. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  31162. */
  31163. _this.instances = new Array();
  31164. _this._LODLevels = new Array();
  31165. /** @hidden */
  31166. _this._visibleInstances = {};
  31167. _this._renderIdForInstances = new Array();
  31168. _this._batchCache = new _InstancesBatch();
  31169. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31170. // Use by builder only to know what orientation were the mesh build in.
  31171. /** @hidden */
  31172. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  31173. /**
  31174. * Use this property to change the original side orientation defined at construction time
  31175. */
  31176. _this.overrideMaterialSideOrientation = null;
  31177. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31178. // Will be used to save a source mesh reference, If any
  31179. _this._source = null;
  31180. scene = _this.getScene();
  31181. if (source) {
  31182. // Geometry
  31183. if (source._geometry) {
  31184. source._geometry.applyToMesh(_this);
  31185. }
  31186. // Deep copy
  31187. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31188. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  31189. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  31190. ], ["_poseMatrix"]);
  31191. // Source mesh
  31192. _this._source = source;
  31193. // Construction Params
  31194. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  31195. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  31196. var myAnyThis = _this;
  31197. var myAnySource = source;
  31198. myAnyThis._closePath = myAnySource._closePath;
  31199. myAnyThis._idx = myAnySource._idx;
  31200. myAnyThis.dashSize = myAnySource.dashSize;
  31201. myAnyThis.gapSize = myAnySource.gapSize;
  31202. myAnyThis.path3D = myAnySource.path3D;
  31203. myAnyThis.pathArray = myAnySource.pathArray;
  31204. myAnyThis.arc = myAnySource.arc;
  31205. myAnyThis.radius = myAnySource.radius;
  31206. // Animation ranges
  31207. if (_this._source._ranges) {
  31208. var ranges = _this._source._ranges;
  31209. for (var name in ranges) {
  31210. if (!ranges.hasOwnProperty(name)) {
  31211. continue;
  31212. }
  31213. if (!ranges[name]) {
  31214. continue;
  31215. }
  31216. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  31217. }
  31218. }
  31219. // Metadata
  31220. if (source.metadata && source.metadata.clone) {
  31221. _this.metadata = source.metadata.clone();
  31222. }
  31223. else {
  31224. _this.metadata = source.metadata;
  31225. }
  31226. // Tags
  31227. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31228. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31229. }
  31230. // Parent
  31231. _this.parent = source.parent;
  31232. // Pivot
  31233. _this.setPivotMatrix(source.getPivotMatrix());
  31234. _this.id = name + "." + source.id;
  31235. // Material
  31236. _this.material = source.material;
  31237. var index;
  31238. if (!doNotCloneChildren) {
  31239. // Children
  31240. var directDescendants = source.getDescendants(true);
  31241. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31242. var child = directDescendants[index_1];
  31243. if (child.clone) {
  31244. child.clone(name + "." + child.name, _this);
  31245. }
  31246. }
  31247. }
  31248. // Physics clone
  31249. var physicsEngine = _this.getScene().getPhysicsEngine();
  31250. if (clonePhysicsImpostor && physicsEngine) {
  31251. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31252. if (impostor) {
  31253. _this.physicsImpostor = impostor.clone(_this);
  31254. }
  31255. }
  31256. // Particles
  31257. for (index = 0; index < scene.particleSystems.length; index++) {
  31258. var system = scene.particleSystems[index];
  31259. if (system.emitter === source) {
  31260. system.clone(system.name, _this);
  31261. }
  31262. }
  31263. _this.refreshBoundingInfo();
  31264. _this.computeWorldMatrix(true);
  31265. }
  31266. // Parent
  31267. if (parent !== null) {
  31268. _this.parent = parent;
  31269. }
  31270. return _this;
  31271. }
  31272. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31273. /**
  31274. * An event triggered before rendering the mesh
  31275. */
  31276. get: function () {
  31277. if (!this._onBeforeRenderObservable) {
  31278. this._onBeforeRenderObservable = new BABYLON.Observable();
  31279. }
  31280. return this._onBeforeRenderObservable;
  31281. },
  31282. enumerable: true,
  31283. configurable: true
  31284. });
  31285. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31286. /**
  31287. * An event triggered after rendering the mesh
  31288. */
  31289. get: function () {
  31290. if (!this._onAfterRenderObservable) {
  31291. this._onAfterRenderObservable = new BABYLON.Observable();
  31292. }
  31293. return this._onAfterRenderObservable;
  31294. },
  31295. enumerable: true,
  31296. configurable: true
  31297. });
  31298. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31299. /**
  31300. * An event triggered before drawing the mesh
  31301. */
  31302. get: function () {
  31303. if (!this._onBeforeDrawObservable) {
  31304. this._onBeforeDrawObservable = new BABYLON.Observable();
  31305. }
  31306. return this._onBeforeDrawObservable;
  31307. },
  31308. enumerable: true,
  31309. configurable: true
  31310. });
  31311. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31312. /**
  31313. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  31314. */
  31315. set: function (callback) {
  31316. if (this._onBeforeDrawObserver) {
  31317. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31318. }
  31319. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31320. },
  31321. enumerable: true,
  31322. configurable: true
  31323. });
  31324. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31325. /**
  31326. * Gets or sets the morph target manager
  31327. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  31328. */
  31329. get: function () {
  31330. return this._morphTargetManager;
  31331. },
  31332. set: function (value) {
  31333. if (this._morphTargetManager === value) {
  31334. return;
  31335. }
  31336. this._morphTargetManager = value;
  31337. this._syncGeometryWithMorphTargetManager();
  31338. },
  31339. enumerable: true,
  31340. configurable: true
  31341. });
  31342. Object.defineProperty(Mesh.prototype, "source", {
  31343. /**
  31344. * Gets the source mesh (the one used to clone this one from)
  31345. */
  31346. get: function () {
  31347. return this._source;
  31348. },
  31349. enumerable: true,
  31350. configurable: true
  31351. });
  31352. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31353. /**
  31354. * Gets or sets a boolean indicating that this mesh does not use index buffer
  31355. */
  31356. get: function () {
  31357. return this._unIndexed;
  31358. },
  31359. set: function (value) {
  31360. if (this._unIndexed !== value) {
  31361. this._unIndexed = value;
  31362. this._markSubMeshesAsAttributesDirty();
  31363. }
  31364. },
  31365. enumerable: true,
  31366. configurable: true
  31367. });
  31368. // Methods
  31369. /**
  31370. * Gets the class name
  31371. * @returns the string "Mesh".
  31372. */
  31373. Mesh.prototype.getClassName = function () {
  31374. return "Mesh";
  31375. };
  31376. /**
  31377. * Returns a description of this mesh
  31378. * @param fullDetails define if full details about this mesh must be used
  31379. * @returns a descriptive string representing this mesh
  31380. */
  31381. Mesh.prototype.toString = function (fullDetails) {
  31382. var ret = _super.prototype.toString.call(this, fullDetails);
  31383. ret += ", n vertices: " + this.getTotalVertices();
  31384. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31385. if (this.animations) {
  31386. for (var i = 0; i < this.animations.length; i++) {
  31387. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31388. }
  31389. }
  31390. if (fullDetails) {
  31391. if (this._geometry) {
  31392. var ib = this.getIndices();
  31393. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31394. if (vb && ib) {
  31395. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31396. }
  31397. }
  31398. else {
  31399. ret += ", flat shading: UNKNOWN";
  31400. }
  31401. }
  31402. return ret;
  31403. };
  31404. /** @hidden */
  31405. Mesh.prototype._unBindEffect = function () {
  31406. _super.prototype._unBindEffect.call(this);
  31407. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31408. var instance = _a[_i];
  31409. instance._unBindEffect();
  31410. }
  31411. };
  31412. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31413. /**
  31414. * Gets a boolean indicating if this mesh has LOD
  31415. */
  31416. get: function () {
  31417. return this._LODLevels.length > 0;
  31418. },
  31419. enumerable: true,
  31420. configurable: true
  31421. });
  31422. /**
  31423. * Gets the list of MeshLODLevel associated with the current mesh
  31424. * @returns an array of MeshLODLevel
  31425. */
  31426. Mesh.prototype.getLODLevels = function () {
  31427. return this._LODLevels;
  31428. };
  31429. Mesh.prototype._sortLODLevels = function () {
  31430. this._LODLevels.sort(function (a, b) {
  31431. if (a.distance < b.distance) {
  31432. return 1;
  31433. }
  31434. if (a.distance > b.distance) {
  31435. return -1;
  31436. }
  31437. return 0;
  31438. });
  31439. };
  31440. /**
  31441. * Add a mesh as LOD level triggered at the given distance.
  31442. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31443. * @param distance The distance from the center of the object to show this level
  31444. * @param mesh The mesh to be added as LOD level (can be null)
  31445. * @return This mesh (for chaining)
  31446. */
  31447. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31448. if (mesh && mesh._masterMesh) {
  31449. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31450. return this;
  31451. }
  31452. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31453. this._LODLevels.push(level);
  31454. if (mesh) {
  31455. mesh._masterMesh = this;
  31456. }
  31457. this._sortLODLevels();
  31458. return this;
  31459. };
  31460. /**
  31461. * Returns the LOD level mesh at the passed distance or null if not found.
  31462. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31463. * @param distance The distance from the center of the object to show this level
  31464. * @returns a Mesh or `null`
  31465. */
  31466. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31467. for (var index = 0; index < this._LODLevels.length; index++) {
  31468. var level = this._LODLevels[index];
  31469. if (level.distance === distance) {
  31470. return level.mesh;
  31471. }
  31472. }
  31473. return null;
  31474. };
  31475. /**
  31476. * Remove a mesh from the LOD array
  31477. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31478. * @param mesh defines the mesh to be removed
  31479. * @return This mesh (for chaining)
  31480. */
  31481. Mesh.prototype.removeLODLevel = function (mesh) {
  31482. for (var index = 0; index < this._LODLevels.length; index++) {
  31483. if (this._LODLevels[index].mesh === mesh) {
  31484. this._LODLevels.splice(index, 1);
  31485. if (mesh) {
  31486. mesh._masterMesh = null;
  31487. }
  31488. }
  31489. }
  31490. this._sortLODLevels();
  31491. return this;
  31492. };
  31493. /**
  31494. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31495. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31496. * @param camera defines the camera to use to compute distance
  31497. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  31498. * @return This mesh (for chaining)
  31499. */
  31500. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31501. if (!this._LODLevels || this._LODLevels.length === 0) {
  31502. return this;
  31503. }
  31504. var bSphere;
  31505. if (boundingSphere) {
  31506. bSphere = boundingSphere;
  31507. }
  31508. else {
  31509. var boundingInfo = this.getBoundingInfo();
  31510. bSphere = boundingInfo.boundingSphere;
  31511. }
  31512. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31513. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31514. if (this.onLODLevelSelection) {
  31515. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31516. }
  31517. return this;
  31518. }
  31519. for (var index = 0; index < this._LODLevels.length; index++) {
  31520. var level = this._LODLevels[index];
  31521. if (level.distance < distanceToCamera) {
  31522. if (level.mesh) {
  31523. level.mesh._preActivate();
  31524. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31525. }
  31526. if (this.onLODLevelSelection) {
  31527. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31528. }
  31529. return level.mesh;
  31530. }
  31531. }
  31532. if (this.onLODLevelSelection) {
  31533. this.onLODLevelSelection(distanceToCamera, this, this);
  31534. }
  31535. return this;
  31536. };
  31537. Object.defineProperty(Mesh.prototype, "geometry", {
  31538. /**
  31539. * Gets the mesh internal Geometry object
  31540. */
  31541. get: function () {
  31542. return this._geometry;
  31543. },
  31544. enumerable: true,
  31545. configurable: true
  31546. });
  31547. /**
  31548. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31549. * @returns the total number of vertices
  31550. */
  31551. Mesh.prototype.getTotalVertices = function () {
  31552. if (this._geometry === null || this._geometry === undefined) {
  31553. return 0;
  31554. }
  31555. return this._geometry.getTotalVertices();
  31556. };
  31557. /**
  31558. * Returns the content of an associated vertex buffer
  31559. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31560. * - BABYLON.VertexBuffer.PositionKind
  31561. * - BABYLON.VertexBuffer.UVKind
  31562. * - BABYLON.VertexBuffer.UV2Kind
  31563. * - BABYLON.VertexBuffer.UV3Kind
  31564. * - BABYLON.VertexBuffer.UV4Kind
  31565. * - BABYLON.VertexBuffer.UV5Kind
  31566. * - BABYLON.VertexBuffer.UV6Kind
  31567. * - BABYLON.VertexBuffer.ColorKind
  31568. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31569. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31570. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31571. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31572. * @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
  31573. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  31574. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  31575. */
  31576. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31577. if (!this._geometry) {
  31578. return null;
  31579. }
  31580. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31581. };
  31582. /**
  31583. * Returns the mesh VertexBuffer object from the requested `kind`
  31584. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31585. * - BABYLON.VertexBuffer.PositionKind
  31586. * - BABYLON.VertexBuffer.UVKind
  31587. * - BABYLON.VertexBuffer.UV2Kind
  31588. * - BABYLON.VertexBuffer.UV3Kind
  31589. * - BABYLON.VertexBuffer.UV4Kind
  31590. * - BABYLON.VertexBuffer.UV5Kind
  31591. * - BABYLON.VertexBuffer.UV6Kind
  31592. * - BABYLON.VertexBuffer.ColorKind
  31593. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31594. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31595. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31596. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31597. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  31598. */
  31599. Mesh.prototype.getVertexBuffer = function (kind) {
  31600. if (!this._geometry) {
  31601. return null;
  31602. }
  31603. return this._geometry.getVertexBuffer(kind);
  31604. };
  31605. /**
  31606. * Tests if a specific vertex buffer is associated with this mesh
  31607. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31608. * - BABYLON.VertexBuffer.PositionKind
  31609. * - BABYLON.VertexBuffer.UVKind
  31610. * - BABYLON.VertexBuffer.UV2Kind
  31611. * - BABYLON.VertexBuffer.UV3Kind
  31612. * - BABYLON.VertexBuffer.UV4Kind
  31613. * - BABYLON.VertexBuffer.UV5Kind
  31614. * - BABYLON.VertexBuffer.UV6Kind
  31615. * - BABYLON.VertexBuffer.ColorKind
  31616. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31617. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31618. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31619. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31620. * @returns a boolean
  31621. */
  31622. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31623. if (!this._geometry) {
  31624. if (this._delayInfo) {
  31625. return this._delayInfo.indexOf(kind) !== -1;
  31626. }
  31627. return false;
  31628. }
  31629. return this._geometry.isVerticesDataPresent(kind);
  31630. };
  31631. /**
  31632. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31633. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31634. * - BABYLON.VertexBuffer.PositionKind
  31635. * - BABYLON.VertexBuffer.UVKind
  31636. * - BABYLON.VertexBuffer.UV2Kind
  31637. * - BABYLON.VertexBuffer.UV3Kind
  31638. * - BABYLON.VertexBuffer.UV4Kind
  31639. * - BABYLON.VertexBuffer.UV5Kind
  31640. * - BABYLON.VertexBuffer.UV6Kind
  31641. * - BABYLON.VertexBuffer.ColorKind
  31642. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31643. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31644. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31645. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31646. * @returns a boolean
  31647. */
  31648. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31649. if (!this._geometry) {
  31650. if (this._delayInfo) {
  31651. return this._delayInfo.indexOf(kind) !== -1;
  31652. }
  31653. return false;
  31654. }
  31655. return this._geometry.isVertexBufferUpdatable(kind);
  31656. };
  31657. /**
  31658. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  31659. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31660. * - BABYLON.VertexBuffer.PositionKind
  31661. * - BABYLON.VertexBuffer.UVKind
  31662. * - BABYLON.VertexBuffer.UV2Kind
  31663. * - BABYLON.VertexBuffer.UV3Kind
  31664. * - BABYLON.VertexBuffer.UV4Kind
  31665. * - BABYLON.VertexBuffer.UV5Kind
  31666. * - BABYLON.VertexBuffer.UV6Kind
  31667. * - BABYLON.VertexBuffer.ColorKind
  31668. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31669. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31670. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31671. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31672. * @returns an array of strings
  31673. */
  31674. Mesh.prototype.getVerticesDataKinds = function () {
  31675. if (!this._geometry) {
  31676. var result = new Array();
  31677. if (this._delayInfo) {
  31678. this._delayInfo.forEach(function (kind, index, array) {
  31679. result.push(kind);
  31680. });
  31681. }
  31682. return result;
  31683. }
  31684. return this._geometry.getVerticesDataKinds();
  31685. };
  31686. /**
  31687. * Returns a positive integer : the total number of indices in this mesh geometry.
  31688. * @returns the numner of indices or zero if the mesh has no geometry.
  31689. */
  31690. Mesh.prototype.getTotalIndices = function () {
  31691. if (!this._geometry) {
  31692. return 0;
  31693. }
  31694. return this._geometry.getTotalIndices();
  31695. };
  31696. /**
  31697. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31698. * @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.
  31699. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31700. * @returns the indices array or an empty array if the mesh has no geometry
  31701. */
  31702. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31703. if (!this._geometry) {
  31704. return [];
  31705. }
  31706. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31707. };
  31708. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31709. get: function () {
  31710. return this._masterMesh !== null && this._masterMesh !== undefined;
  31711. },
  31712. enumerable: true,
  31713. configurable: true
  31714. });
  31715. /**
  31716. * Determine if the current mesh is ready to be rendered
  31717. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31718. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31719. * @returns true if all associated assets are ready (material, textures, shaders)
  31720. */
  31721. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31722. if (completeCheck === void 0) { completeCheck = false; }
  31723. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31724. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31725. return false;
  31726. }
  31727. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31728. return false;
  31729. }
  31730. if (!this.subMeshes || this.subMeshes.length === 0) {
  31731. return true;
  31732. }
  31733. if (!completeCheck) {
  31734. return true;
  31735. }
  31736. var engine = this.getEngine();
  31737. var scene = this.getScene();
  31738. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31739. this.computeWorldMatrix();
  31740. var mat = this.material || scene.defaultMaterial;
  31741. if (mat) {
  31742. if (mat.storeEffectOnSubMeshes) {
  31743. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31744. var subMesh = _a[_i];
  31745. var effectiveMaterial = subMesh.getMaterial();
  31746. if (effectiveMaterial) {
  31747. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31748. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31749. return false;
  31750. }
  31751. }
  31752. else {
  31753. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31754. return false;
  31755. }
  31756. }
  31757. }
  31758. }
  31759. }
  31760. else {
  31761. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31762. return false;
  31763. }
  31764. }
  31765. }
  31766. // Shadows
  31767. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31768. var light = _c[_b];
  31769. var generator = light.getShadowGenerator();
  31770. if (generator) {
  31771. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31772. var subMesh = _e[_d];
  31773. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31774. return false;
  31775. }
  31776. }
  31777. }
  31778. }
  31779. // LOD
  31780. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31781. var lod = _g[_f];
  31782. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31783. return false;
  31784. }
  31785. }
  31786. return true;
  31787. };
  31788. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31789. /**
  31790. * 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.
  31791. */
  31792. get: function () {
  31793. return this._areNormalsFrozen;
  31794. },
  31795. enumerable: true,
  31796. configurable: true
  31797. });
  31798. /**
  31799. * 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.
  31800. * @returns the current mesh
  31801. */
  31802. Mesh.prototype.freezeNormals = function () {
  31803. this._areNormalsFrozen = true;
  31804. return this;
  31805. };
  31806. /**
  31807. * 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
  31808. * @returns the current mesh
  31809. */
  31810. Mesh.prototype.unfreezeNormals = function () {
  31811. this._areNormalsFrozen = false;
  31812. return this;
  31813. };
  31814. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31815. /**
  31816. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31817. */
  31818. set: function (count) {
  31819. this._overridenInstanceCount = count;
  31820. },
  31821. enumerable: true,
  31822. configurable: true
  31823. });
  31824. // Methods
  31825. /** @hidden */
  31826. Mesh.prototype._preActivate = function () {
  31827. var sceneRenderId = this.getScene().getRenderId();
  31828. if (this._preActivateId === sceneRenderId) {
  31829. return this;
  31830. }
  31831. this._preActivateId = sceneRenderId;
  31832. this._visibleInstances = null;
  31833. return this;
  31834. };
  31835. /** @hidden */
  31836. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31837. if (this._visibleInstances) {
  31838. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31839. }
  31840. return this;
  31841. };
  31842. /** @hidden */
  31843. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31844. if (!this._visibleInstances) {
  31845. this._visibleInstances = {};
  31846. this._visibleInstances.defaultRenderId = renderId;
  31847. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31848. }
  31849. if (!this._visibleInstances[renderId]) {
  31850. this._visibleInstances[renderId] = new Array();
  31851. }
  31852. this._visibleInstances[renderId].push(instance);
  31853. return this;
  31854. };
  31855. /**
  31856. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31857. * This means the mesh underlying bounding box and sphere are recomputed.
  31858. * @returns the current mesh
  31859. */
  31860. Mesh.prototype.refreshBoundingInfo = function () {
  31861. return this._refreshBoundingInfo(false);
  31862. };
  31863. /** @hidden */
  31864. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31865. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31866. return this;
  31867. }
  31868. var data = this._getPositionData(applySkeleton);
  31869. if (data) {
  31870. var bias = this.geometry ? this.geometry.boundingBias : null;
  31871. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  31872. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31873. }
  31874. if (this.subMeshes) {
  31875. for (var index = 0; index < this.subMeshes.length; index++) {
  31876. this.subMeshes[index].refreshBoundingInfo();
  31877. }
  31878. }
  31879. this._updateBoundingInfo();
  31880. return this;
  31881. };
  31882. Mesh.prototype._getPositionData = function (applySkeleton) {
  31883. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31884. if (data && applySkeleton && this.skeleton) {
  31885. data = BABYLON.Tools.Slice(data);
  31886. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31887. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31888. if (matricesWeightsData && matricesIndicesData) {
  31889. var needExtras = this.numBoneInfluencers > 4;
  31890. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31891. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31892. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31893. var tempVector = BABYLON.Tmp.Vector3[0];
  31894. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31895. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31896. var matWeightIdx = 0;
  31897. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31898. finalMatrix.reset();
  31899. var inf;
  31900. var weight;
  31901. for (inf = 0; inf < 4; inf++) {
  31902. weight = matricesWeightsData[matWeightIdx + inf];
  31903. if (weight > 0) {
  31904. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31905. finalMatrix.addToSelf(tempMatrix);
  31906. }
  31907. }
  31908. if (needExtras) {
  31909. for (inf = 0; inf < 4; inf++) {
  31910. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31911. if (weight > 0) {
  31912. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31913. finalMatrix.addToSelf(tempMatrix);
  31914. }
  31915. }
  31916. }
  31917. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31918. tempVector.toArray(data, index);
  31919. }
  31920. }
  31921. }
  31922. return data;
  31923. };
  31924. /** @hidden */
  31925. Mesh.prototype._createGlobalSubMesh = function (force) {
  31926. var totalVertices = this.getTotalVertices();
  31927. if (!totalVertices || !this.getIndices()) {
  31928. return null;
  31929. }
  31930. // Check if we need to recreate the submeshes
  31931. if (this.subMeshes && this.subMeshes.length > 0) {
  31932. var ib = this.getIndices();
  31933. if (!ib) {
  31934. return null;
  31935. }
  31936. var totalIndices = ib.length;
  31937. var needToRecreate = false;
  31938. if (force) {
  31939. needToRecreate = true;
  31940. }
  31941. else {
  31942. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31943. var submesh = _a[_i];
  31944. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31945. needToRecreate = true;
  31946. break;
  31947. }
  31948. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31949. needToRecreate = true;
  31950. break;
  31951. }
  31952. }
  31953. }
  31954. if (!needToRecreate) {
  31955. return this.subMeshes[0];
  31956. }
  31957. }
  31958. this.releaseSubMeshes();
  31959. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31960. };
  31961. /**
  31962. * This function will subdivide the mesh into multiple submeshes
  31963. * @param count defines the expected number of submeshes
  31964. */
  31965. Mesh.prototype.subdivide = function (count) {
  31966. if (count < 1) {
  31967. return;
  31968. }
  31969. var totalIndices = this.getTotalIndices();
  31970. var subdivisionSize = (totalIndices / count) | 0;
  31971. var offset = 0;
  31972. // Ensure that subdivisionSize is a multiple of 3
  31973. while (subdivisionSize % 3 !== 0) {
  31974. subdivisionSize++;
  31975. }
  31976. this.releaseSubMeshes();
  31977. for (var index = 0; index < count; index++) {
  31978. if (offset >= totalIndices) {
  31979. break;
  31980. }
  31981. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31982. offset += subdivisionSize;
  31983. }
  31984. this.synchronizeInstances();
  31985. };
  31986. /**
  31987. * Copy a FloatArray into a specific associated vertex buffer
  31988. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  31989. * - BABYLON.VertexBuffer.PositionKind
  31990. * - BABYLON.VertexBuffer.UVKind
  31991. * - BABYLON.VertexBuffer.UV2Kind
  31992. * - BABYLON.VertexBuffer.UV3Kind
  31993. * - BABYLON.VertexBuffer.UV4Kind
  31994. * - BABYLON.VertexBuffer.UV5Kind
  31995. * - BABYLON.VertexBuffer.UV6Kind
  31996. * - BABYLON.VertexBuffer.ColorKind
  31997. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31998. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31999. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32000. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32001. * @param data defines the data source
  32002. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  32003. * @param stride defines the data stride size (can be null)
  32004. * @returns the current mesh
  32005. */
  32006. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32007. if (updatable === void 0) { updatable = false; }
  32008. if (!this._geometry) {
  32009. var vertexData = new BABYLON.VertexData();
  32010. vertexData.set(data, kind);
  32011. var scene = this.getScene();
  32012. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32013. }
  32014. else {
  32015. this._geometry.setVerticesData(kind, data, updatable, stride);
  32016. }
  32017. return this;
  32018. };
  32019. /**
  32020. * Flags an associated vertex buffer as updatable
  32021. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  32022. * - BABYLON.VertexBuffer.PositionKind
  32023. * - BABYLON.VertexBuffer.UVKind
  32024. * - BABYLON.VertexBuffer.UV2Kind
  32025. * - BABYLON.VertexBuffer.UV3Kind
  32026. * - BABYLON.VertexBuffer.UV4Kind
  32027. * - BABYLON.VertexBuffer.UV5Kind
  32028. * - BABYLON.VertexBuffer.UV6Kind
  32029. * - BABYLON.VertexBuffer.ColorKind
  32030. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32031. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32032. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32033. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32034. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  32035. */
  32036. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32037. if (updatable === void 0) { updatable = true; }
  32038. var vb = this.getVertexBuffer(kind);
  32039. if (!vb || vb.isUpdatable() === updatable) {
  32040. return;
  32041. }
  32042. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32043. };
  32044. /**
  32045. * Sets the mesh global Vertex Buffer
  32046. * @param buffer defines the buffer to use
  32047. * @returns the current mesh
  32048. */
  32049. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32050. if (!this._geometry) {
  32051. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32052. }
  32053. this._geometry.setVerticesBuffer(buffer);
  32054. return this;
  32055. };
  32056. /**
  32057. * Update a specific associated vertex buffer
  32058. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  32059. * - BABYLON.VertexBuffer.PositionKind
  32060. * - BABYLON.VertexBuffer.UVKind
  32061. * - BABYLON.VertexBuffer.UV2Kind
  32062. * - BABYLON.VertexBuffer.UV3Kind
  32063. * - BABYLON.VertexBuffer.UV4Kind
  32064. * - BABYLON.VertexBuffer.UV5Kind
  32065. * - BABYLON.VertexBuffer.UV6Kind
  32066. * - BABYLON.VertexBuffer.ColorKind
  32067. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32068. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32069. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32070. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32071. * @param data defines the data source
  32072. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  32073. * @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)
  32074. * @returns the current mesh
  32075. */
  32076. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32077. if (!this._geometry) {
  32078. return this;
  32079. }
  32080. if (!makeItUnique) {
  32081. this._geometry.updateVerticesData(kind, data, updateExtends);
  32082. }
  32083. else {
  32084. this.makeGeometryUnique();
  32085. this.updateVerticesData(kind, data, updateExtends, false);
  32086. }
  32087. return this;
  32088. };
  32089. /**
  32090. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32091. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32092. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  32093. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  32094. * @returns the current mesh
  32095. */
  32096. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32097. if (computeNormals === void 0) { computeNormals = true; }
  32098. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32099. if (!positions) {
  32100. return this;
  32101. }
  32102. positionFunction(positions);
  32103. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32104. if (computeNormals) {
  32105. var indices = this.getIndices();
  32106. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32107. if (!normals) {
  32108. return this;
  32109. }
  32110. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32111. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32112. }
  32113. return this;
  32114. };
  32115. /**
  32116. * Creates a un-shared specific occurence of the geometry for the mesh.
  32117. * @returns the current mesh
  32118. */
  32119. Mesh.prototype.makeGeometryUnique = function () {
  32120. if (!this._geometry) {
  32121. return this;
  32122. }
  32123. var oldGeometry = this._geometry;
  32124. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32125. oldGeometry.releaseForMesh(this, true);
  32126. geometry.applyToMesh(this);
  32127. return this;
  32128. };
  32129. /**
  32130. * Set the index buffer of this mesh
  32131. * @param indices defines the source data
  32132. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  32133. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  32134. * @returns the current mesh
  32135. */
  32136. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32137. if (totalVertices === void 0) { totalVertices = null; }
  32138. if (updatable === void 0) { updatable = false; }
  32139. if (!this._geometry) {
  32140. var vertexData = new BABYLON.VertexData();
  32141. vertexData.indices = indices;
  32142. var scene = this.getScene();
  32143. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32144. }
  32145. else {
  32146. this._geometry.setIndices(indices, totalVertices, updatable);
  32147. }
  32148. return this;
  32149. };
  32150. /**
  32151. * Update the current index buffer
  32152. * @param indices defines the source data
  32153. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  32154. * @returns the current mesh
  32155. */
  32156. Mesh.prototype.updateIndices = function (indices, offset) {
  32157. if (!this._geometry) {
  32158. return this;
  32159. }
  32160. this._geometry.updateIndices(indices, offset);
  32161. return this;
  32162. };
  32163. /**
  32164. * Invert the geometry to move from a right handed system to a left handed one.
  32165. * @returns the current mesh
  32166. */
  32167. Mesh.prototype.toLeftHanded = function () {
  32168. if (!this._geometry) {
  32169. return this;
  32170. }
  32171. this._geometry.toLeftHanded();
  32172. return this;
  32173. };
  32174. /** @hidden */
  32175. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32176. if (!this._geometry) {
  32177. return this;
  32178. }
  32179. var engine = this.getScene().getEngine();
  32180. // Wireframe
  32181. var indexToBind;
  32182. if (this._unIndexed) {
  32183. indexToBind = null;
  32184. }
  32185. else {
  32186. switch (fillMode) {
  32187. case BABYLON.Material.PointFillMode:
  32188. indexToBind = null;
  32189. break;
  32190. case BABYLON.Material.WireFrameFillMode:
  32191. indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
  32192. break;
  32193. default:
  32194. case BABYLON.Material.TriangleFillMode:
  32195. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32196. break;
  32197. }
  32198. }
  32199. // VBOs
  32200. this._geometry._bind(effect, indexToBind);
  32201. return this;
  32202. };
  32203. /** @hidden */
  32204. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32205. if (alternate === void 0) { alternate = false; }
  32206. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32207. return this;
  32208. }
  32209. if (this._onBeforeDrawObservable) {
  32210. this._onBeforeDrawObservable.notifyObservers(this);
  32211. }
  32212. var scene = this.getScene();
  32213. var engine = scene.getEngine();
  32214. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32215. // or triangles as points
  32216. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32217. }
  32218. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32219. // Triangles as wireframe
  32220. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  32221. }
  32222. else {
  32223. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32224. }
  32225. if (scene._isAlternateRenderingEnabled && !alternate) {
  32226. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32227. if (!effect || !scene.activeCamera) {
  32228. return this;
  32229. }
  32230. scene._switchToAlternateCameraConfiguration(true);
  32231. this._effectiveMaterial.bindView(effect);
  32232. this._effectiveMaterial.bindViewProjection(effect);
  32233. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32234. this._draw(subMesh, fillMode, instancesCount, true);
  32235. engine.setViewport(scene.activeCamera.viewport);
  32236. scene._switchToAlternateCameraConfiguration(false);
  32237. this._effectiveMaterial.bindView(effect);
  32238. this._effectiveMaterial.bindViewProjection(effect);
  32239. }
  32240. return this;
  32241. };
  32242. /**
  32243. * Registers for this mesh a javascript function called just before the rendering process
  32244. * @param func defines the function to call before rendering this mesh
  32245. * @returns the current mesh
  32246. */
  32247. Mesh.prototype.registerBeforeRender = function (func) {
  32248. this.onBeforeRenderObservable.add(func);
  32249. return this;
  32250. };
  32251. /**
  32252. * Disposes a previously registered javascript function called before the rendering
  32253. * @param func defines the function to remove
  32254. * @returns the current mesh
  32255. */
  32256. Mesh.prototype.unregisterBeforeRender = function (func) {
  32257. this.onBeforeRenderObservable.removeCallback(func);
  32258. return this;
  32259. };
  32260. /**
  32261. * Registers for this mesh a javascript function called just after the rendering is complete
  32262. * @param func defines the function to call after rendering this mesh
  32263. * @returns the current mesh
  32264. */
  32265. Mesh.prototype.registerAfterRender = function (func) {
  32266. this.onAfterRenderObservable.add(func);
  32267. return this;
  32268. };
  32269. /**
  32270. * Disposes a previously registered javascript function called after the rendering.
  32271. * @param func defines the function to remove
  32272. * @returns the current mesh
  32273. */
  32274. Mesh.prototype.unregisterAfterRender = function (func) {
  32275. this.onAfterRenderObservable.removeCallback(func);
  32276. return this;
  32277. };
  32278. /** @hidden */
  32279. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32280. var scene = this.getScene();
  32281. this._batchCache.mustReturn = false;
  32282. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32283. this._batchCache.visibleInstances[subMeshId] = null;
  32284. if (this._visibleInstances) {
  32285. var currentRenderId = scene.getRenderId();
  32286. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32287. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32288. var selfRenderId = this._renderId;
  32289. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32290. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32291. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32292. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32293. }
  32294. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32295. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32296. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32297. this._batchCache.mustReturn = true;
  32298. return this._batchCache;
  32299. }
  32300. if (currentRenderId !== selfRenderId) {
  32301. this._batchCache.renderSelf[subMeshId] = false;
  32302. }
  32303. }
  32304. this._renderIdForInstances[subMeshId] = currentRenderId;
  32305. }
  32306. return this._batchCache;
  32307. };
  32308. /** @hidden */
  32309. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32310. var visibleInstances = batch.visibleInstances[subMesh._id];
  32311. if (!visibleInstances) {
  32312. return this;
  32313. }
  32314. var matricesCount = visibleInstances.length + 1;
  32315. var bufferSize = matricesCount * 16 * 4;
  32316. var currentInstancesBufferSize = this._instancesBufferSize;
  32317. var instancesBuffer = this._instancesBuffer;
  32318. while (this._instancesBufferSize < bufferSize) {
  32319. this._instancesBufferSize *= 2;
  32320. }
  32321. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32322. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32323. }
  32324. var offset = 0;
  32325. var instancesCount = 0;
  32326. var world = this.getWorldMatrix();
  32327. if (batch.renderSelf[subMesh._id]) {
  32328. world.copyToArray(this._instancesData, offset);
  32329. offset += 16;
  32330. instancesCount++;
  32331. }
  32332. if (visibleInstances) {
  32333. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32334. var instance = visibleInstances[instanceIndex];
  32335. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32336. offset += 16;
  32337. instancesCount++;
  32338. }
  32339. }
  32340. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32341. if (instancesBuffer) {
  32342. instancesBuffer.dispose();
  32343. }
  32344. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32345. this._instancesBuffer = instancesBuffer;
  32346. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32347. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32348. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32349. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32350. }
  32351. else {
  32352. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32353. }
  32354. this._bind(subMesh, effect, fillMode);
  32355. this._draw(subMesh, fillMode, instancesCount);
  32356. engine.unbindInstanceAttributes();
  32357. return this;
  32358. };
  32359. /** @hidden */
  32360. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32361. var scene = this.getScene();
  32362. var engine = scene.getEngine();
  32363. if (hardwareInstancedRendering) {
  32364. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32365. }
  32366. else {
  32367. if (batch.renderSelf[subMesh._id]) {
  32368. // Draw
  32369. if (onBeforeDraw) {
  32370. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32371. }
  32372. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32373. }
  32374. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32375. if (visibleInstancesForSubMesh) {
  32376. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32377. var instance = visibleInstancesForSubMesh[instanceIndex];
  32378. // World
  32379. var world = instance.getWorldMatrix();
  32380. if (onBeforeDraw) {
  32381. onBeforeDraw(true, world, effectiveMaterial);
  32382. }
  32383. // Draw
  32384. this._draw(subMesh, fillMode);
  32385. }
  32386. }
  32387. }
  32388. return this;
  32389. };
  32390. /**
  32391. * 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
  32392. * @param subMesh defines the subMesh to render
  32393. * @param enableAlphaMode defines if alpha mode can be changed
  32394. * @returns the current mesh
  32395. */
  32396. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32397. if (this._checkOcclusionQuery()) {
  32398. return this;
  32399. }
  32400. var scene = this.getScene();
  32401. // Managing instances
  32402. var batch = this._getInstancesRenderList(subMesh._id);
  32403. if (batch.mustReturn) {
  32404. return this;
  32405. }
  32406. // Checking geometry state
  32407. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32408. return this;
  32409. }
  32410. if (this._onBeforeRenderObservable) {
  32411. this._onBeforeRenderObservable.notifyObservers(this);
  32412. }
  32413. var engine = scene.getEngine();
  32414. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32415. // Material
  32416. var material = subMesh.getMaterial();
  32417. if (!material) {
  32418. return this;
  32419. }
  32420. this._effectiveMaterial = material;
  32421. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32422. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32423. return this;
  32424. }
  32425. }
  32426. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32427. return this;
  32428. }
  32429. // Alpha mode
  32430. if (enableAlphaMode) {
  32431. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32432. }
  32433. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  32434. var step = _a[_i];
  32435. step.action(this, subMesh, batch);
  32436. }
  32437. var effect;
  32438. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32439. effect = subMesh.effect;
  32440. }
  32441. else {
  32442. effect = this._effectiveMaterial.getEffect();
  32443. }
  32444. if (!effect) {
  32445. return this;
  32446. }
  32447. var sideOrientation = this.overrideMaterialSideOrientation;
  32448. if (sideOrientation == null) {
  32449. sideOrientation = this._effectiveMaterial.sideOrientation;
  32450. if (this._getWorldMatrixDeterminant() < 0) {
  32451. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32452. }
  32453. }
  32454. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32455. if (this._effectiveMaterial.forceDepthWrite) {
  32456. engine.setDepthWrite(true);
  32457. }
  32458. // Bind
  32459. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32460. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32461. this._bind(subMesh, effect, fillMode);
  32462. }
  32463. var world = this.getWorldMatrix();
  32464. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32465. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32466. }
  32467. else {
  32468. this._effectiveMaterial.bind(world, this);
  32469. }
  32470. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32471. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32472. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32473. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32474. }
  32475. // Draw
  32476. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32477. // Unbind
  32478. this._effectiveMaterial.unbind();
  32479. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  32480. var step = _c[_b];
  32481. step.action(this, subMesh, batch);
  32482. }
  32483. if (this._onAfterRenderObservable) {
  32484. this._onAfterRenderObservable.notifyObservers(this);
  32485. }
  32486. return this;
  32487. };
  32488. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32489. if (isInstance && effectiveMaterial) {
  32490. effectiveMaterial.bindOnlyWorldMatrix(world);
  32491. }
  32492. };
  32493. /**
  32494. * Normalize matrix weights so that all vertices have a total weight set to 1
  32495. */
  32496. Mesh.prototype.cleanMatrixWeights = function () {
  32497. var epsilon = 1e-3;
  32498. var noInfluenceBoneIndex = 0.0;
  32499. if (this.skeleton) {
  32500. noInfluenceBoneIndex = this.skeleton.bones.length;
  32501. }
  32502. else {
  32503. return;
  32504. }
  32505. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32506. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32507. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32508. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32509. var influencers = this.numBoneInfluencers;
  32510. var size = matricesWeights.length;
  32511. for (var i = 0; i < size; i += 4) {
  32512. var weight = 0.0;
  32513. var firstZeroWeight = -1;
  32514. for (var j = 0; j < 4; j++) {
  32515. var w = matricesWeights[i + j];
  32516. weight += w;
  32517. if (w < epsilon && firstZeroWeight < 0) {
  32518. firstZeroWeight = j;
  32519. }
  32520. }
  32521. if (matricesWeightsExtra) {
  32522. for (var j = 0; j < 4; j++) {
  32523. var w = matricesWeightsExtra[i + j];
  32524. weight += w;
  32525. if (w < epsilon && firstZeroWeight < 0) {
  32526. firstZeroWeight = j + 4;
  32527. }
  32528. }
  32529. }
  32530. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32531. firstZeroWeight = influencers - 1;
  32532. }
  32533. if (weight > epsilon) {
  32534. var mweight = 1.0 / weight;
  32535. for (var j = 0; j < 4; j++) {
  32536. matricesWeights[i + j] *= mweight;
  32537. }
  32538. if (matricesWeightsExtra) {
  32539. for (var j = 0; j < 4; j++) {
  32540. matricesWeightsExtra[i + j] *= mweight;
  32541. }
  32542. }
  32543. }
  32544. else {
  32545. if (firstZeroWeight >= 4) {
  32546. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32547. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32548. }
  32549. else {
  32550. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32551. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32552. }
  32553. }
  32554. }
  32555. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32556. if (matricesIndicesExtra) {
  32557. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32558. }
  32559. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32560. if (matricesWeightsExtra) {
  32561. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32562. }
  32563. };
  32564. /** @hidden */
  32565. Mesh.prototype._checkDelayState = function () {
  32566. var scene = this.getScene();
  32567. if (this._geometry) {
  32568. this._geometry.load(scene);
  32569. }
  32570. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32571. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32572. this._queueLoad(scene);
  32573. }
  32574. return this;
  32575. };
  32576. Mesh.prototype._queueLoad = function (scene) {
  32577. var _this = this;
  32578. scene._addPendingData(this);
  32579. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32580. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32581. if (data instanceof ArrayBuffer) {
  32582. _this._delayLoadingFunction(data, _this);
  32583. }
  32584. else {
  32585. _this._delayLoadingFunction(JSON.parse(data), _this);
  32586. }
  32587. _this.instances.forEach(function (instance) {
  32588. instance._syncSubMeshes();
  32589. });
  32590. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32591. scene._removePendingData(_this);
  32592. }, function () { }, scene.database, getBinaryData);
  32593. return this;
  32594. };
  32595. /**
  32596. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32597. * A mesh is in the frustum if its bounding box intersects the frustum
  32598. * @param frustumPlanes defines the frustum to test
  32599. * @returns true if the mesh is in the frustum planes
  32600. */
  32601. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32602. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32603. return false;
  32604. }
  32605. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32606. return false;
  32607. }
  32608. this._checkDelayState();
  32609. return true;
  32610. };
  32611. /**
  32612. * Sets the mesh material by the material or multiMaterial `id` property
  32613. * @param id is a string identifying the material or the multiMaterial
  32614. * @returns the current mesh
  32615. */
  32616. Mesh.prototype.setMaterialByID = function (id) {
  32617. var materials = this.getScene().materials;
  32618. var index;
  32619. for (index = materials.length - 1; index > -1; index--) {
  32620. if (materials[index].id === id) {
  32621. this.material = materials[index];
  32622. return this;
  32623. }
  32624. }
  32625. // Multi
  32626. var multiMaterials = this.getScene().multiMaterials;
  32627. for (index = multiMaterials.length - 1; index > -1; index--) {
  32628. if (multiMaterials[index].id === id) {
  32629. this.material = multiMaterials[index];
  32630. return this;
  32631. }
  32632. }
  32633. return this;
  32634. };
  32635. /**
  32636. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32637. * @returns an array of IAnimatable
  32638. */
  32639. Mesh.prototype.getAnimatables = function () {
  32640. var results = new Array();
  32641. if (this.material) {
  32642. results.push(this.material);
  32643. }
  32644. if (this.skeleton) {
  32645. results.push(this.skeleton);
  32646. }
  32647. return results;
  32648. };
  32649. /**
  32650. * Modifies the mesh geometry according to the passed transformation matrix.
  32651. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32652. * The mesh normals are modified using the same transformation.
  32653. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32654. * @param transform defines the transform matrix to use
  32655. * @see http://doc.babylonjs.com/resources/baking_transformations
  32656. * @returns the current mesh
  32657. */
  32658. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32659. // Position
  32660. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32661. return this;
  32662. }
  32663. var submeshes = this.subMeshes.splice(0);
  32664. this._resetPointsArrayCache();
  32665. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32666. var temp = new Array();
  32667. var index;
  32668. for (index = 0; index < data.length; index += 3) {
  32669. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32670. }
  32671. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32672. // Normals
  32673. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32674. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32675. temp = [];
  32676. for (index = 0; index < data.length; index += 3) {
  32677. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32678. }
  32679. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32680. }
  32681. // flip faces?
  32682. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32683. this.flipFaces();
  32684. }
  32685. // Restore submeshes
  32686. this.releaseSubMeshes();
  32687. this.subMeshes = submeshes;
  32688. return this;
  32689. };
  32690. /**
  32691. * Modifies the mesh geometry according to its own current World Matrix.
  32692. * The mesh World Matrix is then reset.
  32693. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32694. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32695. * @see http://doc.babylonjs.com/resources/baking_transformations
  32696. * @returns the current mesh
  32697. */
  32698. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32699. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32700. this.scaling.copyFromFloats(1, 1, 1);
  32701. this.position.copyFromFloats(0, 0, 0);
  32702. this.rotation.copyFromFloats(0, 0, 0);
  32703. //only if quaternion is already set
  32704. if (this.rotationQuaternion) {
  32705. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32706. }
  32707. this._worldMatrix = BABYLON.Matrix.Identity();
  32708. return this;
  32709. };
  32710. Object.defineProperty(Mesh.prototype, "_positions", {
  32711. // Cache
  32712. /** @hidden */
  32713. get: function () {
  32714. if (this._geometry) {
  32715. return this._geometry._positions;
  32716. }
  32717. return null;
  32718. },
  32719. enumerable: true,
  32720. configurable: true
  32721. });
  32722. /** @hidden */
  32723. Mesh.prototype._resetPointsArrayCache = function () {
  32724. if (this._geometry) {
  32725. this._geometry._resetPointsArrayCache();
  32726. }
  32727. return this;
  32728. };
  32729. /** @hidden */
  32730. Mesh.prototype._generatePointsArray = function () {
  32731. if (this._geometry) {
  32732. return this._geometry._generatePointsArray();
  32733. }
  32734. return false;
  32735. };
  32736. /**
  32737. * Returns a new Mesh object generated from the current mesh properties.
  32738. * This method must not get confused with createInstance()
  32739. * @param name is a string, the name given to the new mesh
  32740. * @param newParent can be any Node object (default `null`)
  32741. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  32742. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  32743. * @returns a new mesh
  32744. */
  32745. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32746. if (name === void 0) { name = ""; }
  32747. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32748. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32749. };
  32750. /**
  32751. * Releases resources associated with this mesh.
  32752. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32753. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32754. */
  32755. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32756. var _this = this;
  32757. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32758. this.morphTargetManager = null;
  32759. if (this._geometry) {
  32760. this._geometry.releaseForMesh(this, true);
  32761. }
  32762. if (this._onBeforeDrawObservable) {
  32763. this._onBeforeDrawObservable.clear();
  32764. }
  32765. if (this._onBeforeRenderObservable) {
  32766. this._onBeforeRenderObservable.clear();
  32767. }
  32768. if (this._onAfterRenderObservable) {
  32769. this._onAfterRenderObservable.clear();
  32770. }
  32771. // Sources
  32772. var meshes = this.getScene().meshes;
  32773. meshes.forEach(function (abstractMesh) {
  32774. var mesh = abstractMesh;
  32775. if (mesh._source && mesh._source === _this) {
  32776. mesh._source = null;
  32777. }
  32778. });
  32779. this._source = null;
  32780. // Instances
  32781. if (this._instancesBuffer) {
  32782. this._instancesBuffer.dispose();
  32783. this._instancesBuffer = null;
  32784. }
  32785. while (this.instances.length) {
  32786. this.instances[0].dispose();
  32787. }
  32788. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32789. };
  32790. /**
  32791. * Modifies the mesh geometry according to a displacement map.
  32792. * 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.
  32793. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32794. * @param url is a string, the URL from the image file is to be downloaded.
  32795. * @param minHeight is the lower limit of the displacement.
  32796. * @param maxHeight is the upper limit of the displacement.
  32797. * @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.
  32798. * @param uvOffset is an optional vector2 used to offset UV.
  32799. * @param uvScale is an optional vector2 used to scale UV.
  32800. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  32801. * @returns the Mesh.
  32802. */
  32803. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32804. var _this = this;
  32805. if (forceUpdate === void 0) { forceUpdate = false; }
  32806. var scene = this.getScene();
  32807. var onload = function (img) {
  32808. // Getting height map data
  32809. var canvas = document.createElement("canvas");
  32810. var context = canvas.getContext("2d");
  32811. var heightMapWidth = img.width;
  32812. var heightMapHeight = img.height;
  32813. canvas.width = heightMapWidth;
  32814. canvas.height = heightMapHeight;
  32815. context.drawImage(img, 0, 0);
  32816. // Create VertexData from map data
  32817. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32818. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32819. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32820. //execute success callback, if set
  32821. if (onSuccess) {
  32822. onSuccess(_this);
  32823. }
  32824. };
  32825. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32826. return this;
  32827. };
  32828. /**
  32829. * Modifies the mesh geometry according to a displacementMap buffer.
  32830. * 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.
  32831. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32832. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32833. * @param heightMapWidth is the width of the buffer image.
  32834. * @param heightMapHeight is the height of the buffer image.
  32835. * @param minHeight is the lower limit of the displacement.
  32836. * @param maxHeight is the upper limit of the displacement.
  32837. * @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.
  32838. * @param uvOffset is an optional vector2 used to offset UV.
  32839. * @param uvScale is an optional vector2 used to scale UV.
  32840. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  32841. * @returns the Mesh.
  32842. */
  32843. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32844. if (forceUpdate === void 0) { forceUpdate = false; }
  32845. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32846. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32847. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32848. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32849. return this;
  32850. }
  32851. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32852. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32853. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32854. var position = BABYLON.Vector3.Zero();
  32855. var normal = BABYLON.Vector3.Zero();
  32856. var uv = BABYLON.Vector2.Zero();
  32857. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32858. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32859. for (var index = 0; index < positions.length; index += 3) {
  32860. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32861. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32862. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32863. // Compute height
  32864. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32865. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32866. var pos = (u + v * heightMapWidth) * 4;
  32867. var r = buffer[pos] / 255.0;
  32868. var g = buffer[pos + 1] / 255.0;
  32869. var b = buffer[pos + 2] / 255.0;
  32870. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32871. normal.normalize();
  32872. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32873. position = position.add(normal);
  32874. position.toArray(positions, index);
  32875. }
  32876. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32877. if (forceUpdate) {
  32878. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32879. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32880. }
  32881. else {
  32882. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32883. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32884. }
  32885. return this;
  32886. };
  32887. /**
  32888. * Modify the mesh to get a flat shading rendering.
  32889. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32890. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32891. * @returns current mesh
  32892. */
  32893. Mesh.prototype.convertToFlatShadedMesh = function () {
  32894. var kinds = this.getVerticesDataKinds();
  32895. var vbs = {};
  32896. var data = {};
  32897. var newdata = {};
  32898. var updatableNormals = false;
  32899. var kindIndex;
  32900. var kind;
  32901. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32902. kind = kinds[kindIndex];
  32903. var vertexBuffer = this.getVertexBuffer(kind);
  32904. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32905. updatableNormals = vertexBuffer.isUpdatable();
  32906. kinds.splice(kindIndex, 1);
  32907. kindIndex--;
  32908. continue;
  32909. }
  32910. vbs[kind] = vertexBuffer;
  32911. data[kind] = vbs[kind].getData();
  32912. newdata[kind] = [];
  32913. }
  32914. // Save previous submeshes
  32915. var previousSubmeshes = this.subMeshes.slice(0);
  32916. var indices = this.getIndices();
  32917. var totalIndices = this.getTotalIndices();
  32918. // Generating unique vertices per face
  32919. var index;
  32920. for (index = 0; index < totalIndices; index++) {
  32921. var vertexIndex = indices[index];
  32922. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32923. kind = kinds[kindIndex];
  32924. var stride = vbs[kind].getStrideSize();
  32925. for (var offset = 0; offset < stride; offset++) {
  32926. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32927. }
  32928. }
  32929. }
  32930. // Updating faces & normal
  32931. var normals = [];
  32932. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32933. for (index = 0; index < totalIndices; index += 3) {
  32934. indices[index] = index;
  32935. indices[index + 1] = index + 1;
  32936. indices[index + 2] = index + 2;
  32937. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32938. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32939. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32940. var p1p2 = p1.subtract(p2);
  32941. var p3p2 = p3.subtract(p2);
  32942. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32943. // Store same normals for every vertex
  32944. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32945. normals.push(normal.x);
  32946. normals.push(normal.y);
  32947. normals.push(normal.z);
  32948. }
  32949. }
  32950. this.setIndices(indices);
  32951. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32952. // Updating vertex buffers
  32953. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32954. kind = kinds[kindIndex];
  32955. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32956. }
  32957. // Updating submeshes
  32958. this.releaseSubMeshes();
  32959. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32960. var previousOne = previousSubmeshes[submeshIndex];
  32961. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32962. }
  32963. this.synchronizeInstances();
  32964. return this;
  32965. };
  32966. /**
  32967. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32968. * In other words, more vertices, no more indices and a single bigger VBO.
  32969. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32970. * @returns current mesh
  32971. */
  32972. Mesh.prototype.convertToUnIndexedMesh = function () {
  32973. var kinds = this.getVerticesDataKinds();
  32974. var vbs = {};
  32975. var data = {};
  32976. var newdata = {};
  32977. var kindIndex;
  32978. var kind;
  32979. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32980. kind = kinds[kindIndex];
  32981. var vertexBuffer = this.getVertexBuffer(kind);
  32982. vbs[kind] = vertexBuffer;
  32983. data[kind] = vbs[kind].getData();
  32984. newdata[kind] = [];
  32985. }
  32986. // Save previous submeshes
  32987. var previousSubmeshes = this.subMeshes.slice(0);
  32988. var indices = this.getIndices();
  32989. var totalIndices = this.getTotalIndices();
  32990. // Generating unique vertices per face
  32991. var index;
  32992. for (index = 0; index < totalIndices; index++) {
  32993. var vertexIndex = indices[index];
  32994. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32995. kind = kinds[kindIndex];
  32996. var stride = vbs[kind].getStrideSize();
  32997. for (var offset = 0; offset < stride; offset++) {
  32998. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32999. }
  33000. }
  33001. }
  33002. // Updating indices
  33003. for (index = 0; index < totalIndices; index += 3) {
  33004. indices[index] = index;
  33005. indices[index + 1] = index + 1;
  33006. indices[index + 2] = index + 2;
  33007. }
  33008. this.setIndices(indices);
  33009. // Updating vertex buffers
  33010. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33011. kind = kinds[kindIndex];
  33012. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33013. }
  33014. // Updating submeshes
  33015. this.releaseSubMeshes();
  33016. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33017. var previousOne = previousSubmeshes[submeshIndex];
  33018. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33019. }
  33020. this._unIndexed = true;
  33021. this.synchronizeInstances();
  33022. return this;
  33023. };
  33024. /**
  33025. * Inverses facet orientations.
  33026. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33027. * @param flipNormals will also inverts the normals
  33028. * @returns current mesh
  33029. */
  33030. Mesh.prototype.flipFaces = function (flipNormals) {
  33031. if (flipNormals === void 0) { flipNormals = false; }
  33032. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33033. var i;
  33034. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33035. for (i = 0; i < vertex_data.normals.length; i++) {
  33036. vertex_data.normals[i] *= -1;
  33037. }
  33038. }
  33039. if (vertex_data.indices) {
  33040. var temp;
  33041. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33042. // reassign indices
  33043. temp = vertex_data.indices[i + 1];
  33044. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33045. vertex_data.indices[i + 2] = temp;
  33046. }
  33047. }
  33048. vertex_data.applyToMesh(this);
  33049. return this;
  33050. };
  33051. // Instances
  33052. /**
  33053. * Creates a new InstancedMesh object from the mesh model.
  33054. * Warning : this method is not supported for Line mesh and LineSystem
  33055. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  33056. * @param name defines the name of the new instance
  33057. * @returns a new InstancedMesh
  33058. */
  33059. Mesh.prototype.createInstance = function (name) {
  33060. return new BABYLON.InstancedMesh(name, this);
  33061. };
  33062. /**
  33063. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33064. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33065. * @returns the current mesh
  33066. */
  33067. Mesh.prototype.synchronizeInstances = function () {
  33068. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33069. var instance = this.instances[instanceIndex];
  33070. instance._syncSubMeshes();
  33071. }
  33072. return this;
  33073. };
  33074. /**
  33075. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33076. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33077. * This should be used together with the simplification to avoid disappearing triangles.
  33078. * @param successCallback an optional success callback to be called after the optimization finished.
  33079. * @returns the current mesh
  33080. */
  33081. Mesh.prototype.optimizeIndices = function (successCallback) {
  33082. var _this = this;
  33083. var indices = this.getIndices();
  33084. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33085. if (!positions || !indices) {
  33086. return this;
  33087. }
  33088. var vectorPositions = new Array();
  33089. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33090. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33091. }
  33092. var dupes = new Array();
  33093. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33094. var realPos = vectorPositions.length - 1 - iteration;
  33095. var testedPosition = vectorPositions[realPos];
  33096. for (var j = 0; j < realPos; ++j) {
  33097. var againstPosition = vectorPositions[j];
  33098. if (testedPosition.equals(againstPosition)) {
  33099. dupes[realPos] = j;
  33100. break;
  33101. }
  33102. }
  33103. }, function () {
  33104. for (var i = 0; i < indices.length; ++i) {
  33105. indices[i] = dupes[indices[i]] || indices[i];
  33106. }
  33107. //indices are now reordered
  33108. var originalSubMeshes = _this.subMeshes.slice(0);
  33109. _this.setIndices(indices);
  33110. _this.subMeshes = originalSubMeshes;
  33111. if (successCallback) {
  33112. successCallback(_this);
  33113. }
  33114. });
  33115. return this;
  33116. };
  33117. /**
  33118. * Serialize current mesh
  33119. * @param serializationObject defines the object which will receive the serialization data
  33120. */
  33121. Mesh.prototype.serialize = function (serializationObject) {
  33122. serializationObject.name = this.name;
  33123. serializationObject.id = this.id;
  33124. serializationObject.type = this.getClassName();
  33125. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33126. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33127. }
  33128. serializationObject.position = this.position.asArray();
  33129. if (this.rotationQuaternion) {
  33130. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33131. }
  33132. else if (this.rotation) {
  33133. serializationObject.rotation = this.rotation.asArray();
  33134. }
  33135. serializationObject.scaling = this.scaling.asArray();
  33136. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33137. serializationObject.isEnabled = this.isEnabled(false);
  33138. serializationObject.isVisible = this.isVisible;
  33139. serializationObject.infiniteDistance = this.infiniteDistance;
  33140. serializationObject.pickable = this.isPickable;
  33141. serializationObject.receiveShadows = this.receiveShadows;
  33142. serializationObject.billboardMode = this.billboardMode;
  33143. serializationObject.visibility = this.visibility;
  33144. serializationObject.checkCollisions = this.checkCollisions;
  33145. serializationObject.isBlocker = this.isBlocker;
  33146. // Parent
  33147. if (this.parent) {
  33148. serializationObject.parentId = this.parent.id;
  33149. }
  33150. // Geometry
  33151. serializationObject.isUnIndexed = this.isUnIndexed;
  33152. var geometry = this._geometry;
  33153. if (geometry) {
  33154. var geometryId = geometry.id;
  33155. serializationObject.geometryId = geometryId;
  33156. // SubMeshes
  33157. serializationObject.subMeshes = [];
  33158. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33159. var subMesh = this.subMeshes[subIndex];
  33160. serializationObject.subMeshes.push({
  33161. materialIndex: subMesh.materialIndex,
  33162. verticesStart: subMesh.verticesStart,
  33163. verticesCount: subMesh.verticesCount,
  33164. indexStart: subMesh.indexStart,
  33165. indexCount: subMesh.indexCount
  33166. });
  33167. }
  33168. }
  33169. // Material
  33170. if (this.material) {
  33171. serializationObject.materialId = this.material.id;
  33172. }
  33173. else {
  33174. this.material = null;
  33175. }
  33176. // Morph targets
  33177. if (this.morphTargetManager) {
  33178. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33179. }
  33180. // Skeleton
  33181. if (this.skeleton) {
  33182. serializationObject.skeletonId = this.skeleton.id;
  33183. }
  33184. // Physics
  33185. //TODO implement correct serialization for physics impostors.
  33186. var impostor = this.getPhysicsImpostor();
  33187. if (impostor) {
  33188. serializationObject.physicsMass = impostor.getParam("mass");
  33189. serializationObject.physicsFriction = impostor.getParam("friction");
  33190. serializationObject.physicsRestitution = impostor.getParam("mass");
  33191. serializationObject.physicsImpostor = impostor.type;
  33192. }
  33193. // Metadata
  33194. if (this.metadata) {
  33195. serializationObject.metadata = this.metadata;
  33196. }
  33197. // Instances
  33198. serializationObject.instances = [];
  33199. for (var index = 0; index < this.instances.length; index++) {
  33200. var instance = this.instances[index];
  33201. if (instance.doNotSerialize) {
  33202. continue;
  33203. }
  33204. var serializationInstance = {
  33205. name: instance.name,
  33206. id: instance.id,
  33207. position: instance.position.asArray(),
  33208. scaling: instance.scaling.asArray()
  33209. };
  33210. if (instance.parent) {
  33211. serializationInstance.parentId = instance.parent.id;
  33212. }
  33213. if (instance.rotationQuaternion) {
  33214. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33215. }
  33216. else if (instance.rotation) {
  33217. serializationInstance.rotation = instance.rotation.asArray();
  33218. }
  33219. serializationObject.instances.push(serializationInstance);
  33220. // Animations
  33221. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33222. serializationInstance.ranges = instance.serializeAnimationRanges();
  33223. }
  33224. //
  33225. // Animations
  33226. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33227. serializationObject.ranges = this.serializeAnimationRanges();
  33228. // Layer mask
  33229. serializationObject.layerMask = this.layerMask;
  33230. // Alpha
  33231. serializationObject.alphaIndex = this.alphaIndex;
  33232. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33233. // Overlay
  33234. serializationObject.overlayAlpha = this.overlayAlpha;
  33235. serializationObject.overlayColor = this.overlayColor.asArray();
  33236. serializationObject.renderOverlay = this.renderOverlay;
  33237. // Fog
  33238. serializationObject.applyFog = this.applyFog;
  33239. // Action Manager
  33240. if (this.actionManager) {
  33241. serializationObject.actions = this.actionManager.serialize(this.name);
  33242. }
  33243. };
  33244. /** @hidden */
  33245. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33246. if (!this.geometry) {
  33247. return;
  33248. }
  33249. this._markSubMeshesAsAttributesDirty();
  33250. var morphTargetManager = this._morphTargetManager;
  33251. if (morphTargetManager && morphTargetManager.vertexCount) {
  33252. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33253. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33254. this.morphTargetManager = null;
  33255. return;
  33256. }
  33257. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33258. var morphTarget = morphTargetManager.getActiveTarget(index);
  33259. var positions = morphTarget.getPositions();
  33260. if (!positions) {
  33261. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33262. return;
  33263. }
  33264. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33265. var normals = morphTarget.getNormals();
  33266. if (normals) {
  33267. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33268. }
  33269. var tangents = morphTarget.getTangents();
  33270. if (tangents) {
  33271. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33272. }
  33273. }
  33274. }
  33275. else {
  33276. var index = 0;
  33277. // Positions
  33278. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33279. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33280. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33281. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33282. }
  33283. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33284. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33285. }
  33286. index++;
  33287. }
  33288. }
  33289. };
  33290. // Statics
  33291. /**
  33292. * Returns a new Mesh object parsed from the source provided.
  33293. * @param parsedMesh is the source
  33294. * @param scene defines the hosting scene
  33295. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  33296. * @returns a new Mesh
  33297. */
  33298. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33299. var mesh;
  33300. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33301. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33302. }
  33303. else {
  33304. mesh = new Mesh(parsedMesh.name, scene);
  33305. }
  33306. mesh.id = parsedMesh.id;
  33307. if (BABYLON.Tags) {
  33308. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33309. }
  33310. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33311. if (parsedMesh.metadata !== undefined) {
  33312. mesh.metadata = parsedMesh.metadata;
  33313. }
  33314. if (parsedMesh.rotationQuaternion) {
  33315. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33316. }
  33317. else if (parsedMesh.rotation) {
  33318. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33319. }
  33320. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33321. if (parsedMesh.localMatrix) {
  33322. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33323. }
  33324. else if (parsedMesh.pivotMatrix) {
  33325. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33326. }
  33327. mesh.setEnabled(parsedMesh.isEnabled);
  33328. mesh.isVisible = parsedMesh.isVisible;
  33329. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33330. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33331. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33332. if (parsedMesh.applyFog !== undefined) {
  33333. mesh.applyFog = parsedMesh.applyFog;
  33334. }
  33335. if (parsedMesh.pickable !== undefined) {
  33336. mesh.isPickable = parsedMesh.pickable;
  33337. }
  33338. if (parsedMesh.alphaIndex !== undefined) {
  33339. mesh.alphaIndex = parsedMesh.alphaIndex;
  33340. }
  33341. mesh.receiveShadows = parsedMesh.receiveShadows;
  33342. mesh.billboardMode = parsedMesh.billboardMode;
  33343. if (parsedMesh.visibility !== undefined) {
  33344. mesh.visibility = parsedMesh.visibility;
  33345. }
  33346. mesh.checkCollisions = parsedMesh.checkCollisions;
  33347. if (parsedMesh.isBlocker !== undefined) {
  33348. mesh.isBlocker = parsedMesh.isBlocker;
  33349. }
  33350. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33351. // freezeWorldMatrix
  33352. if (parsedMesh.freezeWorldMatrix) {
  33353. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33354. }
  33355. // Parent
  33356. if (parsedMesh.parentId) {
  33357. mesh._waitingParentId = parsedMesh.parentId;
  33358. }
  33359. // Actions
  33360. if (parsedMesh.actions !== undefined) {
  33361. mesh._waitingActions = parsedMesh.actions;
  33362. }
  33363. // Overlay
  33364. if (parsedMesh.overlayAlpha !== undefined) {
  33365. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33366. }
  33367. if (parsedMesh.overlayColor !== undefined) {
  33368. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33369. }
  33370. if (parsedMesh.renderOverlay !== undefined) {
  33371. mesh.renderOverlay = parsedMesh.renderOverlay;
  33372. }
  33373. // Geometry
  33374. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33375. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33376. if (parsedMesh.delayLoadingFile) {
  33377. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33378. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33379. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33380. if (parsedMesh._binaryInfo) {
  33381. mesh._binaryInfo = parsedMesh._binaryInfo;
  33382. }
  33383. mesh._delayInfo = [];
  33384. if (parsedMesh.hasUVs) {
  33385. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33386. }
  33387. if (parsedMesh.hasUVs2) {
  33388. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33389. }
  33390. if (parsedMesh.hasUVs3) {
  33391. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33392. }
  33393. if (parsedMesh.hasUVs4) {
  33394. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33395. }
  33396. if (parsedMesh.hasUVs5) {
  33397. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33398. }
  33399. if (parsedMesh.hasUVs6) {
  33400. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33401. }
  33402. if (parsedMesh.hasColors) {
  33403. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33404. }
  33405. if (parsedMesh.hasMatricesIndices) {
  33406. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33407. }
  33408. if (parsedMesh.hasMatricesWeights) {
  33409. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33410. }
  33411. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33412. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33413. mesh._checkDelayState();
  33414. }
  33415. }
  33416. else {
  33417. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33418. }
  33419. // Material
  33420. if (parsedMesh.materialId) {
  33421. mesh.setMaterialByID(parsedMesh.materialId);
  33422. }
  33423. else {
  33424. mesh.material = null;
  33425. }
  33426. // Morph targets
  33427. if (parsedMesh.morphTargetManagerId > -1) {
  33428. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33429. }
  33430. // Skeleton
  33431. if (parsedMesh.skeletonId > -1) {
  33432. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33433. if (parsedMesh.numBoneInfluencers) {
  33434. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33435. }
  33436. }
  33437. // Animations
  33438. if (parsedMesh.animations) {
  33439. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33440. var parsedAnimation = parsedMesh.animations[animationIndex];
  33441. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33442. }
  33443. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33444. }
  33445. if (parsedMesh.autoAnimate) {
  33446. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33447. }
  33448. // Layer Mask
  33449. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33450. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33451. }
  33452. else {
  33453. mesh.layerMask = 0x0FFFFFFF;
  33454. }
  33455. // Physics
  33456. if (parsedMesh.physicsImpostor) {
  33457. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33458. mass: parsedMesh.physicsMass,
  33459. friction: parsedMesh.physicsFriction,
  33460. restitution: parsedMesh.physicsRestitution
  33461. }, scene);
  33462. }
  33463. // Instances
  33464. if (parsedMesh.instances) {
  33465. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33466. var parsedInstance = parsedMesh.instances[index];
  33467. var instance = mesh.createInstance(parsedInstance.name);
  33468. if (parsedInstance.id) {
  33469. instance.id = parsedInstance.id;
  33470. }
  33471. if (BABYLON.Tags) {
  33472. if (parsedInstance.tags) {
  33473. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33474. }
  33475. else {
  33476. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  33477. }
  33478. }
  33479. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33480. if (parsedInstance.parentId) {
  33481. instance._waitingParentId = parsedInstance.parentId;
  33482. }
  33483. if (parsedInstance.rotationQuaternion) {
  33484. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33485. }
  33486. else if (parsedInstance.rotation) {
  33487. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33488. }
  33489. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33490. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  33491. instance.checkCollisions = parsedInstance.checkCollisions;
  33492. }
  33493. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  33494. instance.isPickable = parsedInstance.pickable;
  33495. }
  33496. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  33497. instance.showBoundingBox = parsedInstance.showBoundingBox;
  33498. }
  33499. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33500. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  33501. }
  33502. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33503. instance.alphaIndex = parsedInstance.alphaIndex;
  33504. }
  33505. // Physics
  33506. if (parsedInstance.physicsImpostor) {
  33507. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  33508. mass: parsedInstance.physicsMass,
  33509. friction: parsedInstance.physicsFriction,
  33510. restitution: parsedInstance.physicsRestitution
  33511. }, scene);
  33512. }
  33513. // Animation
  33514. if (parsedInstance.animations) {
  33515. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  33516. parsedAnimation = parsedInstance.animations[animationIndex];
  33517. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33518. }
  33519. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  33520. if (parsedInstance.autoAnimate) {
  33521. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  33522. }
  33523. }
  33524. }
  33525. }
  33526. return mesh;
  33527. };
  33528. /**
  33529. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  33530. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33531. * @param name defines the name of the mesh to create
  33532. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33533. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  33534. * @param closePath creates a seam between the first and the last points of each path of the path array
  33535. * @param offset is taken in account only if the `pathArray` is containing a single path
  33536. * @param scene defines the hosting scene
  33537. * @param updatable defines if the mesh must be flagged as updatable
  33538. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33539. * @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)
  33540. * @returns a new Mesh
  33541. */
  33542. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33543. if (closeArray === void 0) { closeArray = false; }
  33544. if (updatable === void 0) { updatable = false; }
  33545. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33546. pathArray: pathArray,
  33547. closeArray: closeArray,
  33548. closePath: closePath,
  33549. offset: offset,
  33550. updatable: updatable,
  33551. sideOrientation: sideOrientation,
  33552. instance: instance
  33553. }, scene);
  33554. };
  33555. /**
  33556. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  33557. * @param name defines the name of the mesh to create
  33558. * @param radius sets the radius size (float) of the polygon (default 0.5)
  33559. * @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
  33560. * @param scene defines the hosting scene
  33561. * @param updatable defines if the mesh must be flagged as updatable
  33562. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33563. * @returns a new Mesh
  33564. */
  33565. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33566. if (scene === void 0) { scene = null; }
  33567. var options = {
  33568. radius: radius,
  33569. tessellation: tessellation,
  33570. sideOrientation: sideOrientation,
  33571. updatable: updatable
  33572. };
  33573. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33574. };
  33575. /**
  33576. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  33577. * @param name defines the name of the mesh to create
  33578. * @param size sets the size (float) of each box side (default 1)
  33579. * @param scene defines the hosting scene
  33580. * @param updatable defines if the mesh must be flagged as updatable
  33581. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33582. * @returns a new Mesh
  33583. */
  33584. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33585. if (scene === void 0) { scene = null; }
  33586. var options = {
  33587. size: size,
  33588. sideOrientation: sideOrientation,
  33589. updatable: updatable
  33590. };
  33591. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33592. };
  33593. /**
  33594. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  33595. * @param name defines the name of the mesh to create
  33596. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  33597. * @param diameter sets the diameter size (float) of the sphere (default 1)
  33598. * @param scene defines the hosting scene
  33599. * @param updatable defines if the mesh must be flagged as updatable
  33600. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33601. * @returns a new Mesh
  33602. */
  33603. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33604. var options = {
  33605. segments: segments,
  33606. diameterX: diameter,
  33607. diameterY: diameter,
  33608. diameterZ: diameter,
  33609. sideOrientation: sideOrientation,
  33610. updatable: updatable
  33611. };
  33612. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33613. };
  33614. /**
  33615. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  33616. * @param name defines the name of the mesh to create
  33617. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  33618. * @param diameterTop set the top cap diameter (floats, default 1)
  33619. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  33620. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  33621. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  33622. * @param scene defines the hosting scene
  33623. * @param updatable defines if the mesh must be flagged as updatable
  33624. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33625. * @returns a new Mesh
  33626. */
  33627. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33628. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33629. if (scene !== undefined) {
  33630. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33631. updatable = scene;
  33632. }
  33633. scene = subdivisions;
  33634. subdivisions = 1;
  33635. }
  33636. var options = {
  33637. height: height,
  33638. diameterTop: diameterTop,
  33639. diameterBottom: diameterBottom,
  33640. tessellation: tessellation,
  33641. subdivisions: subdivisions,
  33642. sideOrientation: sideOrientation,
  33643. updatable: updatable
  33644. };
  33645. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33646. };
  33647. // Torus (Code from SharpDX.org)
  33648. /**
  33649. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  33650. * @param name defines the name of the mesh to create
  33651. * @param diameter sets the diameter size (float) of the torus (default 1)
  33652. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  33653. * @param tessellation sets the number of torus sides (postive integer, default 16)
  33654. * @param scene defines the hosting scene
  33655. * @param updatable defines if the mesh must be flagged as updatable
  33656. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33657. * @returns a new Mesh
  33658. */
  33659. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33660. var options = {
  33661. diameter: diameter,
  33662. thickness: thickness,
  33663. tessellation: tessellation,
  33664. sideOrientation: sideOrientation,
  33665. updatable: updatable
  33666. };
  33667. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33668. };
  33669. /**
  33670. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  33671. * @param name defines the name of the mesh to create
  33672. * @param radius sets the global radius size (float) of the torus knot (default 2)
  33673. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  33674. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  33675. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  33676. * @param p the number of windings on X axis (positive integers, default 2)
  33677. * @param q the number of windings on Y axis (positive integers, default 3)
  33678. * @param scene defines the hosting scene
  33679. * @param updatable defines if the mesh must be flagged as updatable
  33680. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33681. * @returns a new Mesh
  33682. */
  33683. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33684. var options = {
  33685. radius: radius,
  33686. tube: tube,
  33687. radialSegments: radialSegments,
  33688. tubularSegments: tubularSegments,
  33689. p: p,
  33690. q: q,
  33691. sideOrientation: sideOrientation,
  33692. updatable: updatable
  33693. };
  33694. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33695. };
  33696. /**
  33697. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  33698. * @param name defines the name of the mesh to create
  33699. * @param points is an array successive Vector3
  33700. * @param scene defines the hosting scene
  33701. * @param updatable defines if the mesh must be flagged as updatable
  33702. * @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).
  33703. * @returns a new Mesh
  33704. */
  33705. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33706. if (scene === void 0) { scene = null; }
  33707. if (updatable === void 0) { updatable = false; }
  33708. if (instance === void 0) { instance = null; }
  33709. var options = {
  33710. points: points,
  33711. updatable: updatable,
  33712. instance: instance
  33713. };
  33714. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33715. };
  33716. /**
  33717. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  33718. * @param name defines the name of the mesh to create
  33719. * @param points is an array successive Vector3
  33720. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  33721. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  33722. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  33723. * @param scene defines the hosting scene
  33724. * @param updatable defines if the mesh must be flagged as updatable
  33725. * @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)
  33726. * @returns a new Mesh
  33727. */
  33728. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33729. if (scene === void 0) { scene = null; }
  33730. var options = {
  33731. points: points,
  33732. dashSize: dashSize,
  33733. gapSize: gapSize,
  33734. dashNb: dashNb,
  33735. updatable: updatable,
  33736. instance: instance
  33737. };
  33738. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33739. };
  33740. /**
  33741. * Creates a polygon mesh.
  33742. * Please consider using the same method from the MeshBuilder class instead.
  33743. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33744. * 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.
  33745. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33746. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33747. * Remember you can only change the shape positions, not their number when updating a polygon.
  33748. */
  33749. /**
  33750. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  33751. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  33752. * @param name defines the name of the mesh to create
  33753. * @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
  33754. * @param scene defines the hosting scene
  33755. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  33756. * @param updatable defines if the mesh must be flagged as updatable
  33757. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33758. * @returns a new Mesh
  33759. */
  33760. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33761. var options = {
  33762. shape: shape,
  33763. holes: holes,
  33764. updatable: updatable,
  33765. sideOrientation: sideOrientation
  33766. };
  33767. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33768. };
  33769. /**
  33770. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  33771. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  33772. * @param name defines the name of the mesh to create
  33773. * @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
  33774. * @param depth defines the height of extrusion
  33775. * @param scene defines the hosting scene
  33776. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  33777. * @param updatable defines if the mesh must be flagged as updatable
  33778. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33779. * @returns a new Mesh
  33780. */
  33781. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33782. var options = {
  33783. shape: shape,
  33784. holes: holes,
  33785. depth: depth,
  33786. updatable: updatable,
  33787. sideOrientation: sideOrientation
  33788. };
  33789. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33790. };
  33791. /**
  33792. * Creates an extruded shape mesh.
  33793. * 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
  33794. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33795. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33796. * @param name defines the name of the mesh to create
  33797. * @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
  33798. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  33799. * @param scale is the value to scale the shape
  33800. * @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
  33801. * @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
  33802. * @param scene defines the hosting scene
  33803. * @param updatable defines if the mesh must be flagged as updatable
  33804. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33805. * @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)
  33806. * @returns a new Mesh
  33807. */
  33808. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33809. if (scene === void 0) { scene = null; }
  33810. var options = {
  33811. shape: shape,
  33812. path: path,
  33813. scale: scale,
  33814. rotation: rotation,
  33815. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33816. sideOrientation: sideOrientation,
  33817. instance: instance,
  33818. updatable: updatable
  33819. };
  33820. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33821. };
  33822. /**
  33823. * Creates an custom extruded shape mesh.
  33824. * The custom extrusion is a parametric shape.
  33825. * It has no predefined shape. Its final shape will depend on the input parameters.
  33826. * Please consider using the same method from the MeshBuilder class instead
  33827. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33828. * @param name defines the name of the mesh to create
  33829. * @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
  33830. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  33831. * @param scaleFunction is a custom Javascript function called on each path point
  33832. * @param rotationFunction is a custom Javascript function called on each path point
  33833. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  33834. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  33835. * @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
  33836. * @param scene defines the hosting scene
  33837. * @param updatable defines if the mesh must be flagged as updatable
  33838. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33839. * @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)
  33840. * @returns a new Mesh
  33841. */
  33842. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33843. var options = {
  33844. shape: shape,
  33845. path: path,
  33846. scaleFunction: scaleFunction,
  33847. rotationFunction: rotationFunction,
  33848. ribbonCloseArray: ribbonCloseArray,
  33849. ribbonClosePath: ribbonClosePath,
  33850. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33851. sideOrientation: sideOrientation,
  33852. instance: instance,
  33853. updatable: updatable
  33854. };
  33855. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33856. };
  33857. /**
  33858. * Creates lathe mesh.
  33859. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33860. * Please consider using the same method from the MeshBuilder class instead
  33861. * @param name defines the name of the mesh to create
  33862. * @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
  33863. * @param radius is the radius value of the lathe
  33864. * @param tessellation is the side number of the lathe.
  33865. * @param scene defines the hosting scene
  33866. * @param updatable defines if the mesh must be flagged as updatable
  33867. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33868. * @returns a new Mesh
  33869. */
  33870. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33871. var options = {
  33872. shape: shape,
  33873. radius: radius,
  33874. tessellation: tessellation,
  33875. sideOrientation: sideOrientation,
  33876. updatable: updatable
  33877. };
  33878. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33879. };
  33880. /**
  33881. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  33882. * @param name defines the name of the mesh to create
  33883. * @param size sets the size (float) of both sides of the plane at once (default 1)
  33884. * @param scene defines the hosting scene
  33885. * @param updatable defines if the mesh must be flagged as updatable
  33886. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33887. * @returns a new Mesh
  33888. */
  33889. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33890. var options = {
  33891. size: size,
  33892. width: size,
  33893. height: size,
  33894. sideOrientation: sideOrientation,
  33895. updatable: updatable
  33896. };
  33897. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33898. };
  33899. /**
  33900. * Creates a ground mesh.
  33901. * Please consider using the same method from the MeshBuilder class instead
  33902. * @param name defines the name of the mesh to create
  33903. * @param width set the width of the ground
  33904. * @param height set the height of the ground
  33905. * @param subdivisions sets the number of subdivisions per side
  33906. * @param scene defines the hosting scene
  33907. * @param updatable defines if the mesh must be flagged as updatable
  33908. * @returns a new Mesh
  33909. */
  33910. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33911. var options = {
  33912. width: width,
  33913. height: height,
  33914. subdivisions: subdivisions,
  33915. updatable: updatable
  33916. };
  33917. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33918. };
  33919. /**
  33920. * Creates a tiled ground mesh.
  33921. * Please consider using the same method from the MeshBuilder class instead
  33922. * @param name defines the name of the mesh to create
  33923. * @param xmin set the ground minimum X coordinate
  33924. * @param zmin set the ground minimum Y coordinate
  33925. * @param xmax set the ground maximum X coordinate
  33926. * @param zmax set the ground maximum Z coordinate
  33927. * @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
  33928. * @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
  33929. * @param scene defines the hosting scene
  33930. * @param updatable defines if the mesh must be flagged as updatable
  33931. * @returns a new Mesh
  33932. */
  33933. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33934. var options = {
  33935. xmin: xmin,
  33936. zmin: zmin,
  33937. xmax: xmax,
  33938. zmax: zmax,
  33939. subdivisions: subdivisions,
  33940. precision: precision,
  33941. updatable: updatable
  33942. };
  33943. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33944. };
  33945. /**
  33946. * Creates a ground mesh from a height map.
  33947. * Please consider using the same method from the MeshBuilder class instead
  33948. * @see http://doc.babylonjs.com/babylon101/height_map
  33949. * @param name defines the name of the mesh to create
  33950. * @param url sets the URL of the height map image resource
  33951. * @param width set the ground width size
  33952. * @param height set the ground height size
  33953. * @param subdivisions sets the number of subdivision per side
  33954. * @param minHeight is the minimum altitude on the ground
  33955. * @param maxHeight is the maximum altitude on the ground
  33956. * @param scene defines the hosting scene
  33957. * @param updatable defines if the mesh must be flagged as updatable
  33958. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  33959. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  33960. * @returns a new Mesh
  33961. */
  33962. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  33963. var options = {
  33964. width: width,
  33965. height: height,
  33966. subdivisions: subdivisions,
  33967. minHeight: minHeight,
  33968. maxHeight: maxHeight,
  33969. updatable: updatable,
  33970. onReady: onReady,
  33971. alphaFilter: alphaFilter
  33972. };
  33973. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33974. };
  33975. /**
  33976. * Creates a tube mesh.
  33977. * The tube is a parametric shape.
  33978. * It has no predefined shape. Its final shape will depend on the input parameters.
  33979. * Please consider using the same method from the MeshBuilder class instead
  33980. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33981. * @param name defines the name of the mesh to create
  33982. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  33983. * @param radius sets the tube radius size
  33984. * @param tessellation is the number of sides on the tubular surface
  33985. * @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
  33986. * @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
  33987. * @param scene defines the hosting scene
  33988. * @param updatable defines if the mesh must be flagged as updatable
  33989. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33990. * @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)
  33991. * @returns a new Mesh
  33992. */
  33993. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33994. var options = {
  33995. path: path,
  33996. radius: radius,
  33997. tessellation: tessellation,
  33998. radiusFunction: radiusFunction,
  33999. arc: 1,
  34000. cap: cap,
  34001. updatable: updatable,
  34002. sideOrientation: sideOrientation,
  34003. instance: instance
  34004. };
  34005. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34006. };
  34007. /**
  34008. * Creates a polyhedron mesh.
  34009. * Please consider using the same method from the MeshBuilder class instead.
  34010. * * 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
  34011. * * The parameter `size` (positive float, default 1) sets the polygon size
  34012. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  34013. * * 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`
  34014. * * 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
  34015. * * 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)`)
  34016. * * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  34017. * * 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
  34018. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34019. * * 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
  34020. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  34021. * @param name defines the name of the mesh to create
  34022. * @param options defines the options used to create the mesh
  34023. * @param scene defines the hosting scene
  34024. * @returns a new Mesh
  34025. */
  34026. Mesh.CreatePolyhedron = function (name, options, scene) {
  34027. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34028. };
  34029. /**
  34030. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  34031. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  34032. * * 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`)
  34033. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  34034. * * 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
  34035. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34036. * * 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
  34037. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  34038. * @param name defines the name of the mesh
  34039. * @param options defines the options used to create the mesh
  34040. * @param scene defines the hosting scene
  34041. * @returns a new Mesh
  34042. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  34043. */
  34044. Mesh.CreateIcoSphere = function (name, options, scene) {
  34045. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34046. };
  34047. /**
  34048. * Creates a decal mesh.
  34049. * Please consider using the same method from the MeshBuilder class instead.
  34050. * A decal is a mesh usually applied as a model onto the surface of another mesh
  34051. * @param name defines the name of the mesh
  34052. * @param sourceMesh defines the mesh receiving the decal
  34053. * @param position sets the position of the decal in world coordinates
  34054. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  34055. * @param size sets the decal scaling
  34056. * @param angle sets the angle to rotate the decal
  34057. * @returns a new Mesh
  34058. */
  34059. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34060. var options = {
  34061. position: position,
  34062. normal: normal,
  34063. size: size,
  34064. angle: angle
  34065. };
  34066. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34067. };
  34068. // Skeletons
  34069. /**
  34070. * Prepare internal position array for software CPU skinning
  34071. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  34072. */
  34073. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34074. if (!this._sourcePositions) {
  34075. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34076. if (!source) {
  34077. return this._sourcePositions;
  34078. }
  34079. this._sourcePositions = new Float32Array(source);
  34080. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34081. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34082. }
  34083. }
  34084. return this._sourcePositions;
  34085. };
  34086. /**
  34087. * Prepare internal normal array for software CPU skinning
  34088. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34089. */
  34090. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34091. if (!this._sourceNormals) {
  34092. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34093. if (!source) {
  34094. return this._sourceNormals;
  34095. }
  34096. this._sourceNormals = new Float32Array(source);
  34097. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34098. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34099. }
  34100. }
  34101. return this._sourceNormals;
  34102. };
  34103. /**
  34104. * Updates the vertex buffer by applying transformation from the bones
  34105. * @param skeleton defines the skeleton to apply to current mesh
  34106. * @returns the current mesh
  34107. */
  34108. Mesh.prototype.applySkeleton = function (skeleton) {
  34109. if (!this.geometry) {
  34110. return this;
  34111. }
  34112. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  34113. return this;
  34114. }
  34115. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  34116. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34117. return this;
  34118. }
  34119. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34120. return this;
  34121. }
  34122. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34123. return this;
  34124. }
  34125. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34126. return this;
  34127. }
  34128. if (!this._sourcePositions) {
  34129. var submeshes = this.subMeshes.slice();
  34130. this.setPositionsForCPUSkinning();
  34131. this.subMeshes = submeshes;
  34132. }
  34133. if (!this._sourceNormals) {
  34134. this.setNormalsForCPUSkinning();
  34135. }
  34136. // positionsData checks for not being Float32Array will only pass at most once
  34137. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34138. if (!positionsData) {
  34139. return this;
  34140. }
  34141. if (!(positionsData instanceof Float32Array)) {
  34142. positionsData = new Float32Array(positionsData);
  34143. }
  34144. // normalsData checks for not being Float32Array will only pass at most once
  34145. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34146. if (!normalsData) {
  34147. return this;
  34148. }
  34149. if (!(normalsData instanceof Float32Array)) {
  34150. normalsData = new Float32Array(normalsData);
  34151. }
  34152. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34153. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34154. if (!matricesWeightsData || !matricesIndicesData) {
  34155. return this;
  34156. }
  34157. var needExtras = this.numBoneInfluencers > 4;
  34158. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34159. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34160. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34161. var tempVector3 = BABYLON.Vector3.Zero();
  34162. var finalMatrix = new BABYLON.Matrix();
  34163. var tempMatrix = new BABYLON.Matrix();
  34164. var matWeightIdx = 0;
  34165. var inf;
  34166. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34167. var weight;
  34168. for (inf = 0; inf < 4; inf++) {
  34169. weight = matricesWeightsData[matWeightIdx + inf];
  34170. if (weight > 0) {
  34171. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34172. finalMatrix.addToSelf(tempMatrix);
  34173. }
  34174. }
  34175. if (needExtras) {
  34176. for (inf = 0; inf < 4; inf++) {
  34177. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34178. if (weight > 0) {
  34179. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34180. finalMatrix.addToSelf(tempMatrix);
  34181. }
  34182. }
  34183. }
  34184. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34185. tempVector3.toArray(positionsData, index);
  34186. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34187. tempVector3.toArray(normalsData, index);
  34188. finalMatrix.reset();
  34189. }
  34190. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34191. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34192. return this;
  34193. };
  34194. // Tools
  34195. /**
  34196. * 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
  34197. * @param meshes defines the list of meshes to scan
  34198. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  34199. */
  34200. Mesh.MinMax = function (meshes) {
  34201. var minVector = null;
  34202. var maxVector = null;
  34203. meshes.forEach(function (mesh, index, array) {
  34204. var boundingInfo = mesh.getBoundingInfo();
  34205. var boundingBox = boundingInfo.boundingBox;
  34206. if (!minVector || !maxVector) {
  34207. minVector = boundingBox.minimumWorld;
  34208. maxVector = boundingBox.maximumWorld;
  34209. }
  34210. else {
  34211. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34212. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34213. }
  34214. });
  34215. if (!minVector || !maxVector) {
  34216. return {
  34217. min: BABYLON.Vector3.Zero(),
  34218. max: BABYLON.Vector3.Zero()
  34219. };
  34220. }
  34221. return {
  34222. min: minVector,
  34223. max: maxVector
  34224. };
  34225. };
  34226. /**
  34227. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  34228. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  34229. * @returns a vector3
  34230. */
  34231. Mesh.Center = function (meshesOrMinMaxVector) {
  34232. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34233. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34234. };
  34235. /**
  34236. * Merge the array of meshes into a single mesh for performance reasons.
  34237. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  34238. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  34239. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  34240. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34241. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  34242. * @returns a new mesh
  34243. */
  34244. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34245. if (disposeSource === void 0) { disposeSource = true; }
  34246. var index;
  34247. if (!allow32BitsIndices) {
  34248. var totalVertices = 0;
  34249. // Counting vertices
  34250. for (index = 0; index < meshes.length; index++) {
  34251. if (meshes[index]) {
  34252. totalVertices += meshes[index].getTotalVertices();
  34253. if (totalVertices > 65536) {
  34254. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34255. return null;
  34256. }
  34257. }
  34258. }
  34259. }
  34260. // Merge
  34261. var vertexData = null;
  34262. var otherVertexData;
  34263. var indiceArray = new Array();
  34264. var source = null;
  34265. for (index = 0; index < meshes.length; index++) {
  34266. if (meshes[index]) {
  34267. var wm = meshes[index].computeWorldMatrix(true);
  34268. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34269. otherVertexData.transform(wm);
  34270. if (vertexData) {
  34271. vertexData.merge(otherVertexData, allow32BitsIndices);
  34272. }
  34273. else {
  34274. vertexData = otherVertexData;
  34275. source = meshes[index];
  34276. }
  34277. if (subdivideWithSubMeshes) {
  34278. indiceArray.push(meshes[index].getTotalIndices());
  34279. }
  34280. }
  34281. }
  34282. source = source;
  34283. if (!meshSubclass) {
  34284. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34285. }
  34286. vertexData.applyToMesh(meshSubclass);
  34287. // Setting properties
  34288. meshSubclass.material = source.material;
  34289. meshSubclass.checkCollisions = source.checkCollisions;
  34290. // Cleaning
  34291. if (disposeSource) {
  34292. for (index = 0; index < meshes.length; index++) {
  34293. if (meshes[index]) {
  34294. meshes[index].dispose();
  34295. }
  34296. }
  34297. }
  34298. // Subdivide
  34299. if (subdivideWithSubMeshes) {
  34300. //-- removal of global submesh
  34301. meshSubclass.releaseSubMeshes();
  34302. index = 0;
  34303. var offset = 0;
  34304. //-- apply subdivision according to index table
  34305. while (index < indiceArray.length) {
  34306. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34307. offset += indiceArray[index];
  34308. index++;
  34309. }
  34310. }
  34311. return meshSubclass;
  34312. };
  34313. // Consts
  34314. /**
  34315. * Mesh side orientation : usually the external or front surface
  34316. */
  34317. Mesh.FRONTSIDE = 0;
  34318. /**
  34319. * Mesh side orientation : usually the internal or back surface
  34320. */
  34321. Mesh.BACKSIDE = 1;
  34322. /**
  34323. * Mesh side orientation : both internal and external or front and back surfaces
  34324. */
  34325. Mesh.DOUBLESIDE = 2;
  34326. /**
  34327. * Mesh side orientation : by default, `FRONTSIDE`
  34328. */
  34329. Mesh.DEFAULTSIDE = 0;
  34330. /**
  34331. * Mesh cap setting : no cap
  34332. */
  34333. Mesh.NO_CAP = 0;
  34334. /**
  34335. * Mesh cap setting : one cap at the beginning of the mesh
  34336. */
  34337. Mesh.CAP_START = 1;
  34338. /**
  34339. * Mesh cap setting : one cap at the end of the mesh
  34340. */
  34341. Mesh.CAP_END = 2;
  34342. /**
  34343. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  34344. */
  34345. Mesh.CAP_ALL = 3;
  34346. return Mesh;
  34347. }(BABYLON.AbstractMesh));
  34348. BABYLON.Mesh = Mesh;
  34349. })(BABYLON || (BABYLON = {}));
  34350. //# sourceMappingURL=babylon.mesh.js.map
  34351. var BABYLON;
  34352. (function (BABYLON) {
  34353. /**
  34354. * Base class for submeshes
  34355. */
  34356. var BaseSubMesh = /** @class */ (function () {
  34357. function BaseSubMesh() {
  34358. }
  34359. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34360. /**
  34361. * Gets associated effect
  34362. */
  34363. get: function () {
  34364. return this._materialEffect;
  34365. },
  34366. enumerable: true,
  34367. configurable: true
  34368. });
  34369. /**
  34370. * Sets associated effect (effect used to render this submesh)
  34371. * @param effect defines the effect to associate with
  34372. * @param defines defines the set of defines used to compile this effect
  34373. */
  34374. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34375. if (defines === void 0) { defines = null; }
  34376. if (this._materialEffect === effect) {
  34377. if (!effect) {
  34378. this._materialDefines = null;
  34379. }
  34380. return;
  34381. }
  34382. this._materialDefines = defines;
  34383. this._materialEffect = effect;
  34384. };
  34385. return BaseSubMesh;
  34386. }());
  34387. BABYLON.BaseSubMesh = BaseSubMesh;
  34388. /**
  34389. * Defines a subdivision inside a mesh
  34390. */
  34391. var SubMesh = /** @class */ (function (_super) {
  34392. __extends(SubMesh, _super);
  34393. /**
  34394. * Creates a new submesh
  34395. * @param materialIndex defines the material index to use
  34396. * @param verticesStart defines vertex index start
  34397. * @param verticesCount defines vertices count
  34398. * @param indexStart defines index start
  34399. * @param indexCount defines indices count
  34400. * @param mesh defines the parent mesh
  34401. * @param renderingMesh defines an optional rendering mesh
  34402. * @param createBoundingBox defines if bounding box should be created for this submesh
  34403. */
  34404. function SubMesh(
  34405. /** the material index to use */
  34406. materialIndex,
  34407. /** vertex index start */
  34408. verticesStart,
  34409. /** vertices count */
  34410. verticesCount,
  34411. /** index start */
  34412. indexStart,
  34413. /** indices count */
  34414. indexCount, mesh, renderingMesh, createBoundingBox) {
  34415. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34416. var _this = _super.call(this) || this;
  34417. _this.materialIndex = materialIndex;
  34418. _this.verticesStart = verticesStart;
  34419. _this.verticesCount = verticesCount;
  34420. _this.indexStart = indexStart;
  34421. _this.indexCount = indexCount;
  34422. /** @hidden */
  34423. _this._renderId = 0;
  34424. _this._mesh = mesh;
  34425. _this._renderingMesh = renderingMesh || mesh;
  34426. mesh.subMeshes.push(_this);
  34427. _this._trianglePlanes = [];
  34428. _this._id = mesh.subMeshes.length - 1;
  34429. if (createBoundingBox) {
  34430. _this.refreshBoundingInfo();
  34431. mesh.computeWorldMatrix(true);
  34432. }
  34433. return _this;
  34434. }
  34435. /**
  34436. * Add a new submesh to a mesh
  34437. * @param materialIndex defines the material index to use
  34438. * @param verticesStart defines vertex index start
  34439. * @param verticesCount defines vertices count
  34440. * @param indexStart defines index start
  34441. * @param indexCount defines indices count
  34442. * @param mesh defines the parent mesh
  34443. * @param renderingMesh defines an optional rendering mesh
  34444. * @param createBoundingBox defines if bounding box should be created for this submesh
  34445. * @returns the new submesh
  34446. */
  34447. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34448. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34449. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34450. };
  34451. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34452. /**
  34453. * Returns true if this submesh covers the entire parent mesh
  34454. * @ignorenaming
  34455. */
  34456. get: function () {
  34457. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  34458. },
  34459. enumerable: true,
  34460. configurable: true
  34461. });
  34462. /**
  34463. * Returns the submesh BoudingInfo object
  34464. * @returns current bounding info (or mesh's one if the submesh is global)
  34465. */
  34466. SubMesh.prototype.getBoundingInfo = function () {
  34467. if (this.IsGlobal) {
  34468. return this._mesh.getBoundingInfo();
  34469. }
  34470. return this._boundingInfo;
  34471. };
  34472. /**
  34473. * Sets the submesh BoundingInfo
  34474. * @param boundingInfo defines the new bounding info to use
  34475. * @returns the SubMesh
  34476. */
  34477. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34478. this._boundingInfo = boundingInfo;
  34479. return this;
  34480. };
  34481. /**
  34482. * Returns the mesh of the current submesh
  34483. * @return the parent mesh
  34484. */
  34485. SubMesh.prototype.getMesh = function () {
  34486. return this._mesh;
  34487. };
  34488. /**
  34489. * Returns the rendering mesh of the submesh
  34490. * @returns the rendering mesh (could be different from parent mesh)
  34491. */
  34492. SubMesh.prototype.getRenderingMesh = function () {
  34493. return this._renderingMesh;
  34494. };
  34495. /**
  34496. * Returns the submesh material
  34497. * @returns null or the current material
  34498. */
  34499. SubMesh.prototype.getMaterial = function () {
  34500. var rootMaterial = this._renderingMesh.material;
  34501. if (rootMaterial === null || rootMaterial === undefined) {
  34502. return this._mesh.getScene().defaultMaterial;
  34503. }
  34504. else if (rootMaterial.getSubMaterial) {
  34505. var multiMaterial = rootMaterial;
  34506. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34507. if (this._currentMaterial !== effectiveMaterial) {
  34508. this._currentMaterial = effectiveMaterial;
  34509. this._materialDefines = null;
  34510. }
  34511. return effectiveMaterial;
  34512. }
  34513. return rootMaterial;
  34514. };
  34515. // Methods
  34516. /**
  34517. * Sets a new updated BoundingInfo object to the submesh
  34518. * @returns the SubMesh
  34519. */
  34520. SubMesh.prototype.refreshBoundingInfo = function () {
  34521. this._lastColliderWorldVertices = null;
  34522. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34523. return this;
  34524. }
  34525. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34526. if (!data) {
  34527. this._boundingInfo = this._mesh.getBoundingInfo();
  34528. return this;
  34529. }
  34530. var indices = this._renderingMesh.getIndices();
  34531. var extend;
  34532. //is this the only submesh?
  34533. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34534. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34535. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34536. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34537. }
  34538. else {
  34539. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34540. }
  34541. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34542. return this;
  34543. };
  34544. /** @hidden */
  34545. SubMesh.prototype._checkCollision = function (collider) {
  34546. var boundingInfo = this.getBoundingInfo();
  34547. return boundingInfo._checkCollision(collider);
  34548. };
  34549. /**
  34550. * Updates the submesh BoundingInfo
  34551. * @param world defines the world matrix to use to update the bounding info
  34552. * @returns the submesh
  34553. */
  34554. SubMesh.prototype.updateBoundingInfo = function (world) {
  34555. var boundingInfo = this.getBoundingInfo();
  34556. if (!boundingInfo) {
  34557. this.refreshBoundingInfo();
  34558. boundingInfo = this.getBoundingInfo();
  34559. }
  34560. boundingInfo.update(world);
  34561. return this;
  34562. };
  34563. /**
  34564. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34565. * @param frustumPlanes defines the frustum planes
  34566. * @returns true if the submesh is intersecting with the frustum
  34567. */
  34568. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34569. var boundingInfo = this.getBoundingInfo();
  34570. if (!boundingInfo) {
  34571. return false;
  34572. }
  34573. return boundingInfo.isInFrustum(frustumPlanes);
  34574. };
  34575. /**
  34576. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  34577. * @param frustumPlanes defines the frustum planes
  34578. * @returns true if the submesh is inside the frustum
  34579. */
  34580. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34581. var boundingInfo = this.getBoundingInfo();
  34582. if (!boundingInfo) {
  34583. return false;
  34584. }
  34585. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34586. };
  34587. /**
  34588. * Renders the submesh
  34589. * @param enableAlphaMode defines if alpha needs to be used
  34590. * @returns the submesh
  34591. */
  34592. SubMesh.prototype.render = function (enableAlphaMode) {
  34593. this._renderingMesh.render(this, enableAlphaMode);
  34594. return this;
  34595. };
  34596. /**
  34597. * @hidden
  34598. */
  34599. SubMesh.prototype._getLinesIndexBuffer = function (indices, engine) {
  34600. if (!this._linesIndexBuffer) {
  34601. var linesIndices = [];
  34602. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34603. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34604. }
  34605. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34606. this._linesIndexCount = linesIndices.length;
  34607. }
  34608. return this._linesIndexBuffer;
  34609. };
  34610. /**
  34611. * Checks if the submesh intersects with a ray
  34612. * @param ray defines the ray to test
  34613. * @returns true is the passed ray intersects the submesh bounding box
  34614. */
  34615. SubMesh.prototype.canIntersects = function (ray) {
  34616. var boundingInfo = this.getBoundingInfo();
  34617. if (!boundingInfo) {
  34618. return false;
  34619. }
  34620. return ray.intersectsBox(boundingInfo.boundingBox);
  34621. };
  34622. /**
  34623. * Intersects current submesh with a ray
  34624. * @param ray defines the ray to test
  34625. * @param positions defines mesh's positions array
  34626. * @param indices defines mesh's indices array
  34627. * @param fastCheck defines if only bounding info should be used
  34628. * @returns intersection info or null if no intersection
  34629. */
  34630. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34631. var intersectInfo = null;
  34632. var material = this.getMaterial();
  34633. if (!material) {
  34634. return null;
  34635. }
  34636. switch (material.fillMode) {
  34637. case BABYLON.Material.PointListDrawMode:
  34638. case BABYLON.Material.LineListDrawMode:
  34639. case BABYLON.Material.LineLoopDrawMode:
  34640. case BABYLON.Material.LineStripDrawMode:
  34641. case BABYLON.Material.TriangleFanDrawMode:
  34642. case BABYLON.Material.TriangleStripDrawMode:
  34643. return null;
  34644. }
  34645. // LineMesh first as it's also a Mesh...
  34646. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34647. var lineMesh = this._mesh;
  34648. // Line test
  34649. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34650. var p0 = positions[indices[index]];
  34651. var p1 = positions[indices[index + 1]];
  34652. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34653. if (length < 0) {
  34654. continue;
  34655. }
  34656. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34657. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34658. if (fastCheck) {
  34659. break;
  34660. }
  34661. }
  34662. }
  34663. }
  34664. else {
  34665. // Triangles test
  34666. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34667. var p0 = positions[indices[index]];
  34668. var p1 = positions[indices[index + 1]];
  34669. var p2 = positions[indices[index + 2]];
  34670. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34671. if (currentIntersectInfo) {
  34672. if (currentIntersectInfo.distance < 0) {
  34673. continue;
  34674. }
  34675. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34676. intersectInfo = currentIntersectInfo;
  34677. intersectInfo.faceId = index / 3;
  34678. if (fastCheck) {
  34679. break;
  34680. }
  34681. }
  34682. }
  34683. }
  34684. }
  34685. return intersectInfo;
  34686. };
  34687. /** @hidden */
  34688. SubMesh.prototype._rebuild = function () {
  34689. if (this._linesIndexBuffer) {
  34690. this._linesIndexBuffer = null;
  34691. }
  34692. };
  34693. // Clone
  34694. /**
  34695. * Creates a new submesh from the passed mesh
  34696. * @param newMesh defines the new hosting mesh
  34697. * @param newRenderingMesh defines an optional rendering mesh
  34698. * @returns the new submesh
  34699. */
  34700. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34701. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34702. if (!this.IsGlobal) {
  34703. var boundingInfo = this.getBoundingInfo();
  34704. if (!boundingInfo) {
  34705. return result;
  34706. }
  34707. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34708. }
  34709. return result;
  34710. };
  34711. // Dispose
  34712. /**
  34713. * Release associated resources
  34714. */
  34715. SubMesh.prototype.dispose = function () {
  34716. if (this._linesIndexBuffer) {
  34717. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34718. this._linesIndexBuffer = null;
  34719. }
  34720. // Remove from mesh
  34721. var index = this._mesh.subMeshes.indexOf(this);
  34722. this._mesh.subMeshes.splice(index, 1);
  34723. };
  34724. // Statics
  34725. /**
  34726. * Creates a new submesh from indices data
  34727. * @param materialIndex the index of the main mesh material
  34728. * @param startIndex the index where to start the copy in the mesh indices array
  34729. * @param indexCount the number of indices to copy then from the startIndex
  34730. * @param mesh the main mesh to create the submesh from
  34731. * @param renderingMesh the optional rendering mesh
  34732. * @returns a new submesh
  34733. */
  34734. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34735. var minVertexIndex = Number.MAX_VALUE;
  34736. var maxVertexIndex = -Number.MAX_VALUE;
  34737. renderingMesh = (renderingMesh || mesh);
  34738. var indices = renderingMesh.getIndices();
  34739. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34740. var vertexIndex = indices[index];
  34741. if (vertexIndex < minVertexIndex)
  34742. minVertexIndex = vertexIndex;
  34743. if (vertexIndex > maxVertexIndex)
  34744. maxVertexIndex = vertexIndex;
  34745. }
  34746. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34747. };
  34748. return SubMesh;
  34749. }(BaseSubMesh));
  34750. BABYLON.SubMesh = SubMesh;
  34751. })(BABYLON || (BABYLON = {}));
  34752. //# sourceMappingURL=babylon.subMesh.js.map
  34753. var __assign = (this && this.__assign) || function () {
  34754. __assign = Object.assign || function(t) {
  34755. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34756. s = arguments[i];
  34757. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34758. t[p] = s[p];
  34759. }
  34760. return t;
  34761. };
  34762. return __assign.apply(this, arguments);
  34763. };
  34764. var BABYLON;
  34765. (function (BABYLON) {
  34766. /**
  34767. * Manages the defines for the Material
  34768. */
  34769. var MaterialDefines = /** @class */ (function () {
  34770. function MaterialDefines() {
  34771. this._isDirty = true;
  34772. /** @hidden */
  34773. this._areLightsDirty = true;
  34774. /** @hidden */
  34775. this._areAttributesDirty = true;
  34776. /** @hidden */
  34777. this._areTexturesDirty = true;
  34778. /** @hidden */
  34779. this._areFresnelDirty = true;
  34780. /** @hidden */
  34781. this._areMiscDirty = true;
  34782. /** @hidden */
  34783. this._areImageProcessingDirty = true;
  34784. /** @hidden */
  34785. this._normals = false;
  34786. /** @hidden */
  34787. this._uvs = false;
  34788. /** @hidden */
  34789. this._needNormals = false;
  34790. /** @hidden */
  34791. this._needUVs = false;
  34792. }
  34793. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34794. /**
  34795. * Specifies if the material needs to be re-calculated
  34796. */
  34797. get: function () {
  34798. return this._isDirty;
  34799. },
  34800. enumerable: true,
  34801. configurable: true
  34802. });
  34803. /**
  34804. * Marks the material to indicate that it has been re-calculated
  34805. */
  34806. MaterialDefines.prototype.markAsProcessed = function () {
  34807. this._isDirty = false;
  34808. this._areAttributesDirty = false;
  34809. this._areTexturesDirty = false;
  34810. this._areFresnelDirty = false;
  34811. this._areLightsDirty = false;
  34812. this._areMiscDirty = false;
  34813. this._areImageProcessingDirty = false;
  34814. };
  34815. /**
  34816. * Marks the material to indicate that it needs to be re-calculated
  34817. */
  34818. MaterialDefines.prototype.markAsUnprocessed = function () {
  34819. this._isDirty = true;
  34820. };
  34821. /**
  34822. * Marks the material to indicate all of its defines need to be re-calculated
  34823. */
  34824. MaterialDefines.prototype.markAllAsDirty = function () {
  34825. this._areTexturesDirty = true;
  34826. this._areAttributesDirty = true;
  34827. this._areLightsDirty = true;
  34828. this._areFresnelDirty = true;
  34829. this._areMiscDirty = true;
  34830. this._areImageProcessingDirty = true;
  34831. this._isDirty = true;
  34832. };
  34833. /**
  34834. * Marks the material to indicate that image processing needs to be re-calculated
  34835. */
  34836. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34837. this._areImageProcessingDirty = true;
  34838. this._isDirty = true;
  34839. };
  34840. /**
  34841. * Marks the material to indicate the lights need to be re-calculated
  34842. */
  34843. MaterialDefines.prototype.markAsLightDirty = function () {
  34844. this._areLightsDirty = true;
  34845. this._isDirty = true;
  34846. };
  34847. /**
  34848. * Marks the attribute state as changed
  34849. */
  34850. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34851. this._areAttributesDirty = true;
  34852. this._isDirty = true;
  34853. };
  34854. /**
  34855. * Marks the texture state as changed
  34856. */
  34857. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34858. this._areTexturesDirty = true;
  34859. this._isDirty = true;
  34860. };
  34861. /**
  34862. * Marks the fresnel state as changed
  34863. */
  34864. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34865. this._areFresnelDirty = true;
  34866. this._isDirty = true;
  34867. };
  34868. /**
  34869. * Marks the misc state as changed
  34870. */
  34871. MaterialDefines.prototype.markAsMiscDirty = function () {
  34872. this._areMiscDirty = true;
  34873. this._isDirty = true;
  34874. };
  34875. /**
  34876. * Rebuilds the material defines
  34877. */
  34878. MaterialDefines.prototype.rebuild = function () {
  34879. if (this._keys) {
  34880. delete this._keys;
  34881. }
  34882. this._keys = [];
  34883. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34884. var key = _a[_i];
  34885. if (key[0] === "_") {
  34886. continue;
  34887. }
  34888. this._keys.push(key);
  34889. }
  34890. };
  34891. /**
  34892. * Specifies if two material defines are equal
  34893. * @param other - A material define instance to compare to
  34894. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34895. */
  34896. MaterialDefines.prototype.isEqual = function (other) {
  34897. if (this._keys.length !== other._keys.length) {
  34898. return false;
  34899. }
  34900. for (var index = 0; index < this._keys.length; index++) {
  34901. var prop = this._keys[index];
  34902. if (this[prop] !== other[prop]) {
  34903. return false;
  34904. }
  34905. }
  34906. return true;
  34907. };
  34908. /**
  34909. * Clones this instance's defines to another instance
  34910. * @param other - material defines to clone values to
  34911. */
  34912. MaterialDefines.prototype.cloneTo = function (other) {
  34913. if (this._keys.length !== other._keys.length) {
  34914. other._keys = this._keys.slice(0);
  34915. }
  34916. for (var index = 0; index < this._keys.length; index++) {
  34917. var prop = this._keys[index];
  34918. other[prop] = this[prop];
  34919. }
  34920. };
  34921. /**
  34922. * Resets the material define values
  34923. */
  34924. MaterialDefines.prototype.reset = function () {
  34925. for (var index = 0; index < this._keys.length; index++) {
  34926. var prop = this._keys[index];
  34927. var type = typeof this[prop];
  34928. switch (type) {
  34929. case "number":
  34930. this[prop] = 0;
  34931. break;
  34932. case "string":
  34933. this[prop] = "";
  34934. break;
  34935. default:
  34936. this[prop] = false;
  34937. break;
  34938. }
  34939. }
  34940. };
  34941. /**
  34942. * Converts the material define values to a string
  34943. * @returns - String of material define information
  34944. */
  34945. MaterialDefines.prototype.toString = function () {
  34946. var result = "";
  34947. for (var index = 0; index < this._keys.length; index++) {
  34948. var prop = this._keys[index];
  34949. var value = this[prop];
  34950. var type = typeof value;
  34951. switch (type) {
  34952. case "number":
  34953. case "string":
  34954. result += "#define " + prop + " " + value + "\n";
  34955. break;
  34956. default:
  34957. if (value) {
  34958. result += "#define " + prop + "\n";
  34959. }
  34960. break;
  34961. }
  34962. }
  34963. return result;
  34964. };
  34965. return MaterialDefines;
  34966. }());
  34967. BABYLON.MaterialDefines = MaterialDefines;
  34968. /**
  34969. * Base class for the main features of a material in Babylon.js
  34970. */
  34971. var Material = /** @class */ (function () {
  34972. /**
  34973. * Creates a material instance
  34974. * @param name defines the name of the material
  34975. * @param scene defines the scene to reference
  34976. * @param doNotAdd specifies if the material should be added to the scene
  34977. */
  34978. function Material(name, scene, doNotAdd) {
  34979. /**
  34980. * Specifies if the ready state should be checked on each call
  34981. */
  34982. this.checkReadyOnEveryCall = false;
  34983. /**
  34984. * Specifies if the ready state should be checked once
  34985. */
  34986. this.checkReadyOnlyOnce = false;
  34987. /**
  34988. * The state of the material
  34989. */
  34990. this.state = "";
  34991. /**
  34992. * The alpha value of the material
  34993. */
  34994. this._alpha = 1.0;
  34995. /**
  34996. * Specifies if back face culling is enabled
  34997. */
  34998. this._backFaceCulling = true;
  34999. /**
  35000. * Specifies if the material should be serialized
  35001. */
  35002. this.doNotSerialize = false;
  35003. /**
  35004. * Specifies if the effect should be stored on sub meshes
  35005. */
  35006. this.storeEffectOnSubMeshes = false;
  35007. /**
  35008. * An event triggered when the material is disposed
  35009. */
  35010. this.onDisposeObservable = new BABYLON.Observable();
  35011. /**
  35012. * Stores the value of the alpha mode
  35013. */
  35014. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35015. /**
  35016. * Stores the state of the need depth pre-pass value
  35017. */
  35018. this._needDepthPrePass = false;
  35019. /**
  35020. * Specifies if depth writing should be disabled
  35021. */
  35022. this.disableDepthWrite = false;
  35023. /**
  35024. * Specifies if depth writing should be forced
  35025. */
  35026. this.forceDepthWrite = false;
  35027. /**
  35028. * Specifies if there should be a separate pass for culling
  35029. */
  35030. this.separateCullingPass = false;
  35031. /**
  35032. * Stores the state specifing if fog should be enabled
  35033. */
  35034. this._fogEnabled = true;
  35035. /**
  35036. * Stores the size of points
  35037. */
  35038. this.pointSize = 1.0;
  35039. /**
  35040. * Stores the z offset value
  35041. */
  35042. this.zOffset = 0;
  35043. /**
  35044. * @hidden
  35045. * Specifies if the material was previously ready
  35046. */
  35047. this._wasPreviouslyReady = false;
  35048. /**
  35049. * Stores the fill mode state
  35050. */
  35051. this._fillMode = Material.TriangleFillMode;
  35052. this.name = name;
  35053. this.id = name || BABYLON.Tools.RandomId();
  35054. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35055. this.uniqueId = this._scene.getUniqueId();
  35056. if (this._scene.useRightHandedSystem) {
  35057. this.sideOrientation = Material.ClockWiseSideOrientation;
  35058. }
  35059. else {
  35060. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35061. }
  35062. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35063. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35064. if (!doNotAdd) {
  35065. this._scene.materials.push(this);
  35066. this._scene.onNewMaterialAddedObservable.notifyObservers(this);
  35067. }
  35068. }
  35069. Object.defineProperty(Material, "TriangleFillMode", {
  35070. /**
  35071. * Returns the triangle fill mode
  35072. */
  35073. get: function () {
  35074. return Material._TriangleFillMode;
  35075. },
  35076. enumerable: true,
  35077. configurable: true
  35078. });
  35079. Object.defineProperty(Material, "WireFrameFillMode", {
  35080. /**
  35081. * Returns the wireframe mode
  35082. */
  35083. get: function () {
  35084. return Material._WireFrameFillMode;
  35085. },
  35086. enumerable: true,
  35087. configurable: true
  35088. });
  35089. Object.defineProperty(Material, "PointFillMode", {
  35090. /**
  35091. * Returns the point fill mode
  35092. */
  35093. get: function () {
  35094. return Material._PointFillMode;
  35095. },
  35096. enumerable: true,
  35097. configurable: true
  35098. });
  35099. Object.defineProperty(Material, "PointListDrawMode", {
  35100. /**
  35101. * Returns the point list draw mode
  35102. */
  35103. get: function () {
  35104. return Material._PointListDrawMode;
  35105. },
  35106. enumerable: true,
  35107. configurable: true
  35108. });
  35109. Object.defineProperty(Material, "LineListDrawMode", {
  35110. /**
  35111. * Returns the line list draw mode
  35112. */
  35113. get: function () {
  35114. return Material._LineListDrawMode;
  35115. },
  35116. enumerable: true,
  35117. configurable: true
  35118. });
  35119. Object.defineProperty(Material, "LineLoopDrawMode", {
  35120. /**
  35121. * Returns the line loop draw mode
  35122. */
  35123. get: function () {
  35124. return Material._LineLoopDrawMode;
  35125. },
  35126. enumerable: true,
  35127. configurable: true
  35128. });
  35129. Object.defineProperty(Material, "LineStripDrawMode", {
  35130. /**
  35131. * Returns the line strip draw mode
  35132. */
  35133. get: function () {
  35134. return Material._LineStripDrawMode;
  35135. },
  35136. enumerable: true,
  35137. configurable: true
  35138. });
  35139. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35140. /**
  35141. * Returns the triangle strip draw mode
  35142. */
  35143. get: function () {
  35144. return Material._TriangleStripDrawMode;
  35145. },
  35146. enumerable: true,
  35147. configurable: true
  35148. });
  35149. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35150. /**
  35151. * Returns the triangle fan draw mode
  35152. */
  35153. get: function () {
  35154. return Material._TriangleFanDrawMode;
  35155. },
  35156. enumerable: true,
  35157. configurable: true
  35158. });
  35159. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35160. /**
  35161. * Returns the clock-wise side orientation
  35162. */
  35163. get: function () {
  35164. return Material._ClockWiseSideOrientation;
  35165. },
  35166. enumerable: true,
  35167. configurable: true
  35168. });
  35169. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35170. /**
  35171. * Returns the counter clock-wise side orientation
  35172. */
  35173. get: function () {
  35174. return Material._CounterClockWiseSideOrientation;
  35175. },
  35176. enumerable: true,
  35177. configurable: true
  35178. });
  35179. Object.defineProperty(Material.prototype, "alpha", {
  35180. /**
  35181. * Gets the alpha value of the material
  35182. */
  35183. get: function () {
  35184. return this._alpha;
  35185. },
  35186. /**
  35187. * Sets the alpha value of the material
  35188. */
  35189. set: function (value) {
  35190. if (this._alpha === value) {
  35191. return;
  35192. }
  35193. this._alpha = value;
  35194. this.markAsDirty(Material.MiscDirtyFlag);
  35195. },
  35196. enumerable: true,
  35197. configurable: true
  35198. });
  35199. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35200. /**
  35201. * Gets the back-face culling state
  35202. */
  35203. get: function () {
  35204. return this._backFaceCulling;
  35205. },
  35206. /**
  35207. * Sets the back-face culling state
  35208. */
  35209. set: function (value) {
  35210. if (this._backFaceCulling === value) {
  35211. return;
  35212. }
  35213. this._backFaceCulling = value;
  35214. this.markAsDirty(Material.TextureDirtyFlag);
  35215. },
  35216. enumerable: true,
  35217. configurable: true
  35218. });
  35219. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  35220. /**
  35221. * Gets a boolean indicating that current material needs to register RTT
  35222. */
  35223. get: function () {
  35224. return false;
  35225. },
  35226. enumerable: true,
  35227. configurable: true
  35228. });
  35229. Object.defineProperty(Material.prototype, "onDispose", {
  35230. /**
  35231. * Called during a dispose event
  35232. */
  35233. set: function (callback) {
  35234. if (this._onDisposeObserver) {
  35235. this.onDisposeObservable.remove(this._onDisposeObserver);
  35236. }
  35237. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35238. },
  35239. enumerable: true,
  35240. configurable: true
  35241. });
  35242. Object.defineProperty(Material.prototype, "onBindObservable", {
  35243. /**
  35244. * An event triggered when the material is bound
  35245. */
  35246. get: function () {
  35247. if (!this._onBindObservable) {
  35248. this._onBindObservable = new BABYLON.Observable();
  35249. }
  35250. return this._onBindObservable;
  35251. },
  35252. enumerable: true,
  35253. configurable: true
  35254. });
  35255. Object.defineProperty(Material.prototype, "onBind", {
  35256. /**
  35257. * Called during a bind event
  35258. */
  35259. set: function (callback) {
  35260. if (this._onBindObserver) {
  35261. this.onBindObservable.remove(this._onBindObserver);
  35262. }
  35263. this._onBindObserver = this.onBindObservable.add(callback);
  35264. },
  35265. enumerable: true,
  35266. configurable: true
  35267. });
  35268. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  35269. /**
  35270. * An event triggered when the material is unbound
  35271. */
  35272. get: function () {
  35273. if (!this._onUnBindObservable) {
  35274. this._onUnBindObservable = new BABYLON.Observable();
  35275. }
  35276. return this._onUnBindObservable;
  35277. },
  35278. enumerable: true,
  35279. configurable: true
  35280. });
  35281. Object.defineProperty(Material.prototype, "alphaMode", {
  35282. /**
  35283. * Gets the value of the alpha mode
  35284. */
  35285. get: function () {
  35286. return this._alphaMode;
  35287. },
  35288. /**
  35289. * Sets the value of the alpha mode.
  35290. *
  35291. * | Value | Type | Description |
  35292. * | --- | --- | --- |
  35293. * | 0 | ALPHA_DISABLE | |
  35294. * | 1 | ALPHA_ADD | |
  35295. * | 2 | ALPHA_COMBINE | |
  35296. * | 3 | ALPHA_SUBTRACT | |
  35297. * | 4 | ALPHA_MULTIPLY | |
  35298. * | 5 | ALPHA_MAXIMIZED | |
  35299. * | 6 | ALPHA_ONEONE | |
  35300. * | 7 | ALPHA_PREMULTIPLIED | |
  35301. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35302. * | 9 | ALPHA_INTERPOLATE | |
  35303. * | 10 | ALPHA_SCREENMODE | |
  35304. *
  35305. */
  35306. set: function (value) {
  35307. if (this._alphaMode === value) {
  35308. return;
  35309. }
  35310. this._alphaMode = value;
  35311. this.markAsDirty(Material.TextureDirtyFlag);
  35312. },
  35313. enumerable: true,
  35314. configurable: true
  35315. });
  35316. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35317. /**
  35318. * Gets the depth pre-pass value
  35319. */
  35320. get: function () {
  35321. return this._needDepthPrePass;
  35322. },
  35323. /**
  35324. * Sets the need depth pre-pass value
  35325. */
  35326. set: function (value) {
  35327. if (this._needDepthPrePass === value) {
  35328. return;
  35329. }
  35330. this._needDepthPrePass = value;
  35331. if (this._needDepthPrePass) {
  35332. this.checkReadyOnEveryCall = true;
  35333. }
  35334. },
  35335. enumerable: true,
  35336. configurable: true
  35337. });
  35338. Object.defineProperty(Material.prototype, "fogEnabled", {
  35339. /**
  35340. * Gets the value of the fog enabled state
  35341. */
  35342. get: function () {
  35343. return this._fogEnabled;
  35344. },
  35345. /**
  35346. * Sets the state for enabling fog
  35347. */
  35348. set: function (value) {
  35349. if (this._fogEnabled === value) {
  35350. return;
  35351. }
  35352. this._fogEnabled = value;
  35353. this.markAsDirty(Material.MiscDirtyFlag);
  35354. },
  35355. enumerable: true,
  35356. configurable: true
  35357. });
  35358. Object.defineProperty(Material.prototype, "wireframe", {
  35359. /**
  35360. * Gets a value specifying if wireframe mode is enabled
  35361. */
  35362. get: function () {
  35363. switch (this._fillMode) {
  35364. case Material.WireFrameFillMode:
  35365. case Material.LineListDrawMode:
  35366. case Material.LineLoopDrawMode:
  35367. case Material.LineStripDrawMode:
  35368. return true;
  35369. }
  35370. return this._scene.forceWireframe;
  35371. },
  35372. /**
  35373. * Sets the state of wireframe mode
  35374. */
  35375. set: function (value) {
  35376. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35377. },
  35378. enumerable: true,
  35379. configurable: true
  35380. });
  35381. Object.defineProperty(Material.prototype, "pointsCloud", {
  35382. /**
  35383. * Gets the value specifying if point clouds are enabled
  35384. */
  35385. get: function () {
  35386. switch (this._fillMode) {
  35387. case Material.PointFillMode:
  35388. case Material.PointListDrawMode:
  35389. return true;
  35390. }
  35391. return this._scene.forcePointsCloud;
  35392. },
  35393. /**
  35394. * Sets the state of point cloud mode
  35395. */
  35396. set: function (value) {
  35397. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35398. },
  35399. enumerable: true,
  35400. configurable: true
  35401. });
  35402. Object.defineProperty(Material.prototype, "fillMode", {
  35403. /**
  35404. * Gets the material fill mode
  35405. */
  35406. get: function () {
  35407. return this._fillMode;
  35408. },
  35409. /**
  35410. * Sets the material fill mode
  35411. */
  35412. set: function (value) {
  35413. if (this._fillMode === value) {
  35414. return;
  35415. }
  35416. this._fillMode = value;
  35417. this.markAsDirty(Material.MiscDirtyFlag);
  35418. },
  35419. enumerable: true,
  35420. configurable: true
  35421. });
  35422. /**
  35423. * Returns a string representation of the current material
  35424. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35425. * @returns a string with material information
  35426. */
  35427. Material.prototype.toString = function (fullDetails) {
  35428. var ret = "Name: " + this.name;
  35429. if (fullDetails) {
  35430. }
  35431. return ret;
  35432. };
  35433. /**
  35434. * Gets the class name of the material
  35435. * @returns a string with the class name of the material
  35436. */
  35437. Material.prototype.getClassName = function () {
  35438. return "Material";
  35439. };
  35440. Object.defineProperty(Material.prototype, "isFrozen", {
  35441. /**
  35442. * Specifies if updates for the material been locked
  35443. */
  35444. get: function () {
  35445. return this.checkReadyOnlyOnce;
  35446. },
  35447. enumerable: true,
  35448. configurable: true
  35449. });
  35450. /**
  35451. * Locks updates for the material
  35452. */
  35453. Material.prototype.freeze = function () {
  35454. this.checkReadyOnlyOnce = true;
  35455. };
  35456. /**
  35457. * Unlocks updates for the material
  35458. */
  35459. Material.prototype.unfreeze = function () {
  35460. this.checkReadyOnlyOnce = false;
  35461. };
  35462. /**
  35463. * Specifies if the material is ready to be used
  35464. * @param mesh defines the mesh to check
  35465. * @param useInstances specifies if instances should be used
  35466. * @returns a boolean indicating if the material is ready to be used
  35467. */
  35468. Material.prototype.isReady = function (mesh, useInstances) {
  35469. return true;
  35470. };
  35471. /**
  35472. * Specifies that the submesh is ready to be used
  35473. * @param mesh defines the mesh to check
  35474. * @param subMesh defines which submesh to check
  35475. * @param useInstances specifies that instances should be used
  35476. * @returns a boolean indicating that the submesh is ready or not
  35477. */
  35478. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35479. return false;
  35480. };
  35481. /**
  35482. * Returns the material effect
  35483. * @returns the effect associated with the material
  35484. */
  35485. Material.prototype.getEffect = function () {
  35486. return this._effect;
  35487. };
  35488. /**
  35489. * Returns the current scene
  35490. * @returns a Scene
  35491. */
  35492. Material.prototype.getScene = function () {
  35493. return this._scene;
  35494. };
  35495. /**
  35496. * Specifies if the material will require alpha blending
  35497. * @returns a boolean specifying if alpha blending is needed
  35498. */
  35499. Material.prototype.needAlphaBlending = function () {
  35500. return (this.alpha < 1.0);
  35501. };
  35502. /**
  35503. * Specifies if the mesh will require alpha blending
  35504. * @param mesh defines the mesh to check
  35505. * @returns a boolean specifying if alpha blending is needed for the mesh
  35506. */
  35507. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35508. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35509. };
  35510. /**
  35511. * Specifies if this material should be rendered in alpha test mode
  35512. * @returns a boolean specifying if an alpha test is needed.
  35513. */
  35514. Material.prototype.needAlphaTesting = function () {
  35515. return false;
  35516. };
  35517. /**
  35518. * Gets the texture used for the alpha test
  35519. * @returns the texture to use for alpha testing
  35520. */
  35521. Material.prototype.getAlphaTestTexture = function () {
  35522. return null;
  35523. };
  35524. /**
  35525. * Marks the material to indicate that it needs to be re-calculated
  35526. */
  35527. Material.prototype.markDirty = function () {
  35528. this._wasPreviouslyReady = false;
  35529. };
  35530. /** @hidden */
  35531. Material.prototype._preBind = function (effect, overrideOrientation) {
  35532. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35533. var engine = this._scene.getEngine();
  35534. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35535. var reverse = orientation === Material.ClockWiseSideOrientation;
  35536. engine.enableEffect(effect ? effect : this._effect);
  35537. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35538. return reverse;
  35539. };
  35540. /**
  35541. * Binds the material to the mesh
  35542. * @param world defines the world transformation matrix
  35543. * @param mesh defines the mesh to bind the material to
  35544. */
  35545. Material.prototype.bind = function (world, mesh) {
  35546. };
  35547. /**
  35548. * Binds the submesh to the material
  35549. * @param world defines the world transformation matrix
  35550. * @param mesh defines the mesh containing the submesh
  35551. * @param subMesh defines the submesh to bind the material to
  35552. */
  35553. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35554. };
  35555. /**
  35556. * Binds the world matrix to the material
  35557. * @param world defines the world transformation matrix
  35558. */
  35559. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35560. };
  35561. /**
  35562. * Binds the scene's uniform buffer to the effect.
  35563. * @param effect defines the effect to bind to the scene uniform buffer
  35564. * @param sceneUbo defines the uniform buffer storing scene data
  35565. */
  35566. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35567. sceneUbo.bindToEffect(effect, "Scene");
  35568. };
  35569. /**
  35570. * Binds the view matrix to the effect
  35571. * @param effect defines the effect to bind the view matrix to
  35572. */
  35573. Material.prototype.bindView = function (effect) {
  35574. if (!this._useUBO) {
  35575. effect.setMatrix("view", this.getScene().getViewMatrix());
  35576. }
  35577. else {
  35578. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35579. }
  35580. };
  35581. /**
  35582. * Binds the view projection matrix to the effect
  35583. * @param effect defines the effect to bind the view projection matrix to
  35584. */
  35585. Material.prototype.bindViewProjection = function (effect) {
  35586. if (!this._useUBO) {
  35587. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35588. }
  35589. else {
  35590. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35591. }
  35592. };
  35593. /**
  35594. * Specifies if material alpha testing should be turned on for the mesh
  35595. * @param mesh defines the mesh to check
  35596. */
  35597. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35598. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35599. };
  35600. /**
  35601. * Processes to execute after binding the material to a mesh
  35602. * @param mesh defines the rendered mesh
  35603. */
  35604. Material.prototype._afterBind = function (mesh) {
  35605. this._scene._cachedMaterial = this;
  35606. if (mesh) {
  35607. this._scene._cachedVisibility = mesh.visibility;
  35608. }
  35609. else {
  35610. this._scene._cachedVisibility = 1;
  35611. }
  35612. if (this._onBindObservable && mesh) {
  35613. this._onBindObservable.notifyObservers(mesh);
  35614. }
  35615. if (this.disableDepthWrite) {
  35616. var engine = this._scene.getEngine();
  35617. this._cachedDepthWriteState = engine.getDepthWrite();
  35618. engine.setDepthWrite(false);
  35619. }
  35620. };
  35621. /**
  35622. * Unbinds the material from the mesh
  35623. */
  35624. Material.prototype.unbind = function () {
  35625. if (this._onUnBindObservable) {
  35626. this._onUnBindObservable.notifyObservers(this);
  35627. }
  35628. if (this.disableDepthWrite) {
  35629. var engine = this._scene.getEngine();
  35630. engine.setDepthWrite(this._cachedDepthWriteState);
  35631. }
  35632. };
  35633. /**
  35634. * Gets the active textures from the material
  35635. * @returns an array of textures
  35636. */
  35637. Material.prototype.getActiveTextures = function () {
  35638. return [];
  35639. };
  35640. /**
  35641. * Specifies if the material uses a texture
  35642. * @param texture defines the texture to check against the material
  35643. * @returns a boolean specifying if the material uses the texture
  35644. */
  35645. Material.prototype.hasTexture = function (texture) {
  35646. return false;
  35647. };
  35648. /**
  35649. * Makes a duplicate of the material, and gives it a new name
  35650. * @param name defines the new name for the duplicated material
  35651. * @returns the cloned material
  35652. */
  35653. Material.prototype.clone = function (name) {
  35654. return null;
  35655. };
  35656. /**
  35657. * Gets the meshes bound to the material
  35658. * @returns an array of meshes bound to the material
  35659. */
  35660. Material.prototype.getBindedMeshes = function () {
  35661. var result = new Array();
  35662. for (var index = 0; index < this._scene.meshes.length; index++) {
  35663. var mesh = this._scene.meshes[index];
  35664. if (mesh.material === this) {
  35665. result.push(mesh);
  35666. }
  35667. }
  35668. return result;
  35669. };
  35670. /**
  35671. * Force shader compilation
  35672. * @param mesh defines the mesh associated with this material
  35673. * @param onCompiled defines a function to execute once the material is compiled
  35674. * @param options defines the options to configure the compilation
  35675. */
  35676. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35677. var _this = this;
  35678. var localOptions = __assign({ clipPlane: false }, options);
  35679. var subMesh = new BABYLON.BaseSubMesh();
  35680. var scene = this.getScene();
  35681. var checkReady = function () {
  35682. if (!_this._scene || !_this._scene.getEngine()) {
  35683. return;
  35684. }
  35685. if (subMesh._materialDefines) {
  35686. subMesh._materialDefines._renderId = -1;
  35687. }
  35688. var clipPlaneState = scene.clipPlane;
  35689. if (localOptions.clipPlane) {
  35690. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35691. }
  35692. if (_this.storeEffectOnSubMeshes) {
  35693. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35694. if (onCompiled) {
  35695. onCompiled(_this);
  35696. }
  35697. }
  35698. else {
  35699. setTimeout(checkReady, 16);
  35700. }
  35701. }
  35702. else {
  35703. if (_this.isReady(mesh)) {
  35704. if (onCompiled) {
  35705. onCompiled(_this);
  35706. }
  35707. }
  35708. else {
  35709. setTimeout(checkReady, 16);
  35710. }
  35711. }
  35712. if (localOptions.clipPlane) {
  35713. scene.clipPlane = clipPlaneState;
  35714. }
  35715. };
  35716. checkReady();
  35717. };
  35718. /**
  35719. * Force shader compilation
  35720. * @param mesh defines the mesh that will use this material
  35721. * @param options defines additional options for compiling the shaders
  35722. * @returns a promise that resolves when the compilation completes
  35723. */
  35724. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35725. var _this = this;
  35726. return new Promise(function (resolve) {
  35727. _this.forceCompilation(mesh, function () {
  35728. resolve();
  35729. }, options);
  35730. });
  35731. };
  35732. /**
  35733. * Marks a define in the material to indicate that it needs to be re-computed
  35734. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35735. */
  35736. Material.prototype.markAsDirty = function (flag) {
  35737. if (flag & Material.TextureDirtyFlag) {
  35738. this._markAllSubMeshesAsTexturesDirty();
  35739. }
  35740. if (flag & Material.LightDirtyFlag) {
  35741. this._markAllSubMeshesAsLightsDirty();
  35742. }
  35743. if (flag & Material.FresnelDirtyFlag) {
  35744. this._markAllSubMeshesAsFresnelDirty();
  35745. }
  35746. if (flag & Material.AttributesDirtyFlag) {
  35747. this._markAllSubMeshesAsAttributesDirty();
  35748. }
  35749. if (flag & Material.MiscDirtyFlag) {
  35750. this._markAllSubMeshesAsMiscDirty();
  35751. }
  35752. this.getScene().resetCachedMaterial();
  35753. };
  35754. /**
  35755. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35756. * @param func defines a function which checks material defines against the submeshes
  35757. */
  35758. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35759. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35760. var mesh = _a[_i];
  35761. if (!mesh.subMeshes) {
  35762. continue;
  35763. }
  35764. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35765. var subMesh = _c[_b];
  35766. if (subMesh.getMaterial() !== this) {
  35767. continue;
  35768. }
  35769. if (!subMesh._materialDefines) {
  35770. continue;
  35771. }
  35772. func(subMesh._materialDefines);
  35773. }
  35774. }
  35775. };
  35776. /**
  35777. * Indicates that image processing needs to be re-calculated for all submeshes
  35778. */
  35779. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35780. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35781. };
  35782. /**
  35783. * Indicates that textures need to be re-calculated for all submeshes
  35784. */
  35785. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35786. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35787. };
  35788. /**
  35789. * Indicates that fresnel needs to be re-calculated for all submeshes
  35790. */
  35791. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35792. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35793. };
  35794. /**
  35795. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35796. */
  35797. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35798. this._markAllSubMeshesAsDirty(function (defines) {
  35799. defines.markAsFresnelDirty();
  35800. defines.markAsMiscDirty();
  35801. });
  35802. };
  35803. /**
  35804. * Indicates that lights need to be re-calculated for all submeshes
  35805. */
  35806. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35807. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35808. };
  35809. /**
  35810. * Indicates that attributes need to be re-calculated for all submeshes
  35811. */
  35812. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35813. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35814. };
  35815. /**
  35816. * Indicates that misc needs to be re-calculated for all submeshes
  35817. */
  35818. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35819. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35820. };
  35821. /**
  35822. * Indicates that textures and misc need to be re-calculated for all submeshes
  35823. */
  35824. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35825. this._markAllSubMeshesAsDirty(function (defines) {
  35826. defines.markAsTexturesDirty();
  35827. defines.markAsMiscDirty();
  35828. });
  35829. };
  35830. /**
  35831. * Disposes the material
  35832. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35833. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35834. */
  35835. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35836. // Animations
  35837. this.getScene().stopAnimation(this);
  35838. this.getScene().freeProcessedMaterials();
  35839. // Remove from scene
  35840. var index = this._scene.materials.indexOf(this);
  35841. if (index >= 0) {
  35842. this._scene.materials.splice(index, 1);
  35843. }
  35844. this._scene.onMaterialRemovedObservable.notifyObservers(this);
  35845. // Remove from meshes
  35846. for (index = 0; index < this._scene.meshes.length; index++) {
  35847. var mesh = this._scene.meshes[index];
  35848. if (mesh.material === this) {
  35849. mesh.material = null;
  35850. if (mesh.geometry) {
  35851. var geometry = (mesh.geometry);
  35852. if (this.storeEffectOnSubMeshes) {
  35853. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35854. var subMesh = _a[_i];
  35855. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35856. if (forceDisposeEffect && subMesh._materialEffect) {
  35857. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35858. }
  35859. }
  35860. }
  35861. else {
  35862. geometry._releaseVertexArrayObject(this._effect);
  35863. }
  35864. }
  35865. }
  35866. }
  35867. this._uniformBuffer.dispose();
  35868. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35869. if (forceDisposeEffect && this._effect) {
  35870. if (!this.storeEffectOnSubMeshes) {
  35871. this._scene.getEngine()._releaseEffect(this._effect);
  35872. }
  35873. this._effect = null;
  35874. }
  35875. // Callback
  35876. this.onDisposeObservable.notifyObservers(this);
  35877. this.onDisposeObservable.clear();
  35878. if (this._onBindObservable) {
  35879. this._onBindObservable.clear();
  35880. }
  35881. if (this._onUnBindObservable) {
  35882. this._onUnBindObservable.clear();
  35883. }
  35884. };
  35885. /**
  35886. * Serializes this material
  35887. * @returns the serialized material object
  35888. */
  35889. Material.prototype.serialize = function () {
  35890. return BABYLON.SerializationHelper.Serialize(this);
  35891. };
  35892. /**
  35893. * Creates a MultiMaterial from parsed MultiMaterial data.
  35894. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35895. * @param scene defines the hosting scene
  35896. * @returns a new MultiMaterial
  35897. */
  35898. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35899. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35900. multiMaterial.id = parsedMultiMaterial.id;
  35901. if (BABYLON.Tags) {
  35902. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35903. }
  35904. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35905. var subMatId = parsedMultiMaterial.materials[matIndex];
  35906. if (subMatId) {
  35907. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35908. }
  35909. else {
  35910. multiMaterial.subMaterials.push(null);
  35911. }
  35912. }
  35913. return multiMaterial;
  35914. };
  35915. /**
  35916. * Creates a material from parsed material data
  35917. * @param parsedMaterial defines parsed material data
  35918. * @param scene defines the hosting scene
  35919. * @param rootUrl defines the root URL to use to load textures
  35920. * @returns a new material
  35921. */
  35922. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35923. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35924. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35925. }
  35926. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35927. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35928. if (!BABYLON.LegacyPBRMaterial) {
  35929. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35930. return;
  35931. }
  35932. }
  35933. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35934. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35935. };
  35936. // Triangle views
  35937. Material._TriangleFillMode = 0;
  35938. Material._WireFrameFillMode = 1;
  35939. Material._PointFillMode = 2;
  35940. // Draw modes
  35941. Material._PointListDrawMode = 3;
  35942. Material._LineListDrawMode = 4;
  35943. Material._LineLoopDrawMode = 5;
  35944. Material._LineStripDrawMode = 6;
  35945. Material._TriangleStripDrawMode = 7;
  35946. Material._TriangleFanDrawMode = 8;
  35947. /**
  35948. * Stores the clock-wise side orientation
  35949. */
  35950. Material._ClockWiseSideOrientation = 0;
  35951. /**
  35952. * Stores the counter clock-wise side orientation
  35953. */
  35954. Material._CounterClockWiseSideOrientation = 1;
  35955. /**
  35956. * The dirty texture flag value
  35957. */
  35958. Material.TextureDirtyFlag = 1;
  35959. /**
  35960. * The dirty light flag value
  35961. */
  35962. Material.LightDirtyFlag = 2;
  35963. /**
  35964. * The dirty fresnel flag value
  35965. */
  35966. Material.FresnelDirtyFlag = 4;
  35967. /**
  35968. * The dirty attribute flag value
  35969. */
  35970. Material.AttributesDirtyFlag = 8;
  35971. /**
  35972. * The dirty misc flag value
  35973. */
  35974. Material.MiscDirtyFlag = 16;
  35975. /**
  35976. * The all dirty flag value
  35977. */
  35978. Material.AllDirtyFlag = 31;
  35979. __decorate([
  35980. BABYLON.serialize()
  35981. ], Material.prototype, "id", void 0);
  35982. __decorate([
  35983. BABYLON.serialize()
  35984. ], Material.prototype, "uniqueId", void 0);
  35985. __decorate([
  35986. BABYLON.serialize()
  35987. ], Material.prototype, "name", void 0);
  35988. __decorate([
  35989. BABYLON.serialize()
  35990. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35991. __decorate([
  35992. BABYLON.serialize()
  35993. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35994. __decorate([
  35995. BABYLON.serialize()
  35996. ], Material.prototype, "state", void 0);
  35997. __decorate([
  35998. BABYLON.serialize("alpha")
  35999. ], Material.prototype, "_alpha", void 0);
  36000. __decorate([
  36001. BABYLON.serialize("backFaceCulling")
  36002. ], Material.prototype, "_backFaceCulling", void 0);
  36003. __decorate([
  36004. BABYLON.serialize()
  36005. ], Material.prototype, "sideOrientation", void 0);
  36006. __decorate([
  36007. BABYLON.serialize("alphaMode")
  36008. ], Material.prototype, "_alphaMode", void 0);
  36009. __decorate([
  36010. BABYLON.serialize()
  36011. ], Material.prototype, "_needDepthPrePass", void 0);
  36012. __decorate([
  36013. BABYLON.serialize()
  36014. ], Material.prototype, "disableDepthWrite", void 0);
  36015. __decorate([
  36016. BABYLON.serialize()
  36017. ], Material.prototype, "forceDepthWrite", void 0);
  36018. __decorate([
  36019. BABYLON.serialize()
  36020. ], Material.prototype, "separateCullingPass", void 0);
  36021. __decorate([
  36022. BABYLON.serialize("fogEnabled")
  36023. ], Material.prototype, "_fogEnabled", void 0);
  36024. __decorate([
  36025. BABYLON.serialize()
  36026. ], Material.prototype, "pointSize", void 0);
  36027. __decorate([
  36028. BABYLON.serialize()
  36029. ], Material.prototype, "zOffset", void 0);
  36030. __decorate([
  36031. BABYLON.serialize()
  36032. ], Material.prototype, "wireframe", null);
  36033. __decorate([
  36034. BABYLON.serialize()
  36035. ], Material.prototype, "pointsCloud", null);
  36036. __decorate([
  36037. BABYLON.serialize()
  36038. ], Material.prototype, "fillMode", null);
  36039. return Material;
  36040. }());
  36041. BABYLON.Material = Material;
  36042. })(BABYLON || (BABYLON = {}));
  36043. //# sourceMappingURL=babylon.material.js.map
  36044. var BABYLON;
  36045. (function (BABYLON) {
  36046. var UniformBuffer = /** @class */ (function () {
  36047. /**
  36048. * Uniform buffer objects.
  36049. *
  36050. * Handles blocks of uniform on the GPU.
  36051. *
  36052. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36053. *
  36054. * For more information, please refer to :
  36055. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36056. */
  36057. function UniformBuffer(engine, data, dynamic) {
  36058. this._engine = engine;
  36059. this._noUBO = !engine.supportsUniformBuffers;
  36060. this._dynamic = dynamic;
  36061. this._data = data || [];
  36062. this._uniformLocations = {};
  36063. this._uniformSizes = {};
  36064. this._uniformLocationPointer = 0;
  36065. this._needSync = false;
  36066. if (this._noUBO) {
  36067. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36068. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36069. this.updateFloat = this._updateFloatForEffect;
  36070. this.updateFloat2 = this._updateFloat2ForEffect;
  36071. this.updateFloat3 = this._updateFloat3ForEffect;
  36072. this.updateFloat4 = this._updateFloat4ForEffect;
  36073. this.updateMatrix = this._updateMatrixForEffect;
  36074. this.updateVector3 = this._updateVector3ForEffect;
  36075. this.updateVector4 = this._updateVector4ForEffect;
  36076. this.updateColor3 = this._updateColor3ForEffect;
  36077. this.updateColor4 = this._updateColor4ForEffect;
  36078. }
  36079. else {
  36080. this._engine._uniformBuffers.push(this);
  36081. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36082. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36083. this.updateFloat = this._updateFloatForUniform;
  36084. this.updateFloat2 = this._updateFloat2ForUniform;
  36085. this.updateFloat3 = this._updateFloat3ForUniform;
  36086. this.updateFloat4 = this._updateFloat4ForUniform;
  36087. this.updateMatrix = this._updateMatrixForUniform;
  36088. this.updateVector3 = this._updateVector3ForUniform;
  36089. this.updateVector4 = this._updateVector4ForUniform;
  36090. this.updateColor3 = this._updateColor3ForUniform;
  36091. this.updateColor4 = this._updateColor4ForUniform;
  36092. }
  36093. }
  36094. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36095. // Properties
  36096. /**
  36097. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36098. * or just falling back on setUniformXXX calls.
  36099. */
  36100. get: function () {
  36101. return !this._noUBO;
  36102. },
  36103. enumerable: true,
  36104. configurable: true
  36105. });
  36106. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36107. /**
  36108. * Indicates if the WebGL underlying uniform buffer is in sync
  36109. * with the javascript cache data.
  36110. */
  36111. get: function () {
  36112. return !this._needSync;
  36113. },
  36114. enumerable: true,
  36115. configurable: true
  36116. });
  36117. /**
  36118. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36119. * Also, a dynamic UniformBuffer will disable cache verification and always
  36120. * update the underlying WebGL uniform buffer to the GPU.
  36121. */
  36122. UniformBuffer.prototype.isDynamic = function () {
  36123. return this._dynamic !== undefined;
  36124. };
  36125. /**
  36126. * The data cache on JS side.
  36127. */
  36128. UniformBuffer.prototype.getData = function () {
  36129. return this._bufferData;
  36130. };
  36131. /**
  36132. * The underlying WebGL Uniform buffer.
  36133. */
  36134. UniformBuffer.prototype.getBuffer = function () {
  36135. return this._buffer;
  36136. };
  36137. /**
  36138. * std140 layout specifies how to align data within an UBO structure.
  36139. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36140. * for specs.
  36141. */
  36142. UniformBuffer.prototype._fillAlignment = function (size) {
  36143. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36144. // and 4x4 matrices
  36145. // TODO : change if other types are used
  36146. var alignment;
  36147. if (size <= 2) {
  36148. alignment = size;
  36149. }
  36150. else {
  36151. alignment = 4;
  36152. }
  36153. if ((this._uniformLocationPointer % alignment) !== 0) {
  36154. var oldPointer = this._uniformLocationPointer;
  36155. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36156. var diff = this._uniformLocationPointer - oldPointer;
  36157. for (var i = 0; i < diff; i++) {
  36158. this._data.push(0);
  36159. }
  36160. }
  36161. };
  36162. /**
  36163. * Adds an uniform in the buffer.
  36164. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36165. * for the layout to be correct !
  36166. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36167. * @param {number|number[]} size Data size, or data directly.
  36168. */
  36169. UniformBuffer.prototype.addUniform = function (name, size) {
  36170. if (this._noUBO) {
  36171. return;
  36172. }
  36173. if (this._uniformLocations[name] !== undefined) {
  36174. // Already existing uniform
  36175. return;
  36176. }
  36177. // This function must be called in the order of the shader layout !
  36178. // size can be the size of the uniform, or data directly
  36179. var data;
  36180. if (size instanceof Array) {
  36181. data = size;
  36182. size = data.length;
  36183. }
  36184. else {
  36185. size = size;
  36186. data = [];
  36187. // Fill with zeros
  36188. for (var i = 0; i < size; i++) {
  36189. data.push(0);
  36190. }
  36191. }
  36192. this._fillAlignment(size);
  36193. this._uniformSizes[name] = size;
  36194. this._uniformLocations[name] = this._uniformLocationPointer;
  36195. this._uniformLocationPointer += size;
  36196. for (var i = 0; i < size; i++) {
  36197. this._data.push(data[i]);
  36198. }
  36199. this._needSync = true;
  36200. };
  36201. /**
  36202. * Wrapper for addUniform.
  36203. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36204. * @param {Matrix} mat A 4x4 matrix.
  36205. */
  36206. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36207. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36208. };
  36209. /**
  36210. * Wrapper for addUniform.
  36211. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36212. * @param {number} x
  36213. * @param {number} y
  36214. */
  36215. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36216. var temp = [x, y];
  36217. this.addUniform(name, temp);
  36218. };
  36219. /**
  36220. * Wrapper for addUniform.
  36221. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36222. * @param {number} x
  36223. * @param {number} y
  36224. * @param {number} z
  36225. */
  36226. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36227. var temp = [x, y, z];
  36228. this.addUniform(name, temp);
  36229. };
  36230. /**
  36231. * Wrapper for addUniform.
  36232. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36233. * @param {Color3} color
  36234. */
  36235. UniformBuffer.prototype.addColor3 = function (name, color) {
  36236. var temp = new Array();
  36237. color.toArray(temp);
  36238. this.addUniform(name, temp);
  36239. };
  36240. /**
  36241. * Wrapper for addUniform.
  36242. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36243. * @param {Color3} color
  36244. * @param {number} alpha
  36245. */
  36246. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36247. var temp = new Array();
  36248. color.toArray(temp);
  36249. temp.push(alpha);
  36250. this.addUniform(name, temp);
  36251. };
  36252. /**
  36253. * Wrapper for addUniform.
  36254. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36255. * @param {Vector3} vector
  36256. */
  36257. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36258. var temp = new Array();
  36259. vector.toArray(temp);
  36260. this.addUniform(name, temp);
  36261. };
  36262. /**
  36263. * Wrapper for addUniform.
  36264. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36265. */
  36266. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36267. this.addUniform(name, 12);
  36268. };
  36269. /**
  36270. * Wrapper for addUniform.
  36271. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36272. */
  36273. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36274. this.addUniform(name, 8);
  36275. };
  36276. /**
  36277. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36278. */
  36279. UniformBuffer.prototype.create = function () {
  36280. if (this._noUBO) {
  36281. return;
  36282. }
  36283. if (this._buffer) {
  36284. return; // nothing to do
  36285. }
  36286. // See spec, alignment must be filled as a vec4
  36287. this._fillAlignment(4);
  36288. this._bufferData = new Float32Array(this._data);
  36289. this._rebuild();
  36290. this._needSync = true;
  36291. };
  36292. /** @hidden */
  36293. UniformBuffer.prototype._rebuild = function () {
  36294. if (this._noUBO) {
  36295. return;
  36296. }
  36297. if (this._dynamic) {
  36298. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36299. }
  36300. else {
  36301. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36302. }
  36303. };
  36304. /**
  36305. * Updates the WebGL Uniform Buffer on the GPU.
  36306. * If the `dynamic` flag is set to true, no cache comparison is done.
  36307. * Otherwise, the buffer will be updated only if the cache differs.
  36308. */
  36309. UniformBuffer.prototype.update = function () {
  36310. if (!this._buffer) {
  36311. this.create();
  36312. return;
  36313. }
  36314. if (!this._dynamic && !this._needSync) {
  36315. return;
  36316. }
  36317. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36318. this._needSync = false;
  36319. };
  36320. /**
  36321. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36322. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36323. * @param {number[]|Float32Array} data Flattened data
  36324. * @param {number} size Size of the data.
  36325. */
  36326. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36327. var location = this._uniformLocations[uniformName];
  36328. if (location === undefined) {
  36329. if (this._buffer) {
  36330. // Cannot add an uniform if the buffer is already created
  36331. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36332. return;
  36333. }
  36334. this.addUniform(uniformName, size);
  36335. location = this._uniformLocations[uniformName];
  36336. }
  36337. if (!this._buffer) {
  36338. this.create();
  36339. }
  36340. if (!this._dynamic) {
  36341. // Cache for static uniform buffers
  36342. var changed = false;
  36343. for (var i = 0; i < size; i++) {
  36344. if (this._bufferData[location + i] !== data[i]) {
  36345. changed = true;
  36346. this._bufferData[location + i] = data[i];
  36347. }
  36348. }
  36349. this._needSync = this._needSync || changed;
  36350. }
  36351. else {
  36352. // No cache for dynamic
  36353. for (var i = 0; i < size; i++) {
  36354. this._bufferData[location + i] = data[i];
  36355. }
  36356. }
  36357. };
  36358. // Update methods
  36359. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36360. // To match std140, matrix must be realigned
  36361. for (var i = 0; i < 3; i++) {
  36362. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36363. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36364. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36365. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36366. }
  36367. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36368. };
  36369. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36370. this._currentEffect.setMatrix3x3(name, matrix);
  36371. };
  36372. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36373. this._currentEffect.setMatrix2x2(name, matrix);
  36374. };
  36375. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36376. // To match std140, matrix must be realigned
  36377. for (var i = 0; i < 2; i++) {
  36378. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36379. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36380. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36381. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36382. }
  36383. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36384. };
  36385. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36386. this._currentEffect.setFloat(name, x);
  36387. };
  36388. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36389. UniformBuffer._tempBuffer[0] = x;
  36390. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36391. };
  36392. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36393. if (suffix === void 0) { suffix = ""; }
  36394. this._currentEffect.setFloat2(name + suffix, x, y);
  36395. };
  36396. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36397. if (suffix === void 0) { suffix = ""; }
  36398. UniformBuffer._tempBuffer[0] = x;
  36399. UniformBuffer._tempBuffer[1] = y;
  36400. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36401. };
  36402. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36403. if (suffix === void 0) { suffix = ""; }
  36404. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36405. };
  36406. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36407. if (suffix === void 0) { suffix = ""; }
  36408. UniformBuffer._tempBuffer[0] = x;
  36409. UniformBuffer._tempBuffer[1] = y;
  36410. UniformBuffer._tempBuffer[2] = z;
  36411. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36412. };
  36413. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36414. if (suffix === void 0) { suffix = ""; }
  36415. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36416. };
  36417. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36418. if (suffix === void 0) { suffix = ""; }
  36419. UniformBuffer._tempBuffer[0] = x;
  36420. UniformBuffer._tempBuffer[1] = y;
  36421. UniformBuffer._tempBuffer[2] = z;
  36422. UniformBuffer._tempBuffer[3] = w;
  36423. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36424. };
  36425. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36426. this._currentEffect.setMatrix(name, mat);
  36427. };
  36428. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36429. this.updateUniform(name, mat.toArray(), 16);
  36430. };
  36431. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36432. this._currentEffect.setVector3(name, vector);
  36433. };
  36434. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36435. vector.toArray(UniformBuffer._tempBuffer);
  36436. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36437. };
  36438. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36439. this._currentEffect.setVector4(name, vector);
  36440. };
  36441. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36442. vector.toArray(UniformBuffer._tempBuffer);
  36443. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36444. };
  36445. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36446. if (suffix === void 0) { suffix = ""; }
  36447. this._currentEffect.setColor3(name + suffix, color);
  36448. };
  36449. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36450. if (suffix === void 0) { suffix = ""; }
  36451. color.toArray(UniformBuffer._tempBuffer);
  36452. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36453. };
  36454. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36455. if (suffix === void 0) { suffix = ""; }
  36456. this._currentEffect.setColor4(name + suffix, color, alpha);
  36457. };
  36458. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36459. if (suffix === void 0) { suffix = ""; }
  36460. color.toArray(UniformBuffer._tempBuffer);
  36461. UniformBuffer._tempBuffer[3] = alpha;
  36462. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36463. };
  36464. /**
  36465. * Sets a sampler uniform on the effect.
  36466. * @param {string} name Name of the sampler.
  36467. * @param {Texture} texture
  36468. */
  36469. UniformBuffer.prototype.setTexture = function (name, texture) {
  36470. this._currentEffect.setTexture(name, texture);
  36471. };
  36472. /**
  36473. * Directly updates the value of the uniform in the cache AND on the GPU.
  36474. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36475. * @param {number[]|Float32Array} data Flattened data
  36476. */
  36477. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36478. this.updateUniform(uniformName, data, data.length);
  36479. this.update();
  36480. };
  36481. /**
  36482. * Binds this uniform buffer to an effect.
  36483. * @param {Effect} effect
  36484. * @param {string} name Name of the uniform block in the shader.
  36485. */
  36486. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36487. this._currentEffect = effect;
  36488. if (this._noUBO || !this._buffer) {
  36489. return;
  36490. }
  36491. effect.bindUniformBuffer(this._buffer, name);
  36492. };
  36493. /**
  36494. * Disposes the uniform buffer.
  36495. */
  36496. UniformBuffer.prototype.dispose = function () {
  36497. if (this._noUBO) {
  36498. return;
  36499. }
  36500. var index = this._engine._uniformBuffers.indexOf(this);
  36501. if (index !== -1) {
  36502. this._engine._uniformBuffers.splice(index, 1);
  36503. }
  36504. if (!this._buffer) {
  36505. return;
  36506. }
  36507. if (this._engine._releaseBuffer(this._buffer)) {
  36508. this._buffer = null;
  36509. }
  36510. };
  36511. // Pool for avoiding memory leaks
  36512. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36513. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36514. return UniformBuffer;
  36515. }());
  36516. BABYLON.UniformBuffer = UniformBuffer;
  36517. })(BABYLON || (BABYLON = {}));
  36518. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36519. var BABYLON;
  36520. (function (BABYLON) {
  36521. /**
  36522. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36523. */
  36524. var VertexData = /** @class */ (function () {
  36525. function VertexData() {
  36526. }
  36527. /**
  36528. * Uses the passed data array to set the set the values for the specified kind of data
  36529. * @param data a linear array of floating numbers
  36530. * @param kind the type of data that is being set, eg positions, colors etc
  36531. */
  36532. VertexData.prototype.set = function (data, kind) {
  36533. switch (kind) {
  36534. case BABYLON.VertexBuffer.PositionKind:
  36535. this.positions = data;
  36536. break;
  36537. case BABYLON.VertexBuffer.NormalKind:
  36538. this.normals = data;
  36539. break;
  36540. case BABYLON.VertexBuffer.TangentKind:
  36541. this.tangents = data;
  36542. break;
  36543. case BABYLON.VertexBuffer.UVKind:
  36544. this.uvs = data;
  36545. break;
  36546. case BABYLON.VertexBuffer.UV2Kind:
  36547. this.uvs2 = data;
  36548. break;
  36549. case BABYLON.VertexBuffer.UV3Kind:
  36550. this.uvs3 = data;
  36551. break;
  36552. case BABYLON.VertexBuffer.UV4Kind:
  36553. this.uvs4 = data;
  36554. break;
  36555. case BABYLON.VertexBuffer.UV5Kind:
  36556. this.uvs5 = data;
  36557. break;
  36558. case BABYLON.VertexBuffer.UV6Kind:
  36559. this.uvs6 = data;
  36560. break;
  36561. case BABYLON.VertexBuffer.ColorKind:
  36562. this.colors = data;
  36563. break;
  36564. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36565. this.matricesIndices = data;
  36566. break;
  36567. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36568. this.matricesWeights = data;
  36569. break;
  36570. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36571. this.matricesIndicesExtra = data;
  36572. break;
  36573. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36574. this.matricesWeightsExtra = data;
  36575. break;
  36576. }
  36577. };
  36578. /**
  36579. * Associates the vertexData to the passed Mesh.
  36580. * Sets it as updatable or not (default `false`)
  36581. * @param mesh the mesh the vertexData is applied to
  36582. * @param updatable when used and having the value true allows new data to update the vertexData
  36583. * @returns the VertexData
  36584. */
  36585. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36586. this._applyTo(mesh, updatable);
  36587. return this;
  36588. };
  36589. /**
  36590. * Associates the vertexData to the passed Geometry.
  36591. * Sets it as updatable or not (default `false`)
  36592. * @param geometry the geometry the vertexData is applied to
  36593. * @param updatable when used and having the value true allows new data to update the vertexData
  36594. * @returns VertexData
  36595. */
  36596. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36597. this._applyTo(geometry, updatable);
  36598. return this;
  36599. };
  36600. /**
  36601. * Updates the associated mesh
  36602. * @param mesh the mesh to be updated
  36603. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36604. * @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
  36605. * @returns VertexData
  36606. */
  36607. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36608. this._update(mesh);
  36609. return this;
  36610. };
  36611. /**
  36612. * Updates the associated geometry
  36613. * @param geometry the geometry to be updated
  36614. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36615. * @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
  36616. * @returns VertexData.
  36617. */
  36618. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36619. this._update(geometry);
  36620. return this;
  36621. };
  36622. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36623. if (updatable === void 0) { updatable = false; }
  36624. if (this.positions) {
  36625. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36626. }
  36627. if (this.normals) {
  36628. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36629. }
  36630. if (this.tangents) {
  36631. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36632. }
  36633. if (this.uvs) {
  36634. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36635. }
  36636. if (this.uvs2) {
  36637. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36638. }
  36639. if (this.uvs3) {
  36640. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36641. }
  36642. if (this.uvs4) {
  36643. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36644. }
  36645. if (this.uvs5) {
  36646. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36647. }
  36648. if (this.uvs6) {
  36649. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36650. }
  36651. if (this.colors) {
  36652. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36653. }
  36654. if (this.matricesIndices) {
  36655. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36656. }
  36657. if (this.matricesWeights) {
  36658. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36659. }
  36660. if (this.matricesIndicesExtra) {
  36661. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36662. }
  36663. if (this.matricesWeightsExtra) {
  36664. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36665. }
  36666. if (this.indices) {
  36667. meshOrGeometry.setIndices(this.indices, null, updatable);
  36668. }
  36669. else {
  36670. meshOrGeometry.setIndices([], null);
  36671. }
  36672. return this;
  36673. };
  36674. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36675. if (this.positions) {
  36676. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36677. }
  36678. if (this.normals) {
  36679. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36680. }
  36681. if (this.tangents) {
  36682. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36683. }
  36684. if (this.uvs) {
  36685. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36686. }
  36687. if (this.uvs2) {
  36688. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36689. }
  36690. if (this.uvs3) {
  36691. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36692. }
  36693. if (this.uvs4) {
  36694. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36695. }
  36696. if (this.uvs5) {
  36697. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36698. }
  36699. if (this.uvs6) {
  36700. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36701. }
  36702. if (this.colors) {
  36703. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36704. }
  36705. if (this.matricesIndices) {
  36706. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36707. }
  36708. if (this.matricesWeights) {
  36709. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36710. }
  36711. if (this.matricesIndicesExtra) {
  36712. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36713. }
  36714. if (this.matricesWeightsExtra) {
  36715. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36716. }
  36717. if (this.indices) {
  36718. meshOrGeometry.setIndices(this.indices, null);
  36719. }
  36720. return this;
  36721. };
  36722. /**
  36723. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36724. * @param matrix the transforming matrix
  36725. * @returns the VertexData
  36726. */
  36727. VertexData.prototype.transform = function (matrix) {
  36728. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36729. var transformed = BABYLON.Vector3.Zero();
  36730. var index;
  36731. if (this.positions) {
  36732. var position = BABYLON.Vector3.Zero();
  36733. for (index = 0; index < this.positions.length; index += 3) {
  36734. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36735. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36736. this.positions[index] = transformed.x;
  36737. this.positions[index + 1] = transformed.y;
  36738. this.positions[index + 2] = transformed.z;
  36739. }
  36740. }
  36741. if (this.normals) {
  36742. var normal = BABYLON.Vector3.Zero();
  36743. for (index = 0; index < this.normals.length; index += 3) {
  36744. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36745. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36746. this.normals[index] = transformed.x;
  36747. this.normals[index + 1] = transformed.y;
  36748. this.normals[index + 2] = transformed.z;
  36749. }
  36750. }
  36751. if (this.tangents) {
  36752. var tangent = BABYLON.Vector4.Zero();
  36753. var tangentTransformed = BABYLON.Vector4.Zero();
  36754. for (index = 0; index < this.tangents.length; index += 4) {
  36755. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36756. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36757. this.tangents[index] = tangentTransformed.x;
  36758. this.tangents[index + 1] = tangentTransformed.y;
  36759. this.tangents[index + 2] = tangentTransformed.z;
  36760. this.tangents[index + 3] = tangentTransformed.w;
  36761. }
  36762. }
  36763. if (flip && this.indices) {
  36764. for (index = 0; index < this.indices.length; index += 3) {
  36765. var tmp = this.indices[index + 1];
  36766. this.indices[index + 1] = this.indices[index + 2];
  36767. this.indices[index + 2] = tmp;
  36768. }
  36769. }
  36770. return this;
  36771. };
  36772. /**
  36773. * Merges the passed VertexData into the current one
  36774. * @param other the VertexData to be merged into the current one
  36775. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36776. * @returns the modified VertexData
  36777. */
  36778. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36779. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36780. this._validate();
  36781. other._validate();
  36782. if (!this.normals !== !other.normals ||
  36783. !this.tangents !== !other.tangents ||
  36784. !this.uvs !== !other.uvs ||
  36785. !this.uvs2 !== !other.uvs2 ||
  36786. !this.uvs3 !== !other.uvs3 ||
  36787. !this.uvs4 !== !other.uvs4 ||
  36788. !this.uvs5 !== !other.uvs5 ||
  36789. !this.uvs6 !== !other.uvs6 ||
  36790. !this.colors !== !other.colors ||
  36791. !this.matricesIndices !== !other.matricesIndices ||
  36792. !this.matricesWeights !== !other.matricesWeights ||
  36793. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36794. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36795. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36796. }
  36797. if (other.indices) {
  36798. if (!this.indices) {
  36799. this.indices = [];
  36800. }
  36801. var offset = this.positions ? this.positions.length / 3 : 0;
  36802. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36803. if (isSrcTypedArray) {
  36804. var len = this.indices.length + other.indices.length;
  36805. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36806. temp.set(this.indices);
  36807. var decal = this.indices.length;
  36808. for (var index = 0; index < other.indices.length; index++) {
  36809. temp[decal + index] = other.indices[index] + offset;
  36810. }
  36811. this.indices = temp;
  36812. }
  36813. else {
  36814. for (var index = 0; index < other.indices.length; index++) {
  36815. this.indices.push(other.indices[index] + offset);
  36816. }
  36817. }
  36818. }
  36819. this.positions = this._mergeElement(this.positions, other.positions);
  36820. this.normals = this._mergeElement(this.normals, other.normals);
  36821. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36822. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36823. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36824. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36825. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36826. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36827. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36828. this.colors = this._mergeElement(this.colors, other.colors);
  36829. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36830. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36831. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36832. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36833. return this;
  36834. };
  36835. VertexData.prototype._mergeElement = function (source, other) {
  36836. if (!source) {
  36837. return other;
  36838. }
  36839. if (!other) {
  36840. return source;
  36841. }
  36842. var len = other.length + source.length;
  36843. var isSrcTypedArray = source instanceof Float32Array;
  36844. var isOthTypedArray = other instanceof Float32Array;
  36845. // use non-loop method when the source is Float32Array
  36846. if (isSrcTypedArray) {
  36847. var ret32 = new Float32Array(len);
  36848. ret32.set(source);
  36849. ret32.set(other, source.length);
  36850. return ret32;
  36851. // source is number[], when other is also use concat
  36852. }
  36853. else if (!isOthTypedArray) {
  36854. return source.concat(other);
  36855. // source is a number[], but other is a Float32Array, loop required
  36856. }
  36857. else {
  36858. var ret = source.slice(0); // copy source to a separate array
  36859. for (var i = 0, len = other.length; i < len; i++) {
  36860. ret.push(other[i]);
  36861. }
  36862. return ret;
  36863. }
  36864. };
  36865. VertexData.prototype._validate = function () {
  36866. if (!this.positions) {
  36867. throw new Error("Positions are required");
  36868. }
  36869. var getElementCount = function (kind, values) {
  36870. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36871. if ((values.length % stride) !== 0) {
  36872. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36873. }
  36874. return values.length / stride;
  36875. };
  36876. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36877. var validateElementCount = function (kind, values) {
  36878. var elementCount = getElementCount(kind, values);
  36879. if (elementCount !== positionsElementCount) {
  36880. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36881. }
  36882. };
  36883. if (this.normals)
  36884. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36885. if (this.tangents)
  36886. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36887. if (this.uvs)
  36888. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36889. if (this.uvs2)
  36890. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36891. if (this.uvs3)
  36892. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36893. if (this.uvs4)
  36894. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36895. if (this.uvs5)
  36896. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36897. if (this.uvs6)
  36898. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36899. if (this.colors)
  36900. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36901. if (this.matricesIndices)
  36902. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36903. if (this.matricesWeights)
  36904. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36905. if (this.matricesIndicesExtra)
  36906. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36907. if (this.matricesWeightsExtra)
  36908. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36909. };
  36910. /**
  36911. * Serializes the VertexData
  36912. * @returns a serialized object
  36913. */
  36914. VertexData.prototype.serialize = function () {
  36915. var serializationObject = this.serialize();
  36916. if (this.positions) {
  36917. serializationObject.positions = this.positions;
  36918. }
  36919. if (this.normals) {
  36920. serializationObject.normals = this.normals;
  36921. }
  36922. if (this.tangents) {
  36923. serializationObject.tangents = this.tangents;
  36924. }
  36925. if (this.uvs) {
  36926. serializationObject.uvs = this.uvs;
  36927. }
  36928. if (this.uvs2) {
  36929. serializationObject.uvs2 = this.uvs2;
  36930. }
  36931. if (this.uvs3) {
  36932. serializationObject.uvs3 = this.uvs3;
  36933. }
  36934. if (this.uvs4) {
  36935. serializationObject.uvs4 = this.uvs4;
  36936. }
  36937. if (this.uvs5) {
  36938. serializationObject.uvs5 = this.uvs5;
  36939. }
  36940. if (this.uvs6) {
  36941. serializationObject.uvs6 = this.uvs6;
  36942. }
  36943. if (this.colors) {
  36944. serializationObject.colors = this.colors;
  36945. }
  36946. if (this.matricesIndices) {
  36947. serializationObject.matricesIndices = this.matricesIndices;
  36948. serializationObject.matricesIndices._isExpanded = true;
  36949. }
  36950. if (this.matricesWeights) {
  36951. serializationObject.matricesWeights = this.matricesWeights;
  36952. }
  36953. if (this.matricesIndicesExtra) {
  36954. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36955. serializationObject.matricesIndicesExtra._isExpanded = true;
  36956. }
  36957. if (this.matricesWeightsExtra) {
  36958. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36959. }
  36960. serializationObject.indices = this.indices;
  36961. return serializationObject;
  36962. };
  36963. // Statics
  36964. /**
  36965. * Extracts the vertexData from a mesh
  36966. * @param mesh the mesh from which to extract the VertexData
  36967. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36968. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36969. * @returns the object VertexData associated to the passed mesh
  36970. */
  36971. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36972. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36973. };
  36974. /**
  36975. * Extracts the vertexData from the geometry
  36976. * @param geometry the geometry from which to extract the VertexData
  36977. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36978. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36979. * @returns the object VertexData associated to the passed mesh
  36980. */
  36981. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36982. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36983. };
  36984. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36985. var result = new VertexData();
  36986. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36987. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36988. }
  36989. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36990. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36991. }
  36992. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36993. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36994. }
  36995. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36996. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36997. }
  36998. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36999. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37000. }
  37001. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37002. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37003. }
  37004. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37005. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37006. }
  37007. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37008. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37009. }
  37010. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37011. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37012. }
  37013. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37014. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37015. }
  37016. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37017. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37018. }
  37019. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37020. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37021. }
  37022. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37023. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37024. }
  37025. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37026. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37027. }
  37028. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  37029. return result;
  37030. };
  37031. /**
  37032. * Creates the VertexData for a Ribbon
  37033. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37034. * * pathArray array of paths, each of which an array of successive Vector3
  37035. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37036. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37037. * * 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
  37038. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37039. * * 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)
  37040. * * 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)
  37041. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37042. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37043. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37044. * @returns the VertexData of the ribbon
  37045. */
  37046. VertexData.CreateRibbon = function (options) {
  37047. var pathArray = options.pathArray;
  37048. var closeArray = options.closeArray || false;
  37049. var closePath = options.closePath || false;
  37050. var invertUV = options.invertUV || false;
  37051. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37052. var offset = options.offset || defaultOffset;
  37053. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37054. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37055. var customUV = options.uvs;
  37056. var customColors = options.colors;
  37057. var positions = [];
  37058. var indices = [];
  37059. var normals = [];
  37060. var uvs = [];
  37061. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37062. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37063. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37064. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37065. var minlg; // minimal length among all paths from pathArray
  37066. var lg = []; // array of path lengths : nb of vertex per path
  37067. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37068. var p; // path iterator
  37069. var i; // point iterator
  37070. var j; // point iterator
  37071. // if single path in pathArray
  37072. if (pathArray.length < 2) {
  37073. var ar1 = [];
  37074. var ar2 = [];
  37075. for (i = 0; i < pathArray[0].length - offset; i++) {
  37076. ar1.push(pathArray[0][i]);
  37077. ar2.push(pathArray[0][i + offset]);
  37078. }
  37079. pathArray = [ar1, ar2];
  37080. }
  37081. // positions and horizontal distances (u)
  37082. var idc = 0;
  37083. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37084. var path;
  37085. var l;
  37086. minlg = pathArray[0].length;
  37087. var vectlg;
  37088. var dist;
  37089. for (p = 0; p < pathArray.length; p++) {
  37090. uTotalDistance[p] = 0;
  37091. us[p] = [0];
  37092. path = pathArray[p];
  37093. l = path.length;
  37094. minlg = (minlg < l) ? minlg : l;
  37095. j = 0;
  37096. while (j < l) {
  37097. positions.push(path[j].x, path[j].y, path[j].z);
  37098. if (j > 0) {
  37099. vectlg = path[j].subtract(path[j - 1]).length();
  37100. dist = vectlg + uTotalDistance[p];
  37101. us[p].push(dist);
  37102. uTotalDistance[p] = dist;
  37103. }
  37104. j++;
  37105. }
  37106. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37107. j--;
  37108. positions.push(path[0].x, path[0].y, path[0].z);
  37109. vectlg = path[j].subtract(path[0]).length();
  37110. dist = vectlg + uTotalDistance[p];
  37111. us[p].push(dist);
  37112. uTotalDistance[p] = dist;
  37113. }
  37114. lg[p] = l + closePathCorr;
  37115. idx[p] = idc;
  37116. idc += (l + closePathCorr);
  37117. }
  37118. // vertical distances (v)
  37119. var path1;
  37120. var path2;
  37121. var vertex1 = null;
  37122. var vertex2 = null;
  37123. for (i = 0; i < minlg + closePathCorr; i++) {
  37124. vTotalDistance[i] = 0;
  37125. vs[i] = [0];
  37126. for (p = 0; p < pathArray.length - 1; p++) {
  37127. path1 = pathArray[p];
  37128. path2 = pathArray[p + 1];
  37129. if (i === minlg) { // closePath
  37130. vertex1 = path1[0];
  37131. vertex2 = path2[0];
  37132. }
  37133. else {
  37134. vertex1 = path1[i];
  37135. vertex2 = path2[i];
  37136. }
  37137. vectlg = vertex2.subtract(vertex1).length();
  37138. dist = vectlg + vTotalDistance[i];
  37139. vs[i].push(dist);
  37140. vTotalDistance[i] = dist;
  37141. }
  37142. if (closeArray && vertex2 && vertex1) {
  37143. path1 = pathArray[p];
  37144. path2 = pathArray[0];
  37145. if (i === minlg) { // closePath
  37146. vertex2 = path2[0];
  37147. }
  37148. vectlg = vertex2.subtract(vertex1).length();
  37149. dist = vectlg + vTotalDistance[i];
  37150. vTotalDistance[i] = dist;
  37151. }
  37152. }
  37153. // uvs
  37154. var u;
  37155. var v;
  37156. if (customUV) {
  37157. for (p = 0; p < customUV.length; p++) {
  37158. uvs.push(customUV[p].x, customUV[p].y);
  37159. }
  37160. }
  37161. else {
  37162. for (p = 0; p < pathArray.length; p++) {
  37163. for (i = 0; i < minlg + closePathCorr; i++) {
  37164. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37165. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37166. if (invertUV) {
  37167. uvs.push(v, u);
  37168. }
  37169. else {
  37170. uvs.push(u, v);
  37171. }
  37172. }
  37173. }
  37174. }
  37175. // indices
  37176. p = 0; // path index
  37177. var pi = 0; // positions array index
  37178. var l1 = lg[p] - 1; // path1 length
  37179. var l2 = lg[p + 1] - 1; // path2 length
  37180. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37181. var shft = idx[1] - idx[0]; // shift
  37182. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37183. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37184. // 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
  37185. indices.push(pi, pi + shft, pi + 1);
  37186. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37187. pi += 1;
  37188. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37189. p++;
  37190. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37191. shft = idx[0] - idx[p];
  37192. l1 = lg[p] - 1;
  37193. l2 = lg[0] - 1;
  37194. }
  37195. else {
  37196. shft = idx[p + 1] - idx[p];
  37197. l1 = lg[p] - 1;
  37198. l2 = lg[p + 1] - 1;
  37199. }
  37200. pi = idx[p];
  37201. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37202. }
  37203. }
  37204. // normals
  37205. VertexData.ComputeNormals(positions, indices, normals);
  37206. if (closePath) { // update both the first and last vertex normals to their average value
  37207. var indexFirst = 0;
  37208. var indexLast = 0;
  37209. for (p = 0; p < pathArray.length; p++) {
  37210. indexFirst = idx[p] * 3;
  37211. if (p + 1 < pathArray.length) {
  37212. indexLast = (idx[p + 1] - 1) * 3;
  37213. }
  37214. else {
  37215. indexLast = normals.length - 3;
  37216. }
  37217. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37218. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37219. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37220. normals[indexLast] = normals[indexFirst];
  37221. normals[indexLast + 1] = normals[indexFirst + 1];
  37222. normals[indexLast + 2] = normals[indexFirst + 2];
  37223. }
  37224. }
  37225. // sides
  37226. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37227. // Colors
  37228. var colors = null;
  37229. if (customColors) {
  37230. colors = new Float32Array(customColors.length * 4);
  37231. for (var c = 0; c < customColors.length; c++) {
  37232. colors[c * 4] = customColors[c].r;
  37233. colors[c * 4 + 1] = customColors[c].g;
  37234. colors[c * 4 + 2] = customColors[c].b;
  37235. colors[c * 4 + 3] = customColors[c].a;
  37236. }
  37237. }
  37238. // Result
  37239. var vertexData = new VertexData();
  37240. var positions32 = new Float32Array(positions);
  37241. var normals32 = new Float32Array(normals);
  37242. var uvs32 = new Float32Array(uvs);
  37243. vertexData.indices = indices;
  37244. vertexData.positions = positions32;
  37245. vertexData.normals = normals32;
  37246. vertexData.uvs = uvs32;
  37247. if (colors) {
  37248. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37249. }
  37250. if (closePath) {
  37251. vertexData._idx = idx;
  37252. }
  37253. return vertexData;
  37254. };
  37255. /**
  37256. * Creates the VertexData for a box
  37257. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37258. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37259. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37260. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37261. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37262. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37263. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37264. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37265. * * 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)
  37266. * * 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)
  37267. * @returns the VertexData of the box
  37268. */
  37269. VertexData.CreateBox = function (options) {
  37270. var normalsSource = [
  37271. new BABYLON.Vector3(0, 0, 1),
  37272. new BABYLON.Vector3(0, 0, -1),
  37273. new BABYLON.Vector3(1, 0, 0),
  37274. new BABYLON.Vector3(-1, 0, 0),
  37275. new BABYLON.Vector3(0, 1, 0),
  37276. new BABYLON.Vector3(0, -1, 0)
  37277. ];
  37278. var indices = [];
  37279. var positions = [];
  37280. var normals = [];
  37281. var uvs = [];
  37282. var width = options.width || options.size || 1;
  37283. var height = options.height || options.size || 1;
  37284. var depth = options.depth || options.size || 1;
  37285. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37286. var faceUV = options.faceUV || new Array(6);
  37287. var faceColors = options.faceColors;
  37288. var colors = [];
  37289. // default face colors and UV if undefined
  37290. for (var f = 0; f < 6; f++) {
  37291. if (faceUV[f] === undefined) {
  37292. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37293. }
  37294. if (faceColors && faceColors[f] === undefined) {
  37295. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37296. }
  37297. }
  37298. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37299. // Create each face in turn.
  37300. for (var index = 0; index < normalsSource.length; index++) {
  37301. var normal = normalsSource[index];
  37302. // Get two vectors perpendicular to the face normal and to each other.
  37303. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37304. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37305. // Six indices (two triangles) per face.
  37306. var verticesLength = positions.length / 3;
  37307. indices.push(verticesLength);
  37308. indices.push(verticesLength + 1);
  37309. indices.push(verticesLength + 2);
  37310. indices.push(verticesLength);
  37311. indices.push(verticesLength + 2);
  37312. indices.push(verticesLength + 3);
  37313. // Four vertices per face.
  37314. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37315. positions.push(vertex.x, vertex.y, vertex.z);
  37316. normals.push(normal.x, normal.y, normal.z);
  37317. uvs.push(faceUV[index].z, faceUV[index].w);
  37318. if (faceColors) {
  37319. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37320. }
  37321. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37322. positions.push(vertex.x, vertex.y, vertex.z);
  37323. normals.push(normal.x, normal.y, normal.z);
  37324. uvs.push(faceUV[index].x, faceUV[index].w);
  37325. if (faceColors) {
  37326. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37327. }
  37328. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37329. positions.push(vertex.x, vertex.y, vertex.z);
  37330. normals.push(normal.x, normal.y, normal.z);
  37331. uvs.push(faceUV[index].x, faceUV[index].y);
  37332. if (faceColors) {
  37333. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37334. }
  37335. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37336. positions.push(vertex.x, vertex.y, vertex.z);
  37337. normals.push(normal.x, normal.y, normal.z);
  37338. uvs.push(faceUV[index].z, faceUV[index].y);
  37339. if (faceColors) {
  37340. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37341. }
  37342. }
  37343. // sides
  37344. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37345. // Result
  37346. var vertexData = new VertexData();
  37347. vertexData.indices = indices;
  37348. vertexData.positions = positions;
  37349. vertexData.normals = normals;
  37350. vertexData.uvs = uvs;
  37351. if (faceColors) {
  37352. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37353. vertexData.colors = totalColors;
  37354. }
  37355. return vertexData;
  37356. };
  37357. /**
  37358. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37359. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37360. * * segments sets the number of horizontal strips optional, default 32
  37361. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37362. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37363. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37364. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37365. * * 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
  37366. * * 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
  37367. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37368. * * 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)
  37369. * * 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)
  37370. * @returns the VertexData of the ellipsoid
  37371. */
  37372. VertexData.CreateSphere = function (options) {
  37373. var segments = options.segments || 32;
  37374. var diameterX = options.diameterX || options.diameter || 1;
  37375. var diameterY = options.diameterY || options.diameter || 1;
  37376. var diameterZ = options.diameterZ || options.diameter || 1;
  37377. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37378. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37379. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37380. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37381. var totalZRotationSteps = 2 + segments;
  37382. var totalYRotationSteps = 2 * totalZRotationSteps;
  37383. var indices = [];
  37384. var positions = [];
  37385. var normals = [];
  37386. var uvs = [];
  37387. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37388. var normalizedZ = zRotationStep / totalZRotationSteps;
  37389. var angleZ = normalizedZ * Math.PI * slice;
  37390. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37391. var normalizedY = yRotationStep / totalYRotationSteps;
  37392. var angleY = normalizedY * Math.PI * 2 * arc;
  37393. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37394. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37395. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37396. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37397. var vertex = complete.multiply(radius);
  37398. var normal = complete.divide(radius).normalize();
  37399. positions.push(vertex.x, vertex.y, vertex.z);
  37400. normals.push(normal.x, normal.y, normal.z);
  37401. uvs.push(normalizedY, normalizedZ);
  37402. }
  37403. if (zRotationStep > 0) {
  37404. var verticesCount = positions.length / 3;
  37405. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37406. indices.push((firstIndex));
  37407. indices.push((firstIndex + 1));
  37408. indices.push(firstIndex + totalYRotationSteps + 1);
  37409. indices.push((firstIndex + totalYRotationSteps + 1));
  37410. indices.push((firstIndex + 1));
  37411. indices.push((firstIndex + totalYRotationSteps + 2));
  37412. }
  37413. }
  37414. }
  37415. // Sides
  37416. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37417. // Result
  37418. var vertexData = new VertexData();
  37419. vertexData.indices = indices;
  37420. vertexData.positions = positions;
  37421. vertexData.normals = normals;
  37422. vertexData.uvs = uvs;
  37423. return vertexData;
  37424. };
  37425. /**
  37426. * Creates the VertexData for a cylinder, cone or prism
  37427. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37428. * * height sets the height (y direction) of the cylinder, optional, default 2
  37429. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37430. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37431. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37432. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37433. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37434. * * 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
  37435. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37436. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37437. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37438. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37439. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37440. * * 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)
  37441. * * 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)
  37442. * @returns the VertexData of the cylinder, cone or prism
  37443. */
  37444. VertexData.CreateCylinder = function (options) {
  37445. var height = options.height || 2;
  37446. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37447. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37448. var tessellation = options.tessellation || 24;
  37449. var subdivisions = options.subdivisions || 1;
  37450. var hasRings = options.hasRings ? true : false;
  37451. var enclose = options.enclose ? true : false;
  37452. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37453. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37454. var faceUV = options.faceUV || new Array(3);
  37455. var faceColors = options.faceColors;
  37456. // default face colors and UV if undefined
  37457. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37458. var ringNb = (hasRings) ? subdivisions : 1;
  37459. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37460. var f;
  37461. for (f = 0; f < surfaceNb; f++) {
  37462. if (faceColors && faceColors[f] === undefined) {
  37463. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37464. }
  37465. }
  37466. for (f = 0; f < surfaceNb; f++) {
  37467. if (faceUV && faceUV[f] === undefined) {
  37468. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37469. }
  37470. }
  37471. var indices = new Array();
  37472. var positions = new Array();
  37473. var normals = new Array();
  37474. var uvs = new Array();
  37475. var colors = new Array();
  37476. var angle_step = Math.PI * 2 * arc / tessellation;
  37477. var angle;
  37478. var h;
  37479. var radius;
  37480. var tan = (diameterBottom - diameterTop) / 2 / height;
  37481. var ringVertex = BABYLON.Vector3.Zero();
  37482. var ringNormal = BABYLON.Vector3.Zero();
  37483. var ringFirstVertex = BABYLON.Vector3.Zero();
  37484. var ringFirstNormal = BABYLON.Vector3.Zero();
  37485. var quadNormal = BABYLON.Vector3.Zero();
  37486. var Y = BABYLON.Axis.Y;
  37487. // positions, normals, uvs
  37488. var i;
  37489. var j;
  37490. var r;
  37491. var ringIdx = 1;
  37492. var s = 1; // surface index
  37493. var cs = 0;
  37494. var v = 0;
  37495. for (i = 0; i <= subdivisions; i++) {
  37496. h = i / subdivisions;
  37497. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37498. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37499. for (r = 0; r < ringIdx; r++) {
  37500. if (hasRings) {
  37501. s += r;
  37502. }
  37503. if (enclose) {
  37504. s += 2 * r;
  37505. }
  37506. for (j = 0; j <= tessellation; j++) {
  37507. angle = j * angle_step;
  37508. // position
  37509. ringVertex.x = Math.cos(-angle) * radius;
  37510. ringVertex.y = -height / 2 + h * height;
  37511. ringVertex.z = Math.sin(-angle) * radius;
  37512. // normal
  37513. if (diameterTop === 0 && i === subdivisions) {
  37514. // if no top cap, reuse former normals
  37515. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37516. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37517. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37518. }
  37519. else {
  37520. ringNormal.x = ringVertex.x;
  37521. ringNormal.z = ringVertex.z;
  37522. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37523. ringNormal.normalize();
  37524. }
  37525. // keep first ring vertex values for enclose
  37526. if (j === 0) {
  37527. ringFirstVertex.copyFrom(ringVertex);
  37528. ringFirstNormal.copyFrom(ringNormal);
  37529. }
  37530. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37531. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37532. if (hasRings) {
  37533. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37534. }
  37535. else {
  37536. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37537. }
  37538. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37539. if (faceColors) {
  37540. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37541. }
  37542. }
  37543. // if enclose, add four vertices and their dedicated normals
  37544. if (arc !== 1 && enclose) {
  37545. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37546. positions.push(0, ringVertex.y, 0);
  37547. positions.push(0, ringVertex.y, 0);
  37548. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37549. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37550. quadNormal.normalize();
  37551. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37552. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37553. quadNormal.normalize();
  37554. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37555. if (hasRings) {
  37556. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37557. }
  37558. else {
  37559. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37560. }
  37561. uvs.push(faceUV[s + 1].x, v);
  37562. uvs.push(faceUV[s + 1].z, v);
  37563. if (hasRings) {
  37564. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37565. }
  37566. else {
  37567. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37568. }
  37569. uvs.push(faceUV[s + 2].x, v);
  37570. uvs.push(faceUV[s + 2].z, v);
  37571. if (faceColors) {
  37572. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37573. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37574. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37575. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37576. }
  37577. }
  37578. if (cs !== s) {
  37579. cs = s;
  37580. }
  37581. }
  37582. }
  37583. // indices
  37584. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37585. var s;
  37586. i = 0;
  37587. for (s = 0; s < subdivisions; s++) {
  37588. var i0 = 0;
  37589. var i1 = 0;
  37590. var i2 = 0;
  37591. var i3 = 0;
  37592. for (j = 0; j < tessellation; j++) {
  37593. i0 = i * (e + 1) + j;
  37594. i1 = (i + 1) * (e + 1) + j;
  37595. i2 = i * (e + 1) + (j + 1);
  37596. i3 = (i + 1) * (e + 1) + (j + 1);
  37597. indices.push(i0, i1, i2);
  37598. indices.push(i3, i2, i1);
  37599. }
  37600. if (arc !== 1 && enclose) { // if enclose, add two quads
  37601. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37602. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37603. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37604. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37605. }
  37606. i = (hasRings) ? (i + 2) : (i + 1);
  37607. }
  37608. // Caps
  37609. var createCylinderCap = function (isTop) {
  37610. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37611. if (radius === 0) {
  37612. return;
  37613. }
  37614. // Cap positions, normals & uvs
  37615. var angle;
  37616. var circleVector;
  37617. var i;
  37618. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37619. var c = null;
  37620. if (faceColors) {
  37621. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37622. }
  37623. // cap center
  37624. var vbase = positions.length / 3;
  37625. var offset = isTop ? height / 2 : -height / 2;
  37626. var center = new BABYLON.Vector3(0, offset, 0);
  37627. positions.push(center.x, center.y, center.z);
  37628. normals.push(0, isTop ? 1 : -1, 0);
  37629. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37630. if (c) {
  37631. colors.push(c.r, c.g, c.b, c.a);
  37632. }
  37633. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37634. for (i = 0; i <= tessellation; i++) {
  37635. angle = Math.PI * 2 * i * arc / tessellation;
  37636. var cos = Math.cos(-angle);
  37637. var sin = Math.sin(-angle);
  37638. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37639. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37640. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37641. normals.push(0, isTop ? 1 : -1, 0);
  37642. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37643. if (c) {
  37644. colors.push(c.r, c.g, c.b, c.a);
  37645. }
  37646. }
  37647. // Cap indices
  37648. for (i = 0; i < tessellation; i++) {
  37649. if (!isTop) {
  37650. indices.push(vbase);
  37651. indices.push(vbase + (i + 1));
  37652. indices.push(vbase + (i + 2));
  37653. }
  37654. else {
  37655. indices.push(vbase);
  37656. indices.push(vbase + (i + 2));
  37657. indices.push(vbase + (i + 1));
  37658. }
  37659. }
  37660. };
  37661. // add caps to geometry
  37662. createCylinderCap(false);
  37663. createCylinderCap(true);
  37664. // Sides
  37665. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37666. var vertexData = new VertexData();
  37667. vertexData.indices = indices;
  37668. vertexData.positions = positions;
  37669. vertexData.normals = normals;
  37670. vertexData.uvs = uvs;
  37671. if (faceColors) {
  37672. vertexData.colors = colors;
  37673. }
  37674. return vertexData;
  37675. };
  37676. /**
  37677. * Creates the VertexData for a torus
  37678. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37679. * * diameter the diameter of the torus, optional default 1
  37680. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37681. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37682. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37683. * * 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)
  37684. * * 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)
  37685. * @returns the VertexData of the torus
  37686. */
  37687. VertexData.CreateTorus = function (options) {
  37688. var indices = [];
  37689. var positions = [];
  37690. var normals = [];
  37691. var uvs = [];
  37692. var diameter = options.diameter || 1;
  37693. var thickness = options.thickness || 0.5;
  37694. var tessellation = options.tessellation || 16;
  37695. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37696. var stride = tessellation + 1;
  37697. for (var i = 0; i <= tessellation; i++) {
  37698. var u = i / tessellation;
  37699. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37700. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37701. for (var j = 0; j <= tessellation; j++) {
  37702. var v = 1 - j / tessellation;
  37703. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37704. var dx = Math.cos(innerAngle);
  37705. var dy = Math.sin(innerAngle);
  37706. // Create a vertex.
  37707. var normal = new BABYLON.Vector3(dx, dy, 0);
  37708. var position = normal.scale(thickness / 2);
  37709. var textureCoordinate = new BABYLON.Vector2(u, v);
  37710. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37711. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37712. positions.push(position.x, position.y, position.z);
  37713. normals.push(normal.x, normal.y, normal.z);
  37714. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37715. // And create indices for two triangles.
  37716. var nextI = (i + 1) % stride;
  37717. var nextJ = (j + 1) % stride;
  37718. indices.push(i * stride + j);
  37719. indices.push(i * stride + nextJ);
  37720. indices.push(nextI * stride + j);
  37721. indices.push(i * stride + nextJ);
  37722. indices.push(nextI * stride + nextJ);
  37723. indices.push(nextI * stride + j);
  37724. }
  37725. }
  37726. // Sides
  37727. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37728. // Result
  37729. var vertexData = new VertexData();
  37730. vertexData.indices = indices;
  37731. vertexData.positions = positions;
  37732. vertexData.normals = normals;
  37733. vertexData.uvs = uvs;
  37734. return vertexData;
  37735. };
  37736. /**
  37737. * Creates the VertexData of the LineSystem
  37738. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37739. * - lines an array of lines, each line being an array of successive Vector3
  37740. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37741. * @returns the VertexData of the LineSystem
  37742. */
  37743. VertexData.CreateLineSystem = function (options) {
  37744. var indices = [];
  37745. var positions = [];
  37746. var lines = options.lines;
  37747. var colors = options.colors;
  37748. var vertexColors = [];
  37749. var idx = 0;
  37750. for (var l = 0; l < lines.length; l++) {
  37751. var points = lines[l];
  37752. for (var index = 0; index < points.length; index++) {
  37753. positions.push(points[index].x, points[index].y, points[index].z);
  37754. if (colors) {
  37755. var color = colors[l];
  37756. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37757. }
  37758. if (index > 0) {
  37759. indices.push(idx - 1);
  37760. indices.push(idx);
  37761. }
  37762. idx++;
  37763. }
  37764. }
  37765. var vertexData = new VertexData();
  37766. vertexData.indices = indices;
  37767. vertexData.positions = positions;
  37768. if (colors) {
  37769. vertexData.colors = vertexColors;
  37770. }
  37771. return vertexData;
  37772. };
  37773. /**
  37774. * Create the VertexData for a DashedLines
  37775. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37776. * - points an array successive Vector3
  37777. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37778. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37779. * - dashNb the intended total number of dashes, optional, default 200
  37780. * @returns the VertexData for the DashedLines
  37781. */
  37782. VertexData.CreateDashedLines = function (options) {
  37783. var dashSize = options.dashSize || 3;
  37784. var gapSize = options.gapSize || 1;
  37785. var dashNb = options.dashNb || 200;
  37786. var points = options.points;
  37787. var positions = new Array();
  37788. var indices = new Array();
  37789. var curvect = BABYLON.Vector3.Zero();
  37790. var lg = 0;
  37791. var nb = 0;
  37792. var shft = 0;
  37793. var dashshft = 0;
  37794. var curshft = 0;
  37795. var idx = 0;
  37796. var i = 0;
  37797. for (i = 0; i < points.length - 1; i++) {
  37798. points[i + 1].subtractToRef(points[i], curvect);
  37799. lg += curvect.length();
  37800. }
  37801. shft = lg / dashNb;
  37802. dashshft = dashSize * shft / (dashSize + gapSize);
  37803. for (i = 0; i < points.length - 1; i++) {
  37804. points[i + 1].subtractToRef(points[i], curvect);
  37805. nb = Math.floor(curvect.length() / shft);
  37806. curvect.normalize();
  37807. for (var j = 0; j < nb; j++) {
  37808. curshft = shft * j;
  37809. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37810. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37811. indices.push(idx, idx + 1);
  37812. idx += 2;
  37813. }
  37814. }
  37815. // Result
  37816. var vertexData = new VertexData();
  37817. vertexData.positions = positions;
  37818. vertexData.indices = indices;
  37819. return vertexData;
  37820. };
  37821. /**
  37822. * Creates the VertexData for a Ground
  37823. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37824. * - width the width (x direction) of the ground, optional, default 1
  37825. * - height the height (z direction) of the ground, optional, default 1
  37826. * - subdivisions the number of subdivisions per side, optional, default 1
  37827. * @returns the VertexData of the Ground
  37828. */
  37829. VertexData.CreateGround = function (options) {
  37830. var indices = [];
  37831. var positions = [];
  37832. var normals = [];
  37833. var uvs = [];
  37834. var row, col;
  37835. var width = options.width || 1;
  37836. var height = options.height || 1;
  37837. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37838. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37839. for (row = 0; row <= subdivisionsY; row++) {
  37840. for (col = 0; col <= subdivisionsX; col++) {
  37841. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37842. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37843. positions.push(position.x, position.y, position.z);
  37844. normals.push(normal.x, normal.y, normal.z);
  37845. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37846. }
  37847. }
  37848. for (row = 0; row < subdivisionsY; row++) {
  37849. for (col = 0; col < subdivisionsX; col++) {
  37850. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37851. indices.push(col + 1 + row * (subdivisionsX + 1));
  37852. indices.push(col + row * (subdivisionsX + 1));
  37853. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37854. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37855. indices.push(col + row * (subdivisionsX + 1));
  37856. }
  37857. }
  37858. // Result
  37859. var vertexData = new VertexData();
  37860. vertexData.indices = indices;
  37861. vertexData.positions = positions;
  37862. vertexData.normals = normals;
  37863. vertexData.uvs = uvs;
  37864. return vertexData;
  37865. };
  37866. /**
  37867. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37868. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37869. * * xmin the ground minimum X coordinate, optional, default -1
  37870. * * zmin the ground minimum Z coordinate, optional, default -1
  37871. * * xmax the ground maximum X coordinate, optional, default 1
  37872. * * zmax the ground maximum Z coordinate, optional, default 1
  37873. * * 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}
  37874. * * 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}
  37875. * @returns the VertexData of the TiledGround
  37876. */
  37877. VertexData.CreateTiledGround = function (options) {
  37878. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37879. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37880. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37881. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37882. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37883. var precision = options.precision || { w: 1, h: 1 };
  37884. var indices = new Array();
  37885. var positions = new Array();
  37886. var normals = new Array();
  37887. var uvs = new Array();
  37888. var row, col, tileRow, tileCol;
  37889. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37890. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37891. precision.w = (precision.w < 1) ? 1 : precision.w;
  37892. precision.h = (precision.h < 1) ? 1 : precision.h;
  37893. var tileSize = {
  37894. 'w': (xmax - xmin) / subdivisions.w,
  37895. 'h': (zmax - zmin) / subdivisions.h
  37896. };
  37897. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37898. // Indices
  37899. var base = positions.length / 3;
  37900. var rowLength = precision.w + 1;
  37901. for (row = 0; row < precision.h; row++) {
  37902. for (col = 0; col < precision.w; col++) {
  37903. var square = [
  37904. base + col + row * rowLength,
  37905. base + (col + 1) + row * rowLength,
  37906. base + (col + 1) + (row + 1) * rowLength,
  37907. base + col + (row + 1) * rowLength
  37908. ];
  37909. indices.push(square[1]);
  37910. indices.push(square[2]);
  37911. indices.push(square[3]);
  37912. indices.push(square[0]);
  37913. indices.push(square[1]);
  37914. indices.push(square[3]);
  37915. }
  37916. }
  37917. // Position, normals and uvs
  37918. var position = BABYLON.Vector3.Zero();
  37919. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37920. for (row = 0; row <= precision.h; row++) {
  37921. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37922. for (col = 0; col <= precision.w; col++) {
  37923. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37924. position.y = 0;
  37925. positions.push(position.x, position.y, position.z);
  37926. normals.push(normal.x, normal.y, normal.z);
  37927. uvs.push(col / precision.w, row / precision.h);
  37928. }
  37929. }
  37930. }
  37931. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37932. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37933. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37934. }
  37935. }
  37936. // Result
  37937. var vertexData = new VertexData();
  37938. vertexData.indices = indices;
  37939. vertexData.positions = positions;
  37940. vertexData.normals = normals;
  37941. vertexData.uvs = uvs;
  37942. return vertexData;
  37943. };
  37944. /**
  37945. * Creates the VertexData of the Ground designed from a heightmap
  37946. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37947. * * width the width (x direction) of the ground
  37948. * * height the height (z direction) of the ground
  37949. * * subdivisions the number of subdivisions per side
  37950. * * minHeight the minimum altitude on the ground, optional, default 0
  37951. * * maxHeight the maximum altitude on the ground, optional default 1
  37952. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37953. * * buffer the array holding the image color data
  37954. * * bufferWidth the width of image
  37955. * * bufferHeight the height of image
  37956. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  37957. * @returns the VertexData of the Ground designed from a heightmap
  37958. */
  37959. VertexData.CreateGroundFromHeightMap = function (options) {
  37960. var indices = [];
  37961. var positions = [];
  37962. var normals = [];
  37963. var uvs = [];
  37964. var row, col;
  37965. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37966. var alphaFilter = options.alphaFilter || 0.0;
  37967. // Vertices
  37968. for (row = 0; row <= options.subdivisions; row++) {
  37969. for (col = 0; col <= options.subdivisions; col++) {
  37970. 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));
  37971. // Compute height
  37972. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37973. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37974. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37975. var r = options.buffer[pos] / 255.0;
  37976. var g = options.buffer[pos + 1] / 255.0;
  37977. var b = options.buffer[pos + 2] / 255.0;
  37978. var a = options.buffer[pos + 3] / 255.0;
  37979. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37980. // If our alpha channel is not within our filter then we will assign a 'special' height
  37981. // Then when building the indices, we will ignore any vertex that is using the special height
  37982. if (a >= alphaFilter)
  37983. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37984. else {
  37985. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  37986. }
  37987. // Add vertex
  37988. positions.push(position.x, position.y, position.z);
  37989. normals.push(0, 0, 0);
  37990. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37991. }
  37992. }
  37993. // Indices
  37994. for (row = 0; row < options.subdivisions; row++) {
  37995. for (col = 0; col < options.subdivisions; col++) {
  37996. // Calculate Indices
  37997. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  37998. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  37999. var idx3 = (col + row * (options.subdivisions + 1));
  38000. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  38001. // Check that all indices are visible (based on our special height)
  38002. // Only display the vertex if all Indices are visible
  38003. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  38004. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  38005. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  38006. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  38007. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  38008. indices.push(idx1);
  38009. indices.push(idx2);
  38010. indices.push(idx3);
  38011. }
  38012. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  38013. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  38014. indices.push(idx4);
  38015. indices.push(idx1);
  38016. indices.push(idx3);
  38017. }
  38018. }
  38019. }
  38020. // Normals
  38021. VertexData.ComputeNormals(positions, indices, normals);
  38022. // Result
  38023. var vertexData = new VertexData();
  38024. vertexData.indices = indices;
  38025. vertexData.positions = positions;
  38026. vertexData.normals = normals;
  38027. vertexData.uvs = uvs;
  38028. return vertexData;
  38029. };
  38030. /**
  38031. * Creates the VertexData for a Plane
  38032. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38033. * * size sets the width and height of the plane to the value of size, optional default 1
  38034. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38035. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38036. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38037. * * 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)
  38038. * * 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)
  38039. * @returns the VertexData of the box
  38040. */
  38041. VertexData.CreatePlane = function (options) {
  38042. var indices = [];
  38043. var positions = [];
  38044. var normals = [];
  38045. var uvs = [];
  38046. var width = options.width || options.size || 1;
  38047. var height = options.height || options.size || 1;
  38048. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38049. // Vertices
  38050. var halfWidth = width / 2.0;
  38051. var halfHeight = height / 2.0;
  38052. positions.push(-halfWidth, -halfHeight, 0);
  38053. normals.push(0, 0, -1.0);
  38054. uvs.push(0.0, 0.0);
  38055. positions.push(halfWidth, -halfHeight, 0);
  38056. normals.push(0, 0, -1.0);
  38057. uvs.push(1.0, 0.0);
  38058. positions.push(halfWidth, halfHeight, 0);
  38059. normals.push(0, 0, -1.0);
  38060. uvs.push(1.0, 1.0);
  38061. positions.push(-halfWidth, halfHeight, 0);
  38062. normals.push(0, 0, -1.0);
  38063. uvs.push(0.0, 1.0);
  38064. // Indices
  38065. indices.push(0);
  38066. indices.push(1);
  38067. indices.push(2);
  38068. indices.push(0);
  38069. indices.push(2);
  38070. indices.push(3);
  38071. // Sides
  38072. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38073. // Result
  38074. var vertexData = new VertexData();
  38075. vertexData.indices = indices;
  38076. vertexData.positions = positions;
  38077. vertexData.normals = normals;
  38078. vertexData.uvs = uvs;
  38079. return vertexData;
  38080. };
  38081. /**
  38082. * Creates the VertexData of the Disc or regular Polygon
  38083. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38084. * * radius the radius of the disc, optional default 0.5
  38085. * * tessellation the number of polygon sides, optional, default 64
  38086. * * 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
  38087. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38088. * * 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)
  38089. * * 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)
  38090. * @returns the VertexData of the box
  38091. */
  38092. VertexData.CreateDisc = function (options) {
  38093. var positions = new Array();
  38094. var indices = new Array();
  38095. var normals = new Array();
  38096. var uvs = new Array();
  38097. var radius = options.radius || 0.5;
  38098. var tessellation = options.tessellation || 64;
  38099. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38100. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38101. // positions and uvs
  38102. positions.push(0, 0, 0); // disc center first
  38103. uvs.push(0.5, 0.5);
  38104. var theta = Math.PI * 2 * arc;
  38105. var step = theta / tessellation;
  38106. for (var a = 0; a < theta; a += step) {
  38107. var x = Math.cos(a);
  38108. var y = Math.sin(a);
  38109. var u = (x + 1) / 2;
  38110. var v = (1 - y) / 2;
  38111. positions.push(radius * x, radius * y, 0);
  38112. uvs.push(u, v);
  38113. }
  38114. if (arc === 1) {
  38115. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38116. uvs.push(uvs[2], uvs[3]);
  38117. }
  38118. //indices
  38119. var vertexNb = positions.length / 3;
  38120. for (var i = 1; i < vertexNb - 1; i++) {
  38121. indices.push(i + 1, 0, i);
  38122. }
  38123. // result
  38124. VertexData.ComputeNormals(positions, indices, normals);
  38125. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38126. var vertexData = new VertexData();
  38127. vertexData.indices = indices;
  38128. vertexData.positions = positions;
  38129. vertexData.normals = normals;
  38130. vertexData.uvs = uvs;
  38131. return vertexData;
  38132. };
  38133. /**
  38134. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38135. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38136. * @param polygon a mesh built from polygonTriangulation.build()
  38137. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38138. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38139. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38140. * @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)
  38141. * @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)
  38142. * @returns the VertexData of the Polygon
  38143. */
  38144. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38145. var faceUV = fUV || new Array(3);
  38146. var faceColors = fColors;
  38147. var colors = [];
  38148. // default face colors and UV if undefined
  38149. for (var f = 0; f < 3; f++) {
  38150. if (faceUV[f] === undefined) {
  38151. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38152. }
  38153. if (faceColors && faceColors[f] === undefined) {
  38154. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38155. }
  38156. }
  38157. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38158. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38159. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38160. var indices = polygon.getIndices();
  38161. // set face colours and textures
  38162. var idx = 0;
  38163. var face = 0;
  38164. for (var index = 0; index < normals.length; index += 3) {
  38165. //Edge Face no. 1
  38166. if (Math.abs(normals[index + 1]) < 0.001) {
  38167. face = 1;
  38168. }
  38169. //Top Face no. 0
  38170. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38171. face = 0;
  38172. }
  38173. //Bottom Face no. 2
  38174. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38175. face = 2;
  38176. }
  38177. idx = index / 3;
  38178. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38179. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38180. if (faceColors) {
  38181. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38182. }
  38183. }
  38184. // sides
  38185. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38186. // Result
  38187. var vertexData = new VertexData();
  38188. vertexData.indices = indices;
  38189. vertexData.positions = positions;
  38190. vertexData.normals = normals;
  38191. vertexData.uvs = uvs;
  38192. if (faceColors) {
  38193. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38194. vertexData.colors = totalColors;
  38195. }
  38196. return vertexData;
  38197. };
  38198. /**
  38199. * Creates the VertexData of the IcoSphere
  38200. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38201. * * radius the radius of the IcoSphere, optional default 1
  38202. * * radiusX allows stretching in the x direction, optional, default radius
  38203. * * radiusY allows stretching in the y direction, optional, default radius
  38204. * * radiusZ allows stretching in the z direction, optional, default radius
  38205. * * flat when true creates a flat shaded mesh, optional, default true
  38206. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38207. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38208. * * 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)
  38209. * * 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)
  38210. * @returns the VertexData of the IcoSphere
  38211. */
  38212. VertexData.CreateIcoSphere = function (options) {
  38213. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38214. var radius = options.radius || 1;
  38215. var flat = (options.flat === undefined) ? true : options.flat;
  38216. var subdivisions = options.subdivisions || 4;
  38217. var radiusX = options.radiusX || radius;
  38218. var radiusY = options.radiusY || radius;
  38219. var radiusZ = options.radiusZ || radius;
  38220. var t = (1 + Math.sqrt(5)) / 2;
  38221. // 12 vertex x,y,z
  38222. var ico_vertices = [
  38223. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38224. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38225. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38226. ];
  38227. // index of 3 vertex makes a face of icopshere
  38228. var ico_indices = [
  38229. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38230. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38231. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38232. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38233. ];
  38234. // vertex for uv have aliased position, not for UV
  38235. var vertices_unalias_id = [
  38236. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38237. // vertex alias
  38238. 0,
  38239. 2,
  38240. 3,
  38241. 3,
  38242. 3,
  38243. 4,
  38244. 7,
  38245. 8,
  38246. 9,
  38247. 9,
  38248. 10,
  38249. 11 // 23: B + 12
  38250. ];
  38251. // uv as integer step (not pixels !)
  38252. var ico_vertexuv = [
  38253. 5, 1, 3, 1, 6, 4, 0, 0,
  38254. 5, 3, 4, 2, 2, 2, 4, 0,
  38255. 2, 0, 1, 1, 6, 0, 6, 2,
  38256. // vertex alias (for same vertex on different faces)
  38257. 0, 4,
  38258. 3, 3,
  38259. 4, 4,
  38260. 3, 1,
  38261. 4, 2,
  38262. 4, 4,
  38263. 0, 2,
  38264. 1, 1,
  38265. 2, 2,
  38266. 3, 3,
  38267. 1, 3,
  38268. 2, 4 // 23: B + 12
  38269. ];
  38270. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38271. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38272. // First island of uv mapping
  38273. // v = 4h 3+ 2
  38274. // v = 3h 9+ 4
  38275. // v = 2h 9+ 5 B
  38276. // v = 1h 9 1 0
  38277. // v = 0h 3 8 7 A
  38278. // u = 0 1 2 3 4 5 6 *a
  38279. // Second island of uv mapping
  38280. // v = 4h 0+ B+ 4+
  38281. // v = 3h A+ 2+
  38282. // v = 2h 7+ 6 3+
  38283. // v = 1h 8+ 3+
  38284. // v = 0h
  38285. // u = 0 1 2 3 4 5 6 *a
  38286. // Face layout on texture UV mapping
  38287. // ============
  38288. // \ 4 /\ 16 / ======
  38289. // \ / \ / /\ 11 /
  38290. // \/ 7 \/ / \ /
  38291. // ======= / 10 \/
  38292. // /\ 17 /\ =======
  38293. // / \ / \ \ 15 /\
  38294. // / 8 \/ 12 \ \ / \
  38295. // ============ \/ 6 \
  38296. // \ 18 /\ ============
  38297. // \ / \ \ 5 /\ 0 /
  38298. // \/ 13 \ \ / \ /
  38299. // ======= \/ 1 \/
  38300. // =============
  38301. // /\ 19 /\ 2 /\
  38302. // / \ / \ / \
  38303. // / 14 \/ 9 \/ 3 \
  38304. // ===================
  38305. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38306. var ustep = 138 / 1024;
  38307. var vstep = 239 / 1024;
  38308. var uoffset = 60 / 1024;
  38309. var voffset = 26 / 1024;
  38310. // Second island should have margin, not to touch the first island
  38311. // avoid any borderline artefact in pixel rounding
  38312. var island_u_offset = -40 / 1024;
  38313. var island_v_offset = +20 / 1024;
  38314. // face is either island 0 or 1 :
  38315. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38316. var island = [
  38317. 0, 0, 0, 0, 1,
  38318. 0, 0, 1, 1, 0,
  38319. 0, 0, 1, 1, 0,
  38320. 0, 1, 1, 1, 0 // 15 - 19
  38321. ];
  38322. var indices = new Array();
  38323. var positions = new Array();
  38324. var normals = new Array();
  38325. var uvs = new Array();
  38326. var current_indice = 0;
  38327. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38328. var face_vertex_pos = new Array(3);
  38329. var face_vertex_uv = new Array(3);
  38330. var v012;
  38331. for (v012 = 0; v012 < 3; v012++) {
  38332. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38333. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38334. }
  38335. // create all with normals
  38336. for (var face = 0; face < 20; face++) {
  38337. // 3 vertex per face
  38338. for (v012 = 0; v012 < 3; v012++) {
  38339. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38340. var v_id = ico_indices[3 * face + v012];
  38341. // vertex have 3D position (x,y,z)
  38342. 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]);
  38343. // Normalize to get normal, then scale to radius
  38344. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38345. // uv Coordinates from vertex ID
  38346. 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);
  38347. }
  38348. // Subdivide the face (interpolate pos, norm, uv)
  38349. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38350. // - norm is linear interpolation of vertex corner normal
  38351. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38352. // - uv is linear interpolation
  38353. //
  38354. // Topology is as below for sub-divide by 2
  38355. // vertex shown as v0,v1,v2
  38356. // interp index is i1 to progress in range [v0,v1[
  38357. // interp index is i2 to progress in range [v0,v2[
  38358. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38359. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38360. //
  38361. //
  38362. // i2 v2
  38363. // ^ ^
  38364. // / / \
  38365. // / / \
  38366. // / / \
  38367. // / / (0,1) \
  38368. // / #---------\
  38369. // / / \ (0,0)'/ \
  38370. // / / \ / \
  38371. // / / \ / \
  38372. // / / (0,0) \ / (1,0) \
  38373. // / #---------#---------\
  38374. // v0 v1
  38375. //
  38376. // --------------------> i1
  38377. //
  38378. // interp of (i1,i2):
  38379. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38380. // along i1 : lerp(x0,x1, i1/(S-i2))
  38381. //
  38382. // centroid of triangle is needed to get help normal computation
  38383. // (c1,c2) are used for centroid location
  38384. var interp_vertex = function (i1, i2, c1, c2) {
  38385. // vertex is interpolated from
  38386. // - face_vertex_pos[0..2]
  38387. // - face_vertex_uv[0..2]
  38388. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38389. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38390. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38391. pos_interp.normalize();
  38392. var vertex_normal;
  38393. if (flat) {
  38394. // in flat mode, recalculate normal as face centroid normal
  38395. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38396. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38397. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38398. }
  38399. else {
  38400. // in smooth mode, recalculate normal from each single vertex position
  38401. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38402. }
  38403. // Vertex normal need correction due to X,Y,Z radius scaling
  38404. vertex_normal.x /= radiusX;
  38405. vertex_normal.y /= radiusY;
  38406. vertex_normal.z /= radiusZ;
  38407. vertex_normal.normalize();
  38408. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38409. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38410. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38411. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38412. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38413. uvs.push(uv_interp.x, uv_interp.y);
  38414. // push each vertex has member of a face
  38415. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38416. indices.push(current_indice);
  38417. current_indice++;
  38418. };
  38419. for (var i2 = 0; i2 < subdivisions; i2++) {
  38420. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38421. // face : (i1,i2) for /\ :
  38422. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38423. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38424. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38425. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38426. if (i1 + i2 + 1 < subdivisions) {
  38427. // face : (i1,i2)' for \/ :
  38428. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38429. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38430. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38431. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38432. }
  38433. }
  38434. }
  38435. }
  38436. // Sides
  38437. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38438. // Result
  38439. var vertexData = new VertexData();
  38440. vertexData.indices = indices;
  38441. vertexData.positions = positions;
  38442. vertexData.normals = normals;
  38443. vertexData.uvs = uvs;
  38444. return vertexData;
  38445. };
  38446. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38447. /**
  38448. * Creates the VertexData for a Polyhedron
  38449. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38450. * * type provided types are:
  38451. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38452. * * 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)
  38453. * * size the size of the IcoSphere, optional default 1
  38454. * * sizeX allows stretching in the x direction, optional, default size
  38455. * * sizeY allows stretching in the y direction, optional, default size
  38456. * * sizeZ allows stretching in the z direction, optional, default size
  38457. * * 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
  38458. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38459. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38460. * * flat when true creates a flat shaded mesh, optional, default true
  38461. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38462. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38463. * * 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)
  38464. * * 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)
  38465. * @returns the VertexData of the Polyhedron
  38466. */
  38467. VertexData.CreatePolyhedron = function (options) {
  38468. // provided polyhedron types :
  38469. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38470. // 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)
  38471. var polyhedra = [];
  38472. 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]] };
  38473. 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]] };
  38474. polyhedra[2] = {
  38475. 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]],
  38476. 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]]
  38477. };
  38478. polyhedra[3] = {
  38479. 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]],
  38480. 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]]
  38481. };
  38482. polyhedra[4] = {
  38483. 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]],
  38484. 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]]
  38485. };
  38486. 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]] };
  38487. 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]] };
  38488. 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]] };
  38489. 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]] };
  38490. 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]] };
  38491. 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]] };
  38492. 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]] };
  38493. 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]] };
  38494. 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]] };
  38495. polyhedra[14] = {
  38496. 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]],
  38497. 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]]
  38498. };
  38499. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38500. var size = options.size;
  38501. var sizeX = options.sizeX || size || 1;
  38502. var sizeY = options.sizeY || size || 1;
  38503. var sizeZ = options.sizeZ || size || 1;
  38504. var data = options.custom || polyhedra[type];
  38505. var nbfaces = data.face.length;
  38506. var faceUV = options.faceUV || new Array(nbfaces);
  38507. var faceColors = options.faceColors;
  38508. var flat = (options.flat === undefined) ? true : options.flat;
  38509. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38510. var positions = new Array();
  38511. var indices = new Array();
  38512. var normals = new Array();
  38513. var uvs = new Array();
  38514. var colors = new Array();
  38515. var index = 0;
  38516. var faceIdx = 0; // face cursor in the array "indexes"
  38517. var indexes = new Array();
  38518. var i = 0;
  38519. var f = 0;
  38520. var u, v, ang, x, y, tmp;
  38521. // default face colors and UV if undefined
  38522. if (flat) {
  38523. for (f = 0; f < nbfaces; f++) {
  38524. if (faceColors && faceColors[f] === undefined) {
  38525. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38526. }
  38527. if (faceUV && faceUV[f] === undefined) {
  38528. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38529. }
  38530. }
  38531. }
  38532. if (!flat) {
  38533. for (i = 0; i < data.vertex.length; i++) {
  38534. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38535. uvs.push(0, 0);
  38536. }
  38537. for (f = 0; f < nbfaces; f++) {
  38538. for (i = 0; i < data.face[f].length - 2; i++) {
  38539. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38540. }
  38541. }
  38542. }
  38543. else {
  38544. for (f = 0; f < nbfaces; f++) {
  38545. var fl = data.face[f].length; // number of vertices of the current face
  38546. ang = 2 * Math.PI / fl;
  38547. x = 0.5 * Math.tan(ang / 2);
  38548. y = 0.5;
  38549. // positions, uvs, colors
  38550. for (i = 0; i < fl; i++) {
  38551. // positions
  38552. 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);
  38553. indexes.push(index);
  38554. index++;
  38555. // uvs
  38556. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38557. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38558. uvs.push(u, v);
  38559. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38560. y = x * Math.sin(ang) + y * Math.cos(ang);
  38561. x = tmp;
  38562. // colors
  38563. if (faceColors) {
  38564. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38565. }
  38566. }
  38567. // indices from indexes
  38568. for (i = 0; i < fl - 2; i++) {
  38569. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38570. }
  38571. faceIdx += fl;
  38572. }
  38573. }
  38574. VertexData.ComputeNormals(positions, indices, normals);
  38575. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38576. var vertexData = new VertexData();
  38577. vertexData.positions = positions;
  38578. vertexData.indices = indices;
  38579. vertexData.normals = normals;
  38580. vertexData.uvs = uvs;
  38581. if (faceColors && flat) {
  38582. vertexData.colors = colors;
  38583. }
  38584. return vertexData;
  38585. };
  38586. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38587. /**
  38588. * Creates the VertexData for a TorusKnot
  38589. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38590. * * radius the radius of the torus knot, optional, default 2
  38591. * * tube the thickness of the tube, optional, default 0.5
  38592. * * radialSegments the number of sides on each tube segments, optional, default 32
  38593. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38594. * * p the number of windings around the z axis, optional, default 2
  38595. * * q the number of windings around the x axis, optional, default 3
  38596. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38597. * * 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)
  38598. * * 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)
  38599. * @returns the VertexData of the Torus Knot
  38600. */
  38601. VertexData.CreateTorusKnot = function (options) {
  38602. var indices = new Array();
  38603. var positions = new Array();
  38604. var normals = new Array();
  38605. var uvs = new Array();
  38606. var radius = options.radius || 2;
  38607. var tube = options.tube || 0.5;
  38608. var radialSegments = options.radialSegments || 32;
  38609. var tubularSegments = options.tubularSegments || 32;
  38610. var p = options.p || 2;
  38611. var q = options.q || 3;
  38612. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38613. // Helper
  38614. var getPos = function (angle) {
  38615. var cu = Math.cos(angle);
  38616. var su = Math.sin(angle);
  38617. var quOverP = q / p * angle;
  38618. var cs = Math.cos(quOverP);
  38619. var tx = radius * (2 + cs) * 0.5 * cu;
  38620. var ty = radius * (2 + cs) * su * 0.5;
  38621. var tz = radius * Math.sin(quOverP) * 0.5;
  38622. return new BABYLON.Vector3(tx, ty, tz);
  38623. };
  38624. // Vertices
  38625. var i;
  38626. var j;
  38627. for (i = 0; i <= radialSegments; i++) {
  38628. var modI = i % radialSegments;
  38629. var u = modI / radialSegments * 2 * p * Math.PI;
  38630. var p1 = getPos(u);
  38631. var p2 = getPos(u + 0.01);
  38632. var tang = p2.subtract(p1);
  38633. var n = p2.add(p1);
  38634. var bitan = BABYLON.Vector3.Cross(tang, n);
  38635. n = BABYLON.Vector3.Cross(bitan, tang);
  38636. bitan.normalize();
  38637. n.normalize();
  38638. for (j = 0; j < tubularSegments; j++) {
  38639. var modJ = j % tubularSegments;
  38640. var v = modJ / tubularSegments * 2 * Math.PI;
  38641. var cx = -tube * Math.cos(v);
  38642. var cy = tube * Math.sin(v);
  38643. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38644. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38645. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38646. uvs.push(i / radialSegments);
  38647. uvs.push(j / tubularSegments);
  38648. }
  38649. }
  38650. for (i = 0; i < radialSegments; i++) {
  38651. for (j = 0; j < tubularSegments; j++) {
  38652. var jNext = (j + 1) % tubularSegments;
  38653. var a = i * tubularSegments + j;
  38654. var b = (i + 1) * tubularSegments + j;
  38655. var c = (i + 1) * tubularSegments + jNext;
  38656. var d = i * tubularSegments + jNext;
  38657. indices.push(d);
  38658. indices.push(b);
  38659. indices.push(a);
  38660. indices.push(d);
  38661. indices.push(c);
  38662. indices.push(b);
  38663. }
  38664. }
  38665. // Normals
  38666. VertexData.ComputeNormals(positions, indices, normals);
  38667. // Sides
  38668. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38669. // Result
  38670. var vertexData = new VertexData();
  38671. vertexData.indices = indices;
  38672. vertexData.positions = positions;
  38673. vertexData.normals = normals;
  38674. vertexData.uvs = uvs;
  38675. return vertexData;
  38676. };
  38677. // Tools
  38678. /**
  38679. * Compute normals for given positions and indices
  38680. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38681. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38682. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38683. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38684. * * facetNormals : optional array of facet normals (vector3)
  38685. * * facetPositions : optional array of facet positions (vector3)
  38686. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38687. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38688. * * bInfo : optional bounding info, required for facetPartitioning computation
  38689. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38690. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38691. * * useRightHandedSystem: optional boolean to for right handed system computation
  38692. * * depthSort : optional boolean to enable the facet depth sort computation
  38693. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38694. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38695. */
  38696. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38697. // temporary scalar variables
  38698. var index = 0; // facet index
  38699. var p1p2x = 0.0; // p1p2 vector x coordinate
  38700. var p1p2y = 0.0; // p1p2 vector y coordinate
  38701. var p1p2z = 0.0; // p1p2 vector z coordinate
  38702. var p3p2x = 0.0; // p3p2 vector x coordinate
  38703. var p3p2y = 0.0; // p3p2 vector y coordinate
  38704. var p3p2z = 0.0; // p3p2 vector z coordinate
  38705. var faceNormalx = 0.0; // facet normal x coordinate
  38706. var faceNormaly = 0.0; // facet normal y coordinate
  38707. var faceNormalz = 0.0; // facet normal z coordinate
  38708. var length = 0.0; // facet normal length before normalization
  38709. var v1x = 0; // vector1 x index in the positions array
  38710. var v1y = 0; // vector1 y index in the positions array
  38711. var v1z = 0; // vector1 z index in the positions array
  38712. var v2x = 0; // vector2 x index in the positions array
  38713. var v2y = 0; // vector2 y index in the positions array
  38714. var v2z = 0; // vector2 z index in the positions array
  38715. var v3x = 0; // vector3 x index in the positions array
  38716. var v3y = 0; // vector3 y index in the positions array
  38717. var v3z = 0; // vector3 z index in the positions array
  38718. var computeFacetNormals = false;
  38719. var computeFacetPositions = false;
  38720. var computeFacetPartitioning = false;
  38721. var computeDepthSort = false;
  38722. var faceNormalSign = 1;
  38723. var ratio = 0;
  38724. var distanceTo = null;
  38725. if (options) {
  38726. computeFacetNormals = (options.facetNormals) ? true : false;
  38727. computeFacetPositions = (options.facetPositions) ? true : false;
  38728. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38729. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38730. ratio = options.ratio || 0;
  38731. computeDepthSort = (options.depthSort) ? true : false;
  38732. distanceTo = (options.distanceTo);
  38733. if (computeDepthSort) {
  38734. if (distanceTo === undefined) {
  38735. distanceTo = BABYLON.Vector3.Zero();
  38736. }
  38737. var depthSortedFacets = options.depthSortedFacets;
  38738. }
  38739. }
  38740. // facetPartitioning reinit if needed
  38741. var xSubRatio = 0;
  38742. var ySubRatio = 0;
  38743. var zSubRatio = 0;
  38744. var subSq = 0;
  38745. if (computeFacetPartitioning && options && options.bbSize) {
  38746. var ox = 0; // X partitioning index for facet position
  38747. var oy = 0; // Y partinioning index for facet position
  38748. var oz = 0; // Z partinioning index for facet position
  38749. var b1x = 0; // X partitioning index for facet v1 vertex
  38750. var b1y = 0; // Y partitioning index for facet v1 vertex
  38751. var b1z = 0; // z partitioning index for facet v1 vertex
  38752. var b2x = 0; // X partitioning index for facet v2 vertex
  38753. var b2y = 0; // Y partitioning index for facet v2 vertex
  38754. var b2z = 0; // Z partitioning index for facet v2 vertex
  38755. var b3x = 0; // X partitioning index for facet v3 vertex
  38756. var b3y = 0; // Y partitioning index for facet v3 vertex
  38757. var b3z = 0; // Z partitioning index for facet v3 vertex
  38758. var block_idx_o = 0; // facet barycenter block index
  38759. var block_idx_v1 = 0; // v1 vertex block index
  38760. var block_idx_v2 = 0; // v2 vertex block index
  38761. var block_idx_v3 = 0; // v3 vertex block index
  38762. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38763. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38764. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38765. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38766. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38767. subSq = options.subDiv.max * options.subDiv.max;
  38768. options.facetPartitioning.length = 0;
  38769. }
  38770. // reset the normals
  38771. for (index = 0; index < positions.length; index++) {
  38772. normals[index] = 0.0;
  38773. }
  38774. // Loop : 1 indice triplet = 1 facet
  38775. var nbFaces = (indices.length / 3) | 0;
  38776. for (index = 0; index < nbFaces; index++) {
  38777. // get the indexes of the coordinates of each vertex of the facet
  38778. v1x = indices[index * 3] * 3;
  38779. v1y = v1x + 1;
  38780. v1z = v1x + 2;
  38781. v2x = indices[index * 3 + 1] * 3;
  38782. v2y = v2x + 1;
  38783. v2z = v2x + 2;
  38784. v3x = indices[index * 3 + 2] * 3;
  38785. v3y = v3x + 1;
  38786. v3z = v3x + 2;
  38787. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38788. p1p2y = positions[v1y] - positions[v2y];
  38789. p1p2z = positions[v1z] - positions[v2z];
  38790. p3p2x = positions[v3x] - positions[v2x];
  38791. p3p2y = positions[v3y] - positions[v2y];
  38792. p3p2z = positions[v3z] - positions[v2z];
  38793. // compute the face normal with the cross product
  38794. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38795. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38796. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38797. // normalize this normal and store it in the array facetData
  38798. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38799. length = (length === 0) ? 1.0 : length;
  38800. faceNormalx /= length;
  38801. faceNormaly /= length;
  38802. faceNormalz /= length;
  38803. if (computeFacetNormals && options) {
  38804. options.facetNormals[index].x = faceNormalx;
  38805. options.facetNormals[index].y = faceNormaly;
  38806. options.facetNormals[index].z = faceNormalz;
  38807. }
  38808. if (computeFacetPositions && options) {
  38809. // compute and the facet barycenter coordinates in the array facetPositions
  38810. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38811. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38812. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38813. }
  38814. if (computeFacetPartitioning && options) {
  38815. // store the facet indexes in arrays in the main facetPartitioning array :
  38816. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38817. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38818. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38819. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38820. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38821. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38822. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38823. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38824. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38825. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38826. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38827. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38828. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38829. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38830. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38831. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38832. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38833. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38834. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38835. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38836. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38837. // push each facet index in each block containing the vertex
  38838. options.facetPartitioning[block_idx_v1].push(index);
  38839. if (block_idx_v2 != block_idx_v1) {
  38840. options.facetPartitioning[block_idx_v2].push(index);
  38841. }
  38842. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38843. options.facetPartitioning[block_idx_v3].push(index);
  38844. }
  38845. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38846. options.facetPartitioning[block_idx_o].push(index);
  38847. }
  38848. }
  38849. if (computeDepthSort && options && options.facetPositions) {
  38850. var dsf = depthSortedFacets[index];
  38851. dsf.ind = index * 3;
  38852. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38853. }
  38854. // compute the normals anyway
  38855. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38856. normals[v1y] += faceNormaly;
  38857. normals[v1z] += faceNormalz;
  38858. normals[v2x] += faceNormalx;
  38859. normals[v2y] += faceNormaly;
  38860. normals[v2z] += faceNormalz;
  38861. normals[v3x] += faceNormalx;
  38862. normals[v3y] += faceNormaly;
  38863. normals[v3z] += faceNormalz;
  38864. }
  38865. // last normalization of each normal
  38866. for (index = 0; index < normals.length / 3; index++) {
  38867. faceNormalx = normals[index * 3];
  38868. faceNormaly = normals[index * 3 + 1];
  38869. faceNormalz = normals[index * 3 + 2];
  38870. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38871. length = (length === 0) ? 1.0 : length;
  38872. faceNormalx /= length;
  38873. faceNormaly /= length;
  38874. faceNormalz /= length;
  38875. normals[index * 3] = faceNormalx;
  38876. normals[index * 3 + 1] = faceNormaly;
  38877. normals[index * 3 + 2] = faceNormalz;
  38878. }
  38879. };
  38880. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38881. var li = indices.length;
  38882. var ln = normals.length;
  38883. var i;
  38884. var n;
  38885. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38886. switch (sideOrientation) {
  38887. case BABYLON.Mesh.FRONTSIDE:
  38888. // nothing changed
  38889. break;
  38890. case BABYLON.Mesh.BACKSIDE:
  38891. var tmp;
  38892. // indices
  38893. for (i = 0; i < li; i += 3) {
  38894. tmp = indices[i];
  38895. indices[i] = indices[i + 2];
  38896. indices[i + 2] = tmp;
  38897. }
  38898. // normals
  38899. for (n = 0; n < ln; n++) {
  38900. normals[n] = -normals[n];
  38901. }
  38902. break;
  38903. case BABYLON.Mesh.DOUBLESIDE:
  38904. // positions
  38905. var lp = positions.length;
  38906. var l = lp / 3;
  38907. for (var p = 0; p < lp; p++) {
  38908. positions[lp + p] = positions[p];
  38909. }
  38910. // indices
  38911. for (i = 0; i < li; i += 3) {
  38912. indices[i + li] = indices[i + 2] + l;
  38913. indices[i + 1 + li] = indices[i + 1] + l;
  38914. indices[i + 2 + li] = indices[i] + l;
  38915. }
  38916. // normals
  38917. for (n = 0; n < ln; n++) {
  38918. normals[ln + n] = -normals[n];
  38919. }
  38920. // uvs
  38921. var lu = uvs.length;
  38922. var u = 0;
  38923. for (u = 0; u < lu; u++) {
  38924. uvs[u + lu] = uvs[u];
  38925. }
  38926. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38927. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38928. u = 0;
  38929. for (i = 0; i < lu / 2; i++) {
  38930. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38931. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38932. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38933. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38934. u += 2;
  38935. }
  38936. break;
  38937. }
  38938. };
  38939. /**
  38940. * Applies VertexData created from the imported parameters to the geometry
  38941. * @param parsedVertexData the parsed data from an imported file
  38942. * @param geometry the geometry to apply the VertexData to
  38943. */
  38944. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38945. var vertexData = new VertexData();
  38946. // positions
  38947. var positions = parsedVertexData.positions;
  38948. if (positions) {
  38949. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38950. }
  38951. // normals
  38952. var normals = parsedVertexData.normals;
  38953. if (normals) {
  38954. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38955. }
  38956. // tangents
  38957. var tangents = parsedVertexData.tangents;
  38958. if (tangents) {
  38959. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38960. }
  38961. // uvs
  38962. var uvs = parsedVertexData.uvs;
  38963. if (uvs) {
  38964. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38965. }
  38966. // uv2s
  38967. var uv2s = parsedVertexData.uv2s;
  38968. if (uv2s) {
  38969. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38970. }
  38971. // uv3s
  38972. var uv3s = parsedVertexData.uv3s;
  38973. if (uv3s) {
  38974. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38975. }
  38976. // uv4s
  38977. var uv4s = parsedVertexData.uv4s;
  38978. if (uv4s) {
  38979. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38980. }
  38981. // uv5s
  38982. var uv5s = parsedVertexData.uv5s;
  38983. if (uv5s) {
  38984. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38985. }
  38986. // uv6s
  38987. var uv6s = parsedVertexData.uv6s;
  38988. if (uv6s) {
  38989. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38990. }
  38991. // colors
  38992. var colors = parsedVertexData.colors;
  38993. if (colors) {
  38994. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38995. }
  38996. // matricesIndices
  38997. var matricesIndices = parsedVertexData.matricesIndices;
  38998. if (matricesIndices) {
  38999. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39000. }
  39001. // matricesWeights
  39002. var matricesWeights = parsedVertexData.matricesWeights;
  39003. if (matricesWeights) {
  39004. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39005. }
  39006. // indices
  39007. var indices = parsedVertexData.indices;
  39008. if (indices) {
  39009. vertexData.indices = indices;
  39010. }
  39011. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39012. };
  39013. return VertexData;
  39014. }());
  39015. BABYLON.VertexData = VertexData;
  39016. })(BABYLON || (BABYLON = {}));
  39017. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39018. var BABYLON;
  39019. (function (BABYLON) {
  39020. /**
  39021. * Class used to store geometry data (vertex buffers + index buffer)
  39022. */
  39023. var Geometry = /** @class */ (function () {
  39024. /**
  39025. * Creates a new geometry
  39026. * @param id defines the unique ID
  39027. * @param scene defines the hosting scene
  39028. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  39029. * @param updatable defines if geometry must be updatable (false by default)
  39030. * @param mesh defines the mesh that will be associated with the geometry
  39031. */
  39032. function Geometry(id, scene, vertexData, updatable, mesh) {
  39033. if (updatable === void 0) { updatable = false; }
  39034. if (mesh === void 0) { mesh = null; }
  39035. /**
  39036. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39037. */
  39038. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39039. this._totalVertices = 0;
  39040. this._isDisposed = false;
  39041. this._indexBufferIsUpdatable = false;
  39042. this.id = id;
  39043. this._engine = scene.getEngine();
  39044. this._meshes = [];
  39045. this._scene = scene;
  39046. //Init vertex buffer cache
  39047. this._vertexBuffers = {};
  39048. this._indices = [];
  39049. this._updatable = updatable;
  39050. // vertexData
  39051. if (vertexData) {
  39052. this.setAllVerticesData(vertexData, updatable);
  39053. }
  39054. else {
  39055. this._totalVertices = 0;
  39056. this._indices = [];
  39057. }
  39058. if (this._engine.getCaps().vertexArrayObject) {
  39059. this._vertexArrayObjects = {};
  39060. }
  39061. // applyToMesh
  39062. if (mesh) {
  39063. if (mesh.getClassName() === "LinesMesh") {
  39064. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39065. this._updateExtend();
  39066. }
  39067. this.applyToMesh(mesh);
  39068. mesh.computeWorldMatrix(true);
  39069. }
  39070. }
  39071. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39072. /**
  39073. * 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
  39074. */
  39075. get: function () {
  39076. return this._boundingBias;
  39077. },
  39078. /**
  39079. * 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
  39080. */
  39081. set: function (value) {
  39082. if (this._boundingBias && this._boundingBias.equals(value)) {
  39083. return;
  39084. }
  39085. this._boundingBias = value.clone();
  39086. this._updateBoundingInfo(true, null);
  39087. },
  39088. enumerable: true,
  39089. configurable: true
  39090. });
  39091. /**
  39092. * Static function used to attach a new empty geometry to a mesh
  39093. * @param mesh defines the mesh to attach the geometry to
  39094. * @returns the new {BABYLON.Geometry}
  39095. */
  39096. Geometry.CreateGeometryForMesh = function (mesh) {
  39097. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39098. geometry.applyToMesh(mesh);
  39099. return geometry;
  39100. };
  39101. Object.defineProperty(Geometry.prototype, "extend", {
  39102. /**
  39103. * Gets the current extend of the geometry
  39104. */
  39105. get: function () {
  39106. return this._extend;
  39107. },
  39108. enumerable: true,
  39109. configurable: true
  39110. });
  39111. /**
  39112. * Gets the hosting scene
  39113. * @returns the hosting {BABYLON.Scene}
  39114. */
  39115. Geometry.prototype.getScene = function () {
  39116. return this._scene;
  39117. };
  39118. /**
  39119. * Gets the hosting engine
  39120. * @returns the hosting {BABYLON.Engine}
  39121. */
  39122. Geometry.prototype.getEngine = function () {
  39123. return this._engine;
  39124. };
  39125. /**
  39126. * Defines if the geometry is ready to use
  39127. * @returns true if the geometry is ready to be used
  39128. */
  39129. Geometry.prototype.isReady = function () {
  39130. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39131. };
  39132. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39133. /**
  39134. * Gets a value indicating that the geometry should not be serialized
  39135. */
  39136. get: function () {
  39137. for (var index = 0; index < this._meshes.length; index++) {
  39138. if (!this._meshes[index].doNotSerialize) {
  39139. return false;
  39140. }
  39141. }
  39142. return true;
  39143. },
  39144. enumerable: true,
  39145. configurable: true
  39146. });
  39147. /** @hidden */
  39148. Geometry.prototype._rebuild = function () {
  39149. if (this._vertexArrayObjects) {
  39150. this._vertexArrayObjects = {};
  39151. }
  39152. // Index buffer
  39153. if (this._meshes.length !== 0 && this._indices) {
  39154. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39155. }
  39156. // Vertex buffers
  39157. for (var key in this._vertexBuffers) {
  39158. var vertexBuffer = this._vertexBuffers[key];
  39159. vertexBuffer._rebuild();
  39160. }
  39161. };
  39162. /**
  39163. * Affects all geometry data in one call
  39164. * @param vertexData defines the geometry data
  39165. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39166. */
  39167. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39168. vertexData.applyToGeometry(this, updatable);
  39169. this.notifyUpdate();
  39170. };
  39171. /**
  39172. * Set specific vertex data
  39173. * @param kind defines the data kind (Position, normal, etc...)
  39174. * @param data defines the vertex data to use
  39175. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39176. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39177. */
  39178. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39179. if (updatable === void 0) { updatable = false; }
  39180. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39181. this.setVerticesBuffer(buffer);
  39182. };
  39183. /**
  39184. * Removes a specific vertex data
  39185. * @param kind defines the data kind (Position, normal, etc...)
  39186. */
  39187. Geometry.prototype.removeVerticesData = function (kind) {
  39188. if (this._vertexBuffers[kind]) {
  39189. this._vertexBuffers[kind].dispose();
  39190. delete this._vertexBuffers[kind];
  39191. }
  39192. };
  39193. /**
  39194. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39195. * @param buffer defines the vertex buffer to use
  39196. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39197. */
  39198. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39199. if (totalVertices === void 0) { totalVertices = null; }
  39200. var kind = buffer.getKind();
  39201. if (this._vertexBuffers[kind]) {
  39202. this._vertexBuffers[kind].dispose();
  39203. }
  39204. this._vertexBuffers[kind] = buffer;
  39205. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39206. var data = buffer.getData();
  39207. if (totalVertices != null) {
  39208. this._totalVertices = totalVertices;
  39209. }
  39210. else {
  39211. if (data != null) {
  39212. this._totalVertices = data.length / (buffer.byteStride / 4);
  39213. }
  39214. }
  39215. this._updateExtend(data);
  39216. this._resetPointsArrayCache();
  39217. var meshes = this._meshes;
  39218. var numOfMeshes = meshes.length;
  39219. for (var index = 0; index < numOfMeshes; index++) {
  39220. var mesh = meshes[index];
  39221. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39222. mesh._createGlobalSubMesh(false);
  39223. mesh.computeWorldMatrix(true);
  39224. }
  39225. }
  39226. this.notifyUpdate(kind);
  39227. if (this._vertexArrayObjects) {
  39228. this._disposeVertexArrayObjects();
  39229. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39230. }
  39231. };
  39232. /**
  39233. * Update a specific vertex buffer
  39234. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39235. * It will do nothing if the buffer is not updatable
  39236. * @param kind defines the data kind (Position, normal, etc...)
  39237. * @param data defines the data to use
  39238. * @param offset defines the offset in the target buffer where to store the data
  39239. * @param useBytes set to true if the offset is in bytes
  39240. */
  39241. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39242. if (useBytes === void 0) { useBytes = false; }
  39243. var vertexBuffer = this.getVertexBuffer(kind);
  39244. if (!vertexBuffer) {
  39245. return;
  39246. }
  39247. vertexBuffer.updateDirectly(data, offset, useBytes);
  39248. this.notifyUpdate(kind);
  39249. };
  39250. /**
  39251. * Update a specific vertex buffer
  39252. * This function will create a new buffer if the current one is not updatable
  39253. * @param kind defines the data kind (Position, normal, etc...)
  39254. * @param data defines the data to use
  39255. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39256. */
  39257. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39258. if (updateExtends === void 0) { updateExtends = false; }
  39259. var vertexBuffer = this.getVertexBuffer(kind);
  39260. if (!vertexBuffer) {
  39261. return;
  39262. }
  39263. vertexBuffer.update(data);
  39264. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39265. this._updateBoundingInfo(updateExtends, data);
  39266. }
  39267. this.notifyUpdate(kind);
  39268. };
  39269. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39270. if (updateExtends) {
  39271. this._updateExtend(data);
  39272. }
  39273. var meshes = this._meshes;
  39274. var numOfMeshes = meshes.length;
  39275. this._resetPointsArrayCache();
  39276. for (var index = 0; index < numOfMeshes; index++) {
  39277. var mesh = meshes[index];
  39278. if (updateExtends) {
  39279. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39280. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39281. var subMesh = mesh.subMeshes[subIndex];
  39282. subMesh.refreshBoundingInfo();
  39283. }
  39284. }
  39285. }
  39286. };
  39287. /** @hidden */
  39288. Geometry.prototype._bind = function (effect, indexToBind) {
  39289. if (!effect) {
  39290. return;
  39291. }
  39292. if (indexToBind === undefined) {
  39293. indexToBind = this._indexBuffer;
  39294. }
  39295. var vbs = this.getVertexBuffers();
  39296. if (!vbs) {
  39297. return;
  39298. }
  39299. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39300. this._engine.bindBuffers(vbs, indexToBind, effect);
  39301. return;
  39302. }
  39303. // Using VAO
  39304. if (!this._vertexArrayObjects[effect.key]) {
  39305. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39306. }
  39307. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39308. };
  39309. /**
  39310. * Gets total number of vertices
  39311. * @returns the total number of vertices
  39312. */
  39313. Geometry.prototype.getTotalVertices = function () {
  39314. if (!this.isReady()) {
  39315. return 0;
  39316. }
  39317. return this._totalVertices;
  39318. };
  39319. /**
  39320. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39321. * @param kind defines the data kind (Position, normal, etc...)
  39322. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39323. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39324. * @returns a float array containing vertex data
  39325. */
  39326. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39327. var vertexBuffer = this.getVertexBuffer(kind);
  39328. if (!vertexBuffer) {
  39329. return null;
  39330. }
  39331. var data = vertexBuffer.getData();
  39332. if (!data) {
  39333. return null;
  39334. }
  39335. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39336. var count = this._totalVertices * vertexBuffer.getSize();
  39337. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39338. var copy_1 = new Array(count);
  39339. vertexBuffer.forEach(count, function (value, index) {
  39340. copy_1[index] = value;
  39341. });
  39342. return copy_1;
  39343. }
  39344. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39345. if (data instanceof Array) {
  39346. var offset = vertexBuffer.byteOffset / 4;
  39347. return BABYLON.Tools.Slice(data, offset, offset + count);
  39348. }
  39349. else if (data instanceof ArrayBuffer) {
  39350. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39351. }
  39352. else {
  39353. var offset = data.byteOffset + vertexBuffer.byteOffset;
  39354. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39355. var result = new Float32Array(count);
  39356. var source = new Float32Array(data.buffer, offset, count);
  39357. result.set(source);
  39358. return result;
  39359. }
  39360. return new Float32Array(data.buffer, offset, count);
  39361. }
  39362. }
  39363. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39364. return BABYLON.Tools.Slice(data);
  39365. }
  39366. return data;
  39367. };
  39368. /**
  39369. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39370. * @param kind defines the data kind (Position, normal, etc...)
  39371. * @returns true if the vertex buffer with the specified kind is updatable
  39372. */
  39373. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39374. var vb = this._vertexBuffers[kind];
  39375. if (!vb) {
  39376. return false;
  39377. }
  39378. return vb.isUpdatable();
  39379. };
  39380. /**
  39381. * Gets a specific vertex buffer
  39382. * @param kind defines the data kind (Position, normal, etc...)
  39383. * @returns a {BABYLON.VertexBuffer}
  39384. */
  39385. Geometry.prototype.getVertexBuffer = function (kind) {
  39386. if (!this.isReady()) {
  39387. return null;
  39388. }
  39389. return this._vertexBuffers[kind];
  39390. };
  39391. /**
  39392. * Returns all vertex buffers
  39393. * @return an object holding all vertex buffers indexed by kind
  39394. */
  39395. Geometry.prototype.getVertexBuffers = function () {
  39396. if (!this.isReady()) {
  39397. return null;
  39398. }
  39399. return this._vertexBuffers;
  39400. };
  39401. /**
  39402. * Gets a boolean indicating if specific vertex buffer is present
  39403. * @param kind defines the data kind (Position, normal, etc...)
  39404. * @returns true if data is present
  39405. */
  39406. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39407. if (!this._vertexBuffers) {
  39408. if (this._delayInfo) {
  39409. return this._delayInfo.indexOf(kind) !== -1;
  39410. }
  39411. return false;
  39412. }
  39413. return this._vertexBuffers[kind] !== undefined;
  39414. };
  39415. /**
  39416. * Gets a list of all attached data kinds (Position, normal, etc...)
  39417. * @returns a list of string containing all kinds
  39418. */
  39419. Geometry.prototype.getVerticesDataKinds = function () {
  39420. var result = [];
  39421. var kind;
  39422. if (!this._vertexBuffers && this._delayInfo) {
  39423. for (kind in this._delayInfo) {
  39424. result.push(kind);
  39425. }
  39426. }
  39427. else {
  39428. for (kind in this._vertexBuffers) {
  39429. result.push(kind);
  39430. }
  39431. }
  39432. return result;
  39433. };
  39434. /**
  39435. * Update index buffer
  39436. * @param indices defines the indices to store in the index buffer
  39437. * @param offset defines the offset in the target buffer where to store the data
  39438. */
  39439. Geometry.prototype.updateIndices = function (indices, offset) {
  39440. if (!this._indexBuffer) {
  39441. return;
  39442. }
  39443. if (!this._indexBufferIsUpdatable) {
  39444. this.setIndices(indices, null, true);
  39445. }
  39446. else {
  39447. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39448. }
  39449. };
  39450. /**
  39451. * Creates a new index buffer
  39452. * @param indices defines the indices to store in the index buffer
  39453. * @param totalVertices defines the total number of vertices (could be null)
  39454. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39455. */
  39456. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39457. if (totalVertices === void 0) { totalVertices = null; }
  39458. if (updatable === void 0) { updatable = false; }
  39459. if (this._indexBuffer) {
  39460. this._engine._releaseBuffer(this._indexBuffer);
  39461. }
  39462. this._disposeVertexArrayObjects();
  39463. this._indices = indices;
  39464. this._indexBufferIsUpdatable = updatable;
  39465. if (this._meshes.length !== 0 && this._indices) {
  39466. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39467. }
  39468. if (totalVertices != undefined) { // including null and undefined
  39469. this._totalVertices = totalVertices;
  39470. }
  39471. var meshes = this._meshes;
  39472. var numOfMeshes = meshes.length;
  39473. for (var index = 0; index < numOfMeshes; index++) {
  39474. meshes[index]._createGlobalSubMesh(true);
  39475. }
  39476. this.notifyUpdate();
  39477. };
  39478. /**
  39479. * Return the total number of indices
  39480. * @returns the total number of indices
  39481. */
  39482. Geometry.prototype.getTotalIndices = function () {
  39483. if (!this.isReady()) {
  39484. return 0;
  39485. }
  39486. return this._indices.length;
  39487. };
  39488. /**
  39489. * Gets the index buffer array
  39490. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39491. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39492. * @returns the index buffer array
  39493. */
  39494. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  39495. if (!this.isReady()) {
  39496. return null;
  39497. }
  39498. var orig = this._indices;
  39499. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39500. return orig;
  39501. }
  39502. else {
  39503. var len = orig.length;
  39504. var copy = [];
  39505. for (var i = 0; i < len; i++) {
  39506. copy.push(orig[i]);
  39507. }
  39508. return copy;
  39509. }
  39510. };
  39511. /**
  39512. * Gets the index buffer
  39513. * @return the index buffer
  39514. */
  39515. Geometry.prototype.getIndexBuffer = function () {
  39516. if (!this.isReady()) {
  39517. return null;
  39518. }
  39519. return this._indexBuffer;
  39520. };
  39521. /** @hidden */
  39522. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39523. if (effect === void 0) { effect = null; }
  39524. if (!effect || !this._vertexArrayObjects) {
  39525. return;
  39526. }
  39527. if (this._vertexArrayObjects[effect.key]) {
  39528. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39529. delete this._vertexArrayObjects[effect.key];
  39530. }
  39531. };
  39532. /**
  39533. * Release the associated resources for a specific mesh
  39534. * @param mesh defines the source mesh
  39535. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39536. */
  39537. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39538. var meshes = this._meshes;
  39539. var index = meshes.indexOf(mesh);
  39540. if (index === -1) {
  39541. return;
  39542. }
  39543. meshes.splice(index, 1);
  39544. mesh._geometry = null;
  39545. if (meshes.length === 0 && shouldDispose) {
  39546. this.dispose();
  39547. }
  39548. };
  39549. /**
  39550. * Apply current geometry to a given mesh
  39551. * @param mesh defines the mesh to apply geometry to
  39552. */
  39553. Geometry.prototype.applyToMesh = function (mesh) {
  39554. if (mesh._geometry === this) {
  39555. return;
  39556. }
  39557. var previousGeometry = mesh._geometry;
  39558. if (previousGeometry) {
  39559. previousGeometry.releaseForMesh(mesh);
  39560. }
  39561. var meshes = this._meshes;
  39562. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39563. mesh._geometry = this;
  39564. this._scene.pushGeometry(this);
  39565. meshes.push(mesh);
  39566. if (this.isReady()) {
  39567. this._applyToMesh(mesh);
  39568. }
  39569. else {
  39570. mesh._boundingInfo = this._boundingInfo;
  39571. }
  39572. };
  39573. Geometry.prototype._updateExtend = function (data) {
  39574. if (data === void 0) { data = null; }
  39575. if (!data) {
  39576. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39577. }
  39578. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39579. };
  39580. Geometry.prototype._applyToMesh = function (mesh) {
  39581. var numOfMeshes = this._meshes.length;
  39582. // vertexBuffers
  39583. for (var kind in this._vertexBuffers) {
  39584. if (numOfMeshes === 1) {
  39585. this._vertexBuffers[kind].create();
  39586. }
  39587. var buffer = this._vertexBuffers[kind].getBuffer();
  39588. if (buffer)
  39589. buffer.references = numOfMeshes;
  39590. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39591. if (!this._extend) {
  39592. this._updateExtend();
  39593. }
  39594. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39595. mesh._createGlobalSubMesh(false);
  39596. //bounding info was just created again, world matrix should be applied again.
  39597. mesh._updateBoundingInfo();
  39598. }
  39599. }
  39600. // indexBuffer
  39601. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39602. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39603. }
  39604. if (this._indexBuffer) {
  39605. this._indexBuffer.references = numOfMeshes;
  39606. }
  39607. };
  39608. Geometry.prototype.notifyUpdate = function (kind) {
  39609. if (this.onGeometryUpdated) {
  39610. this.onGeometryUpdated(this, kind);
  39611. }
  39612. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39613. var mesh = _a[_i];
  39614. mesh._markSubMeshesAsAttributesDirty();
  39615. }
  39616. };
  39617. /**
  39618. * Load the geometry if it was flagged as delay loaded
  39619. * @param scene defines the hosting scene
  39620. * @param onLoaded defines a callback called when the geometry is loaded
  39621. */
  39622. Geometry.prototype.load = function (scene, onLoaded) {
  39623. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39624. return;
  39625. }
  39626. if (this.isReady()) {
  39627. if (onLoaded) {
  39628. onLoaded();
  39629. }
  39630. return;
  39631. }
  39632. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39633. this._queueLoad(scene, onLoaded);
  39634. };
  39635. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39636. var _this = this;
  39637. if (!this.delayLoadingFile) {
  39638. return;
  39639. }
  39640. scene._addPendingData(this);
  39641. scene._loadFile(this.delayLoadingFile, function (data) {
  39642. if (!_this._delayLoadingFunction) {
  39643. return;
  39644. }
  39645. _this._delayLoadingFunction(JSON.parse(data), _this);
  39646. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39647. _this._delayInfo = [];
  39648. scene._removePendingData(_this);
  39649. var meshes = _this._meshes;
  39650. var numOfMeshes = meshes.length;
  39651. for (var index = 0; index < numOfMeshes; index++) {
  39652. _this._applyToMesh(meshes[index]);
  39653. }
  39654. if (onLoaded) {
  39655. onLoaded();
  39656. }
  39657. }, undefined, true);
  39658. };
  39659. /**
  39660. * Invert the geometry to move from a right handed system to a left handed one.
  39661. */
  39662. Geometry.prototype.toLeftHanded = function () {
  39663. // Flip faces
  39664. var tIndices = this.getIndices(false);
  39665. if (tIndices != null && tIndices.length > 0) {
  39666. for (var i = 0; i < tIndices.length; i += 3) {
  39667. var tTemp = tIndices[i + 0];
  39668. tIndices[i + 0] = tIndices[i + 2];
  39669. tIndices[i + 2] = tTemp;
  39670. }
  39671. this.setIndices(tIndices);
  39672. }
  39673. // Negate position.z
  39674. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39675. if (tPositions != null && tPositions.length > 0) {
  39676. for (var i = 0; i < tPositions.length; i += 3) {
  39677. tPositions[i + 2] = -tPositions[i + 2];
  39678. }
  39679. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39680. }
  39681. // Negate normal.z
  39682. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39683. if (tNormals != null && tNormals.length > 0) {
  39684. for (var i = 0; i < tNormals.length; i += 3) {
  39685. tNormals[i + 2] = -tNormals[i + 2];
  39686. }
  39687. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39688. }
  39689. };
  39690. // Cache
  39691. /** @hidden */
  39692. Geometry.prototype._resetPointsArrayCache = function () {
  39693. this._positions = null;
  39694. };
  39695. /** @hidden */
  39696. Geometry.prototype._generatePointsArray = function () {
  39697. if (this._positions)
  39698. return true;
  39699. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39700. if (!data || data.length === 0) {
  39701. return false;
  39702. }
  39703. this._positions = [];
  39704. for (var index = 0; index < data.length; index += 3) {
  39705. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39706. }
  39707. return true;
  39708. };
  39709. /**
  39710. * Gets a value indicating if the geometry is disposed
  39711. * @returns true if the geometry was disposed
  39712. */
  39713. Geometry.prototype.isDisposed = function () {
  39714. return this._isDisposed;
  39715. };
  39716. Geometry.prototype._disposeVertexArrayObjects = function () {
  39717. if (this._vertexArrayObjects) {
  39718. for (var kind in this._vertexArrayObjects) {
  39719. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39720. }
  39721. this._vertexArrayObjects = {};
  39722. }
  39723. };
  39724. /**
  39725. * Free all associated resources
  39726. */
  39727. Geometry.prototype.dispose = function () {
  39728. var meshes = this._meshes;
  39729. var numOfMeshes = meshes.length;
  39730. var index;
  39731. for (index = 0; index < numOfMeshes; index++) {
  39732. this.releaseForMesh(meshes[index]);
  39733. }
  39734. this._meshes = [];
  39735. this._disposeVertexArrayObjects();
  39736. for (var kind in this._vertexBuffers) {
  39737. this._vertexBuffers[kind].dispose();
  39738. }
  39739. this._vertexBuffers = {};
  39740. this._totalVertices = 0;
  39741. if (this._indexBuffer) {
  39742. this._engine._releaseBuffer(this._indexBuffer);
  39743. }
  39744. this._indexBuffer = null;
  39745. this._indices = [];
  39746. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39747. this.delayLoadingFile = null;
  39748. this._delayLoadingFunction = null;
  39749. this._delayInfo = [];
  39750. this._boundingInfo = null;
  39751. this._scene.removeGeometry(this);
  39752. this._isDisposed = true;
  39753. };
  39754. /**
  39755. * Clone the current geometry into a new geometry
  39756. * @param id defines the unique ID of the new geometry
  39757. * @returns a new geometry object
  39758. */
  39759. Geometry.prototype.copy = function (id) {
  39760. var vertexData = new BABYLON.VertexData();
  39761. vertexData.indices = [];
  39762. var indices = this.getIndices();
  39763. if (indices) {
  39764. for (var index = 0; index < indices.length; index++) {
  39765. vertexData.indices.push(indices[index]);
  39766. }
  39767. }
  39768. var updatable = false;
  39769. var stopChecking = false;
  39770. var kind;
  39771. for (kind in this._vertexBuffers) {
  39772. // using slice() to make a copy of the array and not just reference it
  39773. var data = this.getVerticesData(kind);
  39774. if (data instanceof Float32Array) {
  39775. vertexData.set(new Float32Array(data), kind);
  39776. }
  39777. else {
  39778. vertexData.set(data.slice(0), kind);
  39779. }
  39780. if (!stopChecking) {
  39781. var vb = this.getVertexBuffer(kind);
  39782. if (vb) {
  39783. updatable = vb.isUpdatable();
  39784. stopChecking = !updatable;
  39785. }
  39786. }
  39787. }
  39788. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39789. geometry.delayLoadState = this.delayLoadState;
  39790. geometry.delayLoadingFile = this.delayLoadingFile;
  39791. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39792. for (kind in this._delayInfo) {
  39793. geometry._delayInfo = geometry._delayInfo || [];
  39794. geometry._delayInfo.push(kind);
  39795. }
  39796. // Bounding info
  39797. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39798. return geometry;
  39799. };
  39800. /**
  39801. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39802. * @return a JSON representation of the current geometry data (without the vertices data)
  39803. */
  39804. Geometry.prototype.serialize = function () {
  39805. var serializationObject = {};
  39806. serializationObject.id = this.id;
  39807. serializationObject.updatable = this._updatable;
  39808. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39809. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39810. }
  39811. return serializationObject;
  39812. };
  39813. Geometry.prototype.toNumberArray = function (origin) {
  39814. if (Array.isArray(origin)) {
  39815. return origin;
  39816. }
  39817. else {
  39818. return Array.prototype.slice.call(origin);
  39819. }
  39820. };
  39821. /**
  39822. * Serialize all vertices data into a JSON oject
  39823. * @returns a JSON representation of the current geometry data
  39824. */
  39825. Geometry.prototype.serializeVerticeData = function () {
  39826. var serializationObject = this.serialize();
  39827. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39828. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39829. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39830. serializationObject.positions._updatable = true;
  39831. }
  39832. }
  39833. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39834. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39835. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39836. serializationObject.normals._updatable = true;
  39837. }
  39838. }
  39839. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39840. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39841. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39842. serializationObject.tangets._updatable = true;
  39843. }
  39844. }
  39845. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39846. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39847. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39848. serializationObject.uvs._updatable = true;
  39849. }
  39850. }
  39851. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39852. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39853. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39854. serializationObject.uv2s._updatable = true;
  39855. }
  39856. }
  39857. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39858. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39859. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39860. serializationObject.uv3s._updatable = true;
  39861. }
  39862. }
  39863. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39864. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39865. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39866. serializationObject.uv4s._updatable = true;
  39867. }
  39868. }
  39869. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39870. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39871. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39872. serializationObject.uv5s._updatable = true;
  39873. }
  39874. }
  39875. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39876. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39877. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39878. serializationObject.uv6s._updatable = true;
  39879. }
  39880. }
  39881. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39882. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39883. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39884. serializationObject.colors._updatable = true;
  39885. }
  39886. }
  39887. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39888. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39889. serializationObject.matricesIndices._isExpanded = true;
  39890. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39891. serializationObject.matricesIndices._updatable = true;
  39892. }
  39893. }
  39894. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39895. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39896. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39897. serializationObject.matricesWeights._updatable = true;
  39898. }
  39899. }
  39900. serializationObject.indices = this.toNumberArray(this.getIndices());
  39901. return serializationObject;
  39902. };
  39903. // Statics
  39904. /**
  39905. * Extracts a clone of a mesh geometry
  39906. * @param mesh defines the source mesh
  39907. * @param id defines the unique ID of the new geometry object
  39908. * @returns the new geometry object
  39909. */
  39910. Geometry.ExtractFromMesh = function (mesh, id) {
  39911. var geometry = mesh._geometry;
  39912. if (!geometry) {
  39913. return null;
  39914. }
  39915. return geometry.copy(id);
  39916. };
  39917. /**
  39918. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39919. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39920. * Be aware Math.random() could cause collisions, but:
  39921. * "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"
  39922. * @returns a string containing a new GUID
  39923. */
  39924. Geometry.RandomId = function () {
  39925. return BABYLON.Tools.RandomId();
  39926. };
  39927. /** @hidden */
  39928. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39929. var scene = mesh.getScene();
  39930. // Geometry
  39931. var geometryId = parsedGeometry.geometryId;
  39932. if (geometryId) {
  39933. var geometry = scene.getGeometryByID(geometryId);
  39934. if (geometry) {
  39935. geometry.applyToMesh(mesh);
  39936. }
  39937. }
  39938. else if (parsedGeometry instanceof ArrayBuffer) {
  39939. var binaryInfo = mesh._binaryInfo;
  39940. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39941. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39942. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39943. }
  39944. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39945. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39946. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39947. }
  39948. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39949. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39950. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39951. }
  39952. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39953. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39954. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39955. }
  39956. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39957. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39958. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39959. }
  39960. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39961. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39962. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39963. }
  39964. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39965. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39966. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39967. }
  39968. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39969. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39970. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39971. }
  39972. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39973. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39974. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39975. }
  39976. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39977. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39978. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39979. }
  39980. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39981. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39982. var floatIndices = [];
  39983. for (var i = 0; i < matricesIndicesData.length; i++) {
  39984. var index = matricesIndicesData[i];
  39985. floatIndices.push(index & 0x000000FF);
  39986. floatIndices.push((index & 0x0000FF00) >> 8);
  39987. floatIndices.push((index & 0x00FF0000) >> 16);
  39988. floatIndices.push(index >> 24);
  39989. }
  39990. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39991. }
  39992. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39993. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39994. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39995. }
  39996. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39997. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39998. mesh.setIndices(indicesData, null);
  39999. }
  40000. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40001. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40002. mesh.subMeshes = [];
  40003. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40004. var materialIndex = subMeshesData[(i * 5) + 0];
  40005. var verticesStart = subMeshesData[(i * 5) + 1];
  40006. var verticesCount = subMeshesData[(i * 5) + 2];
  40007. var indexStart = subMeshesData[(i * 5) + 3];
  40008. var indexCount = subMeshesData[(i * 5) + 4];
  40009. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40010. }
  40011. }
  40012. }
  40013. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40014. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40015. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40016. if (parsedGeometry.tangents) {
  40017. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40018. }
  40019. if (parsedGeometry.uvs) {
  40020. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40021. }
  40022. if (parsedGeometry.uvs2) {
  40023. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40024. }
  40025. if (parsedGeometry.uvs3) {
  40026. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40027. }
  40028. if (parsedGeometry.uvs4) {
  40029. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40030. }
  40031. if (parsedGeometry.uvs5) {
  40032. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40033. }
  40034. if (parsedGeometry.uvs6) {
  40035. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40036. }
  40037. if (parsedGeometry.colors) {
  40038. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40039. }
  40040. if (parsedGeometry.matricesIndices) {
  40041. if (!parsedGeometry.matricesIndices._isExpanded) {
  40042. var floatIndices = [];
  40043. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40044. var matricesIndex = parsedGeometry.matricesIndices[i];
  40045. floatIndices.push(matricesIndex & 0x000000FF);
  40046. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40047. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40048. floatIndices.push(matricesIndex >> 24);
  40049. }
  40050. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40051. }
  40052. else {
  40053. delete parsedGeometry.matricesIndices._isExpanded;
  40054. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40055. }
  40056. }
  40057. if (parsedGeometry.matricesIndicesExtra) {
  40058. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40059. var floatIndices = [];
  40060. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40061. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40062. floatIndices.push(matricesIndex & 0x000000FF);
  40063. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40064. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40065. floatIndices.push(matricesIndex >> 24);
  40066. }
  40067. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40068. }
  40069. else {
  40070. delete parsedGeometry.matricesIndices._isExpanded;
  40071. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40072. }
  40073. }
  40074. if (parsedGeometry.matricesWeights) {
  40075. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40076. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40077. }
  40078. if (parsedGeometry.matricesWeightsExtra) {
  40079. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40080. }
  40081. mesh.setIndices(parsedGeometry.indices, null);
  40082. }
  40083. // SubMeshes
  40084. if (parsedGeometry.subMeshes) {
  40085. mesh.subMeshes = [];
  40086. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40087. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40088. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40089. }
  40090. }
  40091. // Flat shading
  40092. if (mesh._shouldGenerateFlatShading) {
  40093. mesh.convertToFlatShadedMesh();
  40094. delete mesh._shouldGenerateFlatShading;
  40095. }
  40096. // Update
  40097. mesh.computeWorldMatrix(true);
  40098. scene.onMeshImportedObservable.notifyObservers(mesh);
  40099. };
  40100. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40101. var epsilon = 1e-3;
  40102. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40103. return;
  40104. }
  40105. var noInfluenceBoneIndex = 0.0;
  40106. if (parsedGeometry.skeletonId > -1) {
  40107. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40108. if (!skeleton) {
  40109. return;
  40110. }
  40111. noInfluenceBoneIndex = skeleton.bones.length;
  40112. }
  40113. else {
  40114. return;
  40115. }
  40116. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40117. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40118. var matricesWeights = parsedGeometry.matricesWeights;
  40119. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40120. var influencers = parsedGeometry.numBoneInfluencer;
  40121. var size = matricesWeights.length;
  40122. for (var i = 0; i < size; i += 4) {
  40123. var weight = 0.0;
  40124. var firstZeroWeight = -1;
  40125. for (var j = 0; j < 4; j++) {
  40126. var w = matricesWeights[i + j];
  40127. weight += w;
  40128. if (w < epsilon && firstZeroWeight < 0) {
  40129. firstZeroWeight = j;
  40130. }
  40131. }
  40132. if (matricesWeightsExtra) {
  40133. for (var j = 0; j < 4; j++) {
  40134. var w = matricesWeightsExtra[i + j];
  40135. weight += w;
  40136. if (w < epsilon && firstZeroWeight < 0) {
  40137. firstZeroWeight = j + 4;
  40138. }
  40139. }
  40140. }
  40141. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40142. firstZeroWeight = influencers - 1;
  40143. }
  40144. if (weight > epsilon) {
  40145. var mweight = 1.0 / weight;
  40146. for (var j = 0; j < 4; j++) {
  40147. matricesWeights[i + j] *= mweight;
  40148. }
  40149. if (matricesWeightsExtra) {
  40150. for (var j = 0; j < 4; j++) {
  40151. matricesWeightsExtra[i + j] *= mweight;
  40152. }
  40153. }
  40154. }
  40155. else {
  40156. if (firstZeroWeight >= 4) {
  40157. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40158. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40159. }
  40160. else {
  40161. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40162. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40163. }
  40164. }
  40165. }
  40166. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40167. if (parsedGeometry.matricesWeightsExtra) {
  40168. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40169. }
  40170. };
  40171. /**
  40172. * Create a new geometry from persisted data (Using .babylon file format)
  40173. * @param parsedVertexData defines the persisted data
  40174. * @param scene defines the hosting scene
  40175. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40176. * @returns the new geometry object
  40177. */
  40178. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40179. if (scene.getGeometryByID(parsedVertexData.id)) {
  40180. return null; // null since geometry could be something else than a box...
  40181. }
  40182. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40183. if (BABYLON.Tags) {
  40184. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40185. }
  40186. if (parsedVertexData.delayLoadingFile) {
  40187. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40188. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40189. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40190. geometry._delayInfo = [];
  40191. if (parsedVertexData.hasUVs) {
  40192. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40193. }
  40194. if (parsedVertexData.hasUVs2) {
  40195. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40196. }
  40197. if (parsedVertexData.hasUVs3) {
  40198. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40199. }
  40200. if (parsedVertexData.hasUVs4) {
  40201. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40202. }
  40203. if (parsedVertexData.hasUVs5) {
  40204. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40205. }
  40206. if (parsedVertexData.hasUVs6) {
  40207. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40208. }
  40209. if (parsedVertexData.hasColors) {
  40210. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40211. }
  40212. if (parsedVertexData.hasMatricesIndices) {
  40213. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40214. }
  40215. if (parsedVertexData.hasMatricesWeights) {
  40216. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40217. }
  40218. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40219. }
  40220. else {
  40221. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40222. }
  40223. scene.pushGeometry(geometry, true);
  40224. return geometry;
  40225. };
  40226. return Geometry;
  40227. }());
  40228. BABYLON.Geometry = Geometry;
  40229. // Primitives
  40230. /// Abstract class
  40231. /**
  40232. * Abstract class used to provide common services for all typed geometries
  40233. * @hidden
  40234. */
  40235. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40236. __extends(_PrimitiveGeometry, _super);
  40237. /**
  40238. * Creates a new typed geometry
  40239. * @param id defines the unique ID of the geometry
  40240. * @param scene defines the hosting scene
  40241. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40242. * @param mesh defines the hosting mesh (can be null)
  40243. */
  40244. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40245. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40246. if (mesh === void 0) { mesh = null; }
  40247. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40248. _this._canBeRegenerated = _canBeRegenerated;
  40249. _this._beingRegenerated = true;
  40250. _this.regenerate();
  40251. _this._beingRegenerated = false;
  40252. return _this;
  40253. }
  40254. /**
  40255. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40256. * @returns true if the geometry can be regenerated
  40257. */
  40258. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40259. return this._canBeRegenerated;
  40260. };
  40261. /**
  40262. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40263. */
  40264. _PrimitiveGeometry.prototype.regenerate = function () {
  40265. if (!this._canBeRegenerated) {
  40266. return;
  40267. }
  40268. this._beingRegenerated = true;
  40269. this.setAllVerticesData(this._regenerateVertexData(), false);
  40270. this._beingRegenerated = false;
  40271. };
  40272. /**
  40273. * Clone the geometry
  40274. * @param id defines the unique ID of the new geometry
  40275. * @returns the new geometry
  40276. */
  40277. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40278. return _super.prototype.copy.call(this, id);
  40279. };
  40280. // overrides
  40281. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40282. if (!this._beingRegenerated) {
  40283. return;
  40284. }
  40285. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40286. };
  40287. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40288. if (!this._beingRegenerated) {
  40289. return;
  40290. }
  40291. _super.prototype.setVerticesData.call(this, kind, data, false);
  40292. };
  40293. // to override
  40294. /** @hidden */
  40295. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40296. throw new Error("Abstract method");
  40297. };
  40298. _PrimitiveGeometry.prototype.copy = function (id) {
  40299. throw new Error("Must be overriden in sub-classes.");
  40300. };
  40301. _PrimitiveGeometry.prototype.serialize = function () {
  40302. var serializationObject = _super.prototype.serialize.call(this);
  40303. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40304. return serializationObject;
  40305. };
  40306. return _PrimitiveGeometry;
  40307. }(Geometry));
  40308. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40309. /**
  40310. * Creates a ribbon geometry
  40311. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40312. */
  40313. var RibbonGeometry = /** @class */ (function (_super) {
  40314. __extends(RibbonGeometry, _super);
  40315. /**
  40316. * Creates a ribbon geometry
  40317. * @param id defines the unique ID of the geometry
  40318. * @param scene defines the hosting scene
  40319. * @param pathArray defines the array of paths to use
  40320. * @param closeArray defines if the last path and the first path must be joined
  40321. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40322. * @param offset defines the offset between points
  40323. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40324. * @param mesh defines the hosting mesh (can be null)
  40325. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40326. */
  40327. function RibbonGeometry(id, scene,
  40328. /**
  40329. * Defines the array of paths to use
  40330. */
  40331. pathArray,
  40332. /**
  40333. * Defines if the last and first points of each path in your pathArray must be joined
  40334. */
  40335. closeArray,
  40336. /**
  40337. * Defines if the last and first points of each path in your pathArray must be joined
  40338. */
  40339. closePath,
  40340. /**
  40341. * Defines the offset between points
  40342. */
  40343. offset, canBeRegenerated, mesh,
  40344. /**
  40345. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40346. */
  40347. side) {
  40348. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40349. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40350. _this.pathArray = pathArray;
  40351. _this.closeArray = closeArray;
  40352. _this.closePath = closePath;
  40353. _this.offset = offset;
  40354. _this.side = side;
  40355. return _this;
  40356. }
  40357. /** @hidden */
  40358. RibbonGeometry.prototype._regenerateVertexData = function () {
  40359. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40360. };
  40361. RibbonGeometry.prototype.copy = function (id) {
  40362. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40363. };
  40364. return RibbonGeometry;
  40365. }(_PrimitiveGeometry));
  40366. BABYLON.RibbonGeometry = RibbonGeometry;
  40367. /**
  40368. * Creates a box geometry
  40369. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40370. */
  40371. var BoxGeometry = /** @class */ (function (_super) {
  40372. __extends(BoxGeometry, _super);
  40373. /**
  40374. * Creates a box geometry
  40375. * @param id defines the unique ID of the geometry
  40376. * @param scene defines the hosting scene
  40377. * @param size defines the zise of the box (width, height and depth are the same)
  40378. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40379. * @param mesh defines the hosting mesh (can be null)
  40380. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40381. */
  40382. function BoxGeometry(id, scene,
  40383. /**
  40384. * Defines the zise of the box (width, height and depth are the same)
  40385. */
  40386. size, canBeRegenerated, mesh,
  40387. /**
  40388. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40389. */
  40390. side) {
  40391. if (mesh === void 0) { mesh = null; }
  40392. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40393. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40394. _this.size = size;
  40395. _this.side = side;
  40396. return _this;
  40397. }
  40398. /** @hidden */
  40399. BoxGeometry.prototype._regenerateVertexData = function () {
  40400. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40401. };
  40402. BoxGeometry.prototype.copy = function (id) {
  40403. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40404. };
  40405. BoxGeometry.prototype.serialize = function () {
  40406. var serializationObject = _super.prototype.serialize.call(this);
  40407. serializationObject.size = this.size;
  40408. return serializationObject;
  40409. };
  40410. BoxGeometry.Parse = function (parsedBox, scene) {
  40411. if (scene.getGeometryByID(parsedBox.id)) {
  40412. return null; // null since geometry could be something else than a box...
  40413. }
  40414. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40415. if (BABYLON.Tags) {
  40416. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40417. }
  40418. scene.pushGeometry(box, true);
  40419. return box;
  40420. };
  40421. return BoxGeometry;
  40422. }(_PrimitiveGeometry));
  40423. BABYLON.BoxGeometry = BoxGeometry;
  40424. /**
  40425. * Creates a sphere geometry
  40426. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40427. */
  40428. var SphereGeometry = /** @class */ (function (_super) {
  40429. __extends(SphereGeometry, _super);
  40430. /**
  40431. * Create a new sphere geometry
  40432. * @param id defines the unique ID of the geometry
  40433. * @param scene defines the hosting scene
  40434. * @param segments defines the number of segments to use to create the sphere
  40435. * @param diameter defines the diameter of the sphere
  40436. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40437. * @param mesh defines the hosting mesh (can be null)
  40438. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40439. */
  40440. function SphereGeometry(id, scene,
  40441. /**
  40442. * Defines the number of segments to use to create the sphere
  40443. */
  40444. segments,
  40445. /**
  40446. * Defines the diameter of the sphere
  40447. */
  40448. diameter, canBeRegenerated, mesh,
  40449. /**
  40450. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40451. */
  40452. side) {
  40453. if (mesh === void 0) { mesh = null; }
  40454. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40455. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40456. _this.segments = segments;
  40457. _this.diameter = diameter;
  40458. _this.side = side;
  40459. return _this;
  40460. }
  40461. /** @hidden */
  40462. SphereGeometry.prototype._regenerateVertexData = function () {
  40463. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40464. };
  40465. SphereGeometry.prototype.copy = function (id) {
  40466. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40467. };
  40468. SphereGeometry.prototype.serialize = function () {
  40469. var serializationObject = _super.prototype.serialize.call(this);
  40470. serializationObject.segments = this.segments;
  40471. serializationObject.diameter = this.diameter;
  40472. return serializationObject;
  40473. };
  40474. SphereGeometry.Parse = function (parsedSphere, scene) {
  40475. if (scene.getGeometryByID(parsedSphere.id)) {
  40476. return null; // null since geometry could be something else than a sphere...
  40477. }
  40478. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40479. if (BABYLON.Tags) {
  40480. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40481. }
  40482. scene.pushGeometry(sphere, true);
  40483. return sphere;
  40484. };
  40485. return SphereGeometry;
  40486. }(_PrimitiveGeometry));
  40487. BABYLON.SphereGeometry = SphereGeometry;
  40488. /**
  40489. * Creates a disc geometry
  40490. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40491. */
  40492. var DiscGeometry = /** @class */ (function (_super) {
  40493. __extends(DiscGeometry, _super);
  40494. /**
  40495. * Creates a new disc geometry
  40496. * @param id defines the unique ID of the geometry
  40497. * @param scene defines the hosting scene
  40498. * @param radius defines the radius of the disc
  40499. * @param tessellation defines the tesselation factor to apply to the disc
  40500. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40501. * @param mesh defines the hosting mesh (can be null)
  40502. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40503. */
  40504. function DiscGeometry(id, scene,
  40505. /**
  40506. * Defines the radius of the disc
  40507. */
  40508. radius,
  40509. /**
  40510. * Defines the tesselation factor to apply to the disc
  40511. */
  40512. tessellation, canBeRegenerated, mesh,
  40513. /**
  40514. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40515. */
  40516. side) {
  40517. if (mesh === void 0) { mesh = null; }
  40518. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40519. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40520. _this.radius = radius;
  40521. _this.tessellation = tessellation;
  40522. _this.side = side;
  40523. return _this;
  40524. }
  40525. /** @hidden */
  40526. DiscGeometry.prototype._regenerateVertexData = function () {
  40527. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40528. };
  40529. DiscGeometry.prototype.copy = function (id) {
  40530. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40531. };
  40532. return DiscGeometry;
  40533. }(_PrimitiveGeometry));
  40534. BABYLON.DiscGeometry = DiscGeometry;
  40535. /**
  40536. * Creates a new cylinder geometry
  40537. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40538. */
  40539. var CylinderGeometry = /** @class */ (function (_super) {
  40540. __extends(CylinderGeometry, _super);
  40541. /**
  40542. * Creates a new cylinder geometry
  40543. * @param id defines the unique ID of the geometry
  40544. * @param scene defines the hosting scene
  40545. * @param height defines the height of the cylinder
  40546. * @param diameterTop defines the diameter of the cylinder's top cap
  40547. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40548. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40549. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40550. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40551. * @param mesh defines the hosting mesh (can be null)
  40552. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40553. */
  40554. function CylinderGeometry(id, scene,
  40555. /**
  40556. * Defines the height of the cylinder
  40557. */
  40558. height,
  40559. /**
  40560. * Defines the diameter of the cylinder's top cap
  40561. */
  40562. diameterTop,
  40563. /**
  40564. * Defines the diameter of the cylinder's bottom cap
  40565. */
  40566. diameterBottom,
  40567. /**
  40568. * Defines the tessellation factor to apply to the cylinder
  40569. */
  40570. tessellation,
  40571. /**
  40572. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40573. */
  40574. subdivisions, canBeRegenerated, mesh,
  40575. /**
  40576. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40577. */
  40578. side) {
  40579. if (subdivisions === void 0) { subdivisions = 1; }
  40580. if (mesh === void 0) { mesh = null; }
  40581. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40582. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40583. _this.height = height;
  40584. _this.diameterTop = diameterTop;
  40585. _this.diameterBottom = diameterBottom;
  40586. _this.tessellation = tessellation;
  40587. _this.subdivisions = subdivisions;
  40588. _this.side = side;
  40589. return _this;
  40590. }
  40591. /** @hidden */
  40592. CylinderGeometry.prototype._regenerateVertexData = function () {
  40593. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40594. };
  40595. CylinderGeometry.prototype.copy = function (id) {
  40596. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40597. };
  40598. CylinderGeometry.prototype.serialize = function () {
  40599. var serializationObject = _super.prototype.serialize.call(this);
  40600. serializationObject.height = this.height;
  40601. serializationObject.diameterTop = this.diameterTop;
  40602. serializationObject.diameterBottom = this.diameterBottom;
  40603. serializationObject.tessellation = this.tessellation;
  40604. return serializationObject;
  40605. };
  40606. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40607. if (scene.getGeometryByID(parsedCylinder.id)) {
  40608. return null; // null since geometry could be something else than a cylinder...
  40609. }
  40610. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40611. if (BABYLON.Tags) {
  40612. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40613. }
  40614. scene.pushGeometry(cylinder, true);
  40615. return cylinder;
  40616. };
  40617. return CylinderGeometry;
  40618. }(_PrimitiveGeometry));
  40619. BABYLON.CylinderGeometry = CylinderGeometry;
  40620. /**
  40621. * Creates a new torus geometry
  40622. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40623. */
  40624. var TorusGeometry = /** @class */ (function (_super) {
  40625. __extends(TorusGeometry, _super);
  40626. /**
  40627. * Creates a new torus geometry
  40628. * @param id defines the unique ID of the geometry
  40629. * @param scene defines the hosting scene
  40630. * @param diameter defines the diameter of the torus
  40631. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40632. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40633. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40634. * @param mesh defines the hosting mesh (can be null)
  40635. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40636. */
  40637. function TorusGeometry(id, scene,
  40638. /**
  40639. * Defines the diameter of the torus
  40640. */
  40641. diameter,
  40642. /**
  40643. * Defines the thickness of the torus (ie. internal diameter)
  40644. */
  40645. thickness,
  40646. /**
  40647. * Defines the tesselation factor to apply to the torus
  40648. */
  40649. tessellation, canBeRegenerated, mesh,
  40650. /**
  40651. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40652. */
  40653. side) {
  40654. if (mesh === void 0) { mesh = null; }
  40655. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40656. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40657. _this.diameter = diameter;
  40658. _this.thickness = thickness;
  40659. _this.tessellation = tessellation;
  40660. _this.side = side;
  40661. return _this;
  40662. }
  40663. /** @hidden */
  40664. TorusGeometry.prototype._regenerateVertexData = function () {
  40665. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40666. };
  40667. TorusGeometry.prototype.copy = function (id) {
  40668. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40669. };
  40670. TorusGeometry.prototype.serialize = function () {
  40671. var serializationObject = _super.prototype.serialize.call(this);
  40672. serializationObject.diameter = this.diameter;
  40673. serializationObject.thickness = this.thickness;
  40674. serializationObject.tessellation = this.tessellation;
  40675. return serializationObject;
  40676. };
  40677. TorusGeometry.Parse = function (parsedTorus, scene) {
  40678. if (scene.getGeometryByID(parsedTorus.id)) {
  40679. return null; // null since geometry could be something else than a torus...
  40680. }
  40681. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40682. if (BABYLON.Tags) {
  40683. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40684. }
  40685. scene.pushGeometry(torus, true);
  40686. return torus;
  40687. };
  40688. return TorusGeometry;
  40689. }(_PrimitiveGeometry));
  40690. BABYLON.TorusGeometry = TorusGeometry;
  40691. /**
  40692. * Creates a new ground geometry
  40693. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40694. */
  40695. var GroundGeometry = /** @class */ (function (_super) {
  40696. __extends(GroundGeometry, _super);
  40697. /**
  40698. * Creates a new ground geometry
  40699. * @param id defines the unique ID of the geometry
  40700. * @param scene defines the hosting scene
  40701. * @param width defines the width of the ground
  40702. * @param height defines the height of the ground
  40703. * @param subdivisions defines the subdivisions to apply to the ground
  40704. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40705. * @param mesh defines the hosting mesh (can be null)
  40706. */
  40707. function GroundGeometry(id, scene,
  40708. /**
  40709. * Defines the width of the ground
  40710. */
  40711. width,
  40712. /**
  40713. * Defines the height of the ground
  40714. */
  40715. height,
  40716. /**
  40717. * Defines the subdivisions to apply to the ground
  40718. */
  40719. subdivisions, canBeRegenerated, mesh) {
  40720. if (mesh === void 0) { mesh = null; }
  40721. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40722. _this.width = width;
  40723. _this.height = height;
  40724. _this.subdivisions = subdivisions;
  40725. return _this;
  40726. }
  40727. /** @hidden */
  40728. GroundGeometry.prototype._regenerateVertexData = function () {
  40729. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40730. };
  40731. GroundGeometry.prototype.copy = function (id) {
  40732. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40733. };
  40734. GroundGeometry.prototype.serialize = function () {
  40735. var serializationObject = _super.prototype.serialize.call(this);
  40736. serializationObject.width = this.width;
  40737. serializationObject.height = this.height;
  40738. serializationObject.subdivisions = this.subdivisions;
  40739. return serializationObject;
  40740. };
  40741. GroundGeometry.Parse = function (parsedGround, scene) {
  40742. if (scene.getGeometryByID(parsedGround.id)) {
  40743. return null; // null since geometry could be something else than a ground...
  40744. }
  40745. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40746. if (BABYLON.Tags) {
  40747. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40748. }
  40749. scene.pushGeometry(ground, true);
  40750. return ground;
  40751. };
  40752. return GroundGeometry;
  40753. }(_PrimitiveGeometry));
  40754. BABYLON.GroundGeometry = GroundGeometry;
  40755. /**
  40756. * Creates a tiled ground geometry
  40757. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40758. */
  40759. var TiledGroundGeometry = /** @class */ (function (_super) {
  40760. __extends(TiledGroundGeometry, _super);
  40761. /**
  40762. * Creates a tiled ground geometry
  40763. * @param id defines the unique ID of the geometry
  40764. * @param scene defines the hosting scene
  40765. * @param xmin defines the minimum value on X axis
  40766. * @param zmin defines the minimum value on Z axis
  40767. * @param xmax defines the maximum value on X axis
  40768. * @param zmax defines the maximum value on Z axis
  40769. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40770. * @param precision defines the precision to use when computing the tiles
  40771. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40772. * @param mesh defines the hosting mesh (can be null)
  40773. */
  40774. function TiledGroundGeometry(id, scene,
  40775. /**
  40776. * Defines the minimum value on X axis
  40777. */
  40778. xmin,
  40779. /**
  40780. * Defines the minimum value on Z axis
  40781. */
  40782. zmin,
  40783. /**
  40784. * Defines the maximum value on X axis
  40785. */
  40786. xmax,
  40787. /**
  40788. * Defines the maximum value on Z axis
  40789. */
  40790. zmax,
  40791. /**
  40792. * Defines the subdivisions to apply to the ground
  40793. */
  40794. subdivisions,
  40795. /**
  40796. * Defines the precision to use when computing the tiles
  40797. */
  40798. precision, canBeRegenerated, mesh) {
  40799. if (mesh === void 0) { mesh = null; }
  40800. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40801. _this.xmin = xmin;
  40802. _this.zmin = zmin;
  40803. _this.xmax = xmax;
  40804. _this.zmax = zmax;
  40805. _this.subdivisions = subdivisions;
  40806. _this.precision = precision;
  40807. return _this;
  40808. }
  40809. /** @hidden */
  40810. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40811. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40812. };
  40813. TiledGroundGeometry.prototype.copy = function (id) {
  40814. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40815. };
  40816. return TiledGroundGeometry;
  40817. }(_PrimitiveGeometry));
  40818. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40819. /**
  40820. * Creates a plane geometry
  40821. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40822. */
  40823. var PlaneGeometry = /** @class */ (function (_super) {
  40824. __extends(PlaneGeometry, _super);
  40825. /**
  40826. * Creates a plane geometry
  40827. * @param id defines the unique ID of the geometry
  40828. * @param scene defines the hosting scene
  40829. * @param size defines the size of the plane (width === height)
  40830. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40831. * @param mesh defines the hosting mesh (can be null)
  40832. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40833. */
  40834. function PlaneGeometry(id, scene,
  40835. /**
  40836. * Defines the size of the plane (width === height)
  40837. */
  40838. size, canBeRegenerated, mesh,
  40839. /**
  40840. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40841. */
  40842. side) {
  40843. if (mesh === void 0) { mesh = null; }
  40844. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40845. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40846. _this.size = size;
  40847. _this.side = side;
  40848. return _this;
  40849. }
  40850. /** @hidden */
  40851. PlaneGeometry.prototype._regenerateVertexData = function () {
  40852. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40853. };
  40854. PlaneGeometry.prototype.copy = function (id) {
  40855. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40856. };
  40857. PlaneGeometry.prototype.serialize = function () {
  40858. var serializationObject = _super.prototype.serialize.call(this);
  40859. serializationObject.size = this.size;
  40860. return serializationObject;
  40861. };
  40862. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40863. if (scene.getGeometryByID(parsedPlane.id)) {
  40864. return null; // null since geometry could be something else than a ground...
  40865. }
  40866. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40867. if (BABYLON.Tags) {
  40868. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40869. }
  40870. scene.pushGeometry(plane, true);
  40871. return plane;
  40872. };
  40873. return PlaneGeometry;
  40874. }(_PrimitiveGeometry));
  40875. BABYLON.PlaneGeometry = PlaneGeometry;
  40876. /**
  40877. * Creates a torus knot geometry
  40878. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40879. */
  40880. var TorusKnotGeometry = /** @class */ (function (_super) {
  40881. __extends(TorusKnotGeometry, _super);
  40882. /**
  40883. * Creates a torus knot geometry
  40884. * @param id defines the unique ID of the geometry
  40885. * @param scene defines the hosting scene
  40886. * @param radius defines the radius of the torus knot
  40887. * @param tube defines the thickness of the torus knot tube
  40888. * @param radialSegments defines the number of radial segments
  40889. * @param tubularSegments defines the number of tubular segments
  40890. * @param p defines the first number of windings
  40891. * @param q defines the second number of windings
  40892. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40893. * @param mesh defines the hosting mesh (can be null)
  40894. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40895. */
  40896. function TorusKnotGeometry(id, scene,
  40897. /**
  40898. * Defines the radius of the torus knot
  40899. */
  40900. radius,
  40901. /**
  40902. * Defines the thickness of the torus knot tube
  40903. */
  40904. tube,
  40905. /**
  40906. * Defines the number of radial segments
  40907. */
  40908. radialSegments,
  40909. /**
  40910. * Defines the number of tubular segments
  40911. */
  40912. tubularSegments,
  40913. /**
  40914. * Defines the first number of windings
  40915. */
  40916. p,
  40917. /**
  40918. * Defines the second number of windings
  40919. */
  40920. q, canBeRegenerated, mesh,
  40921. /**
  40922. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40923. */
  40924. side) {
  40925. if (mesh === void 0) { mesh = null; }
  40926. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40927. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40928. _this.radius = radius;
  40929. _this.tube = tube;
  40930. _this.radialSegments = radialSegments;
  40931. _this.tubularSegments = tubularSegments;
  40932. _this.p = p;
  40933. _this.q = q;
  40934. _this.side = side;
  40935. return _this;
  40936. }
  40937. /** @hidden */
  40938. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40939. 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 });
  40940. };
  40941. TorusKnotGeometry.prototype.copy = function (id) {
  40942. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40943. };
  40944. TorusKnotGeometry.prototype.serialize = function () {
  40945. var serializationObject = _super.prototype.serialize.call(this);
  40946. serializationObject.radius = this.radius;
  40947. serializationObject.tube = this.tube;
  40948. serializationObject.radialSegments = this.radialSegments;
  40949. serializationObject.tubularSegments = this.tubularSegments;
  40950. serializationObject.p = this.p;
  40951. serializationObject.q = this.q;
  40952. return serializationObject;
  40953. };
  40954. ;
  40955. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40956. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40957. return null; // null since geometry could be something else than a ground...
  40958. }
  40959. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40960. if (BABYLON.Tags) {
  40961. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40962. }
  40963. scene.pushGeometry(torusKnot, true);
  40964. return torusKnot;
  40965. };
  40966. return TorusKnotGeometry;
  40967. }(_PrimitiveGeometry));
  40968. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40969. //}
  40970. })(BABYLON || (BABYLON = {}));
  40971. //# sourceMappingURL=babylon.geometry.js.map
  40972. var BABYLON;
  40973. (function (BABYLON) {
  40974. /**
  40975. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40976. */
  40977. var PerformanceMonitor = /** @class */ (function () {
  40978. /**
  40979. * constructor
  40980. * @param frameSampleSize The number of samples required to saturate the sliding window
  40981. */
  40982. function PerformanceMonitor(frameSampleSize) {
  40983. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40984. this._enabled = true;
  40985. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40986. }
  40987. /**
  40988. * Samples current frame
  40989. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40990. */
  40991. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40992. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40993. if (!this._enabled)
  40994. return;
  40995. if (this._lastFrameTimeMs != null) {
  40996. var dt = timeMs - this._lastFrameTimeMs;
  40997. this._rollingFrameTime.add(dt);
  40998. }
  40999. this._lastFrameTimeMs = timeMs;
  41000. };
  41001. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41002. /**
  41003. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41004. */
  41005. get: function () {
  41006. return this._rollingFrameTime.average;
  41007. },
  41008. enumerable: true,
  41009. configurable: true
  41010. });
  41011. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41012. /**
  41013. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41014. */
  41015. get: function () {
  41016. return this._rollingFrameTime.variance;
  41017. },
  41018. enumerable: true,
  41019. configurable: true
  41020. });
  41021. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41022. /**
  41023. * Returns the frame time of the most recent frame
  41024. */
  41025. get: function () {
  41026. return this._rollingFrameTime.history(0);
  41027. },
  41028. enumerable: true,
  41029. configurable: true
  41030. });
  41031. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41032. /**
  41033. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41034. */
  41035. get: function () {
  41036. return 1000.0 / this._rollingFrameTime.average;
  41037. },
  41038. enumerable: true,
  41039. configurable: true
  41040. });
  41041. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41042. /**
  41043. * Returns the average framerate in frames per second using the most recent frame time
  41044. */
  41045. get: function () {
  41046. var history = this._rollingFrameTime.history(0);
  41047. if (history === 0) {
  41048. return 0;
  41049. }
  41050. return 1000.0 / history;
  41051. },
  41052. enumerable: true,
  41053. configurable: true
  41054. });
  41055. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41056. /**
  41057. * Returns true if enough samples have been taken to completely fill the sliding window
  41058. */
  41059. get: function () {
  41060. return this._rollingFrameTime.isSaturated();
  41061. },
  41062. enumerable: true,
  41063. configurable: true
  41064. });
  41065. /**
  41066. * Enables contributions to the sliding window sample set
  41067. */
  41068. PerformanceMonitor.prototype.enable = function () {
  41069. this._enabled = true;
  41070. };
  41071. /**
  41072. * Disables contributions to the sliding window sample set
  41073. * Samples will not be interpolated over the disabled period
  41074. */
  41075. PerformanceMonitor.prototype.disable = function () {
  41076. this._enabled = false;
  41077. //clear last sample to avoid interpolating over the disabled period when next enabled
  41078. this._lastFrameTimeMs = null;
  41079. };
  41080. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41081. /**
  41082. * Returns true if sampling is enabled
  41083. */
  41084. get: function () {
  41085. return this._enabled;
  41086. },
  41087. enumerable: true,
  41088. configurable: true
  41089. });
  41090. /**
  41091. * Resets performance monitor
  41092. */
  41093. PerformanceMonitor.prototype.reset = function () {
  41094. //clear last sample to avoid interpolating over the disabled period when next enabled
  41095. this._lastFrameTimeMs = null;
  41096. //wipe record
  41097. this._rollingFrameTime.reset();
  41098. };
  41099. return PerformanceMonitor;
  41100. }());
  41101. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41102. /**
  41103. * RollingAverage
  41104. *
  41105. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41106. */
  41107. var RollingAverage = /** @class */ (function () {
  41108. /**
  41109. * constructor
  41110. * @param length The number of samples required to saturate the sliding window
  41111. */
  41112. function RollingAverage(length) {
  41113. this._samples = new Array(length);
  41114. this.reset();
  41115. }
  41116. /**
  41117. * Adds a sample to the sample set
  41118. * @param v The sample value
  41119. */
  41120. RollingAverage.prototype.add = function (v) {
  41121. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41122. var delta;
  41123. //we need to check if we've already wrapped round
  41124. if (this.isSaturated()) {
  41125. //remove bottom of stack from mean
  41126. var bottomValue = this._samples[this._pos];
  41127. delta = bottomValue - this.average;
  41128. this.average -= delta / (this._sampleCount - 1);
  41129. this._m2 -= delta * (bottomValue - this.average);
  41130. }
  41131. else {
  41132. this._sampleCount++;
  41133. }
  41134. //add new value to mean
  41135. delta = v - this.average;
  41136. this.average += delta / (this._sampleCount);
  41137. this._m2 += delta * (v - this.average);
  41138. //set the new variance
  41139. this.variance = this._m2 / (this._sampleCount - 1);
  41140. this._samples[this._pos] = v;
  41141. this._pos++;
  41142. this._pos %= this._samples.length; //positive wrap around
  41143. };
  41144. /**
  41145. * Returns previously added values or null if outside of history or outside the sliding window domain
  41146. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41147. * @return Value previously recorded with add() or null if outside of range
  41148. */
  41149. RollingAverage.prototype.history = function (i) {
  41150. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41151. return 0;
  41152. }
  41153. var i0 = this._wrapPosition(this._pos - 1.0);
  41154. return this._samples[this._wrapPosition(i0 - i)];
  41155. };
  41156. /**
  41157. * Returns true if enough samples have been taken to completely fill the sliding window
  41158. * @return true if sample-set saturated
  41159. */
  41160. RollingAverage.prototype.isSaturated = function () {
  41161. return this._sampleCount >= this._samples.length;
  41162. };
  41163. /**
  41164. * Resets the rolling average (equivalent to 0 samples taken so far)
  41165. */
  41166. RollingAverage.prototype.reset = function () {
  41167. this.average = 0;
  41168. this.variance = 0;
  41169. this._sampleCount = 0;
  41170. this._pos = 0;
  41171. this._m2 = 0;
  41172. };
  41173. /**
  41174. * Wraps a value around the sample range boundaries
  41175. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41176. * @return Wrapped position in sample range
  41177. */
  41178. RollingAverage.prototype._wrapPosition = function (i) {
  41179. var max = this._samples.length;
  41180. return ((i % max) + max) % max;
  41181. };
  41182. return RollingAverage;
  41183. }());
  41184. BABYLON.RollingAverage = RollingAverage;
  41185. })(BABYLON || (BABYLON = {}));
  41186. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41187. var BABYLON;
  41188. (function (BABYLON) {
  41189. /**
  41190. * "Static Class" containing the most commonly used helper while dealing with material for
  41191. * rendering purpose.
  41192. *
  41193. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41194. *
  41195. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41196. */
  41197. var MaterialHelper = /** @class */ (function () {
  41198. function MaterialHelper() {
  41199. }
  41200. /**
  41201. * Bind the current view position to an effect.
  41202. * @param effect The effect to be bound
  41203. * @param scene The scene the eyes position is used from
  41204. */
  41205. MaterialHelper.BindEyePosition = function (effect, scene) {
  41206. if (scene._forcedViewPosition) {
  41207. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41208. return;
  41209. }
  41210. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41211. };
  41212. /**
  41213. * Helps preparing the defines values about the UVs in used in the effect.
  41214. * UVs are shared as much as we can accross chanels in the shaders.
  41215. * @param texture The texture we are preparing the UVs for
  41216. * @param defines The defines to update
  41217. * @param key The chanel key "diffuse", "specular"... used in the shader
  41218. */
  41219. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41220. defines._needUVs = true;
  41221. defines[key] = true;
  41222. if (texture.getTextureMatrix().isIdentity(true)) {
  41223. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41224. if (texture.coordinatesIndex === 0) {
  41225. defines["MAINUV1"] = true;
  41226. }
  41227. else {
  41228. defines["MAINUV2"] = true;
  41229. }
  41230. }
  41231. else {
  41232. defines[key + "DIRECTUV"] = 0;
  41233. }
  41234. };
  41235. /**
  41236. * Binds a texture matrix value to its corrsponding uniform
  41237. * @param texture The texture to bind the matrix for
  41238. * @param uniformBuffer The uniform buffer receivin the data
  41239. * @param key The chanel key "diffuse", "specular"... used in the shader
  41240. */
  41241. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41242. var matrix = texture.getTextureMatrix();
  41243. if (!matrix.isIdentity(true)) {
  41244. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41245. }
  41246. };
  41247. /**
  41248. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41249. * @param mesh defines the current mesh
  41250. * @param scene defines the current scene
  41251. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41252. * @param pointsCloud defines if point cloud rendering has to be turned on
  41253. * @param fogEnabled defines if fog has to be turned on
  41254. * @param alphaTest defines if alpha testing has to be turned on
  41255. * @param defines defines the current list of defines
  41256. */
  41257. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41258. if (defines._areMiscDirty) {
  41259. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41260. defines["POINTSIZE"] = pointsCloud;
  41261. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41262. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41263. defines["ALPHATEST"] = alphaTest;
  41264. }
  41265. };
  41266. /**
  41267. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41268. * @param scene defines the current scene
  41269. * @param engine defines the current engine
  41270. * @param defines specifies the list of active defines
  41271. * @param useInstances defines if instances have to be turned on
  41272. * @param useClipPlane defines if clip plane have to be turned on
  41273. */
  41274. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41275. if (useClipPlane === void 0) { useClipPlane = null; }
  41276. var changed = false;
  41277. var useClipPlane1 = false;
  41278. var useClipPlane2 = false;
  41279. var useClipPlane3 = false;
  41280. var useClipPlane4 = false;
  41281. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  41282. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  41283. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  41284. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  41285. if (defines["CLIPPLANE"] !== useClipPlane1) {
  41286. defines["CLIPPLANE"] = useClipPlane1;
  41287. changed = true;
  41288. }
  41289. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  41290. defines["CLIPPLANE2"] = useClipPlane2;
  41291. changed = true;
  41292. }
  41293. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  41294. defines["CLIPPLANE3"] = useClipPlane3;
  41295. changed = true;
  41296. }
  41297. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  41298. defines["CLIPPLANE4"] = useClipPlane4;
  41299. changed = true;
  41300. }
  41301. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41302. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41303. changed = true;
  41304. }
  41305. if (defines["INSTANCES"] !== useInstances) {
  41306. defines["INSTANCES"] = useInstances;
  41307. changed = true;
  41308. }
  41309. if (changed) {
  41310. defines.markAsUnprocessed();
  41311. }
  41312. };
  41313. /**
  41314. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41315. * @param mesh The mesh containing the geometry data we will draw
  41316. * @param defines The defines to update
  41317. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41318. * @param useBones Precise whether bones should be used or not (override mesh info)
  41319. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41320. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41321. * @returns false if defines are considered not dirty and have not been checked
  41322. */
  41323. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41324. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41325. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41326. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41327. return false;
  41328. }
  41329. defines._normals = defines._needNormals;
  41330. defines._uvs = defines._needUVs;
  41331. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41332. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41333. defines["TANGENT"] = true;
  41334. }
  41335. if (defines._needUVs) {
  41336. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41337. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41338. }
  41339. else {
  41340. defines["UV1"] = false;
  41341. defines["UV2"] = false;
  41342. }
  41343. if (useVertexColor) {
  41344. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41345. defines["VERTEXCOLOR"] = hasVertexColors;
  41346. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41347. }
  41348. if (useBones) {
  41349. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41350. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41351. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41352. }
  41353. else {
  41354. defines["NUM_BONE_INFLUENCERS"] = 0;
  41355. defines["BonesPerMesh"] = 0;
  41356. }
  41357. }
  41358. if (useMorphTargets) {
  41359. var manager = mesh.morphTargetManager;
  41360. if (manager) {
  41361. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41362. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41363. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41364. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41365. }
  41366. else {
  41367. defines["MORPHTARGETS_TANGENT"] = false;
  41368. defines["MORPHTARGETS_NORMAL"] = false;
  41369. defines["MORPHTARGETS"] = false;
  41370. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41371. }
  41372. }
  41373. return true;
  41374. };
  41375. /**
  41376. * Prepares the defines related to the light information passed in parameter
  41377. * @param scene The scene we are intending to draw
  41378. * @param mesh The mesh the effect is compiling for
  41379. * @param defines The defines to update
  41380. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41381. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41382. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41383. * @returns true if normals will be required for the rest of the effect
  41384. */
  41385. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41386. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41387. if (disableLighting === void 0) { disableLighting = false; }
  41388. if (!defines._areLightsDirty) {
  41389. return defines._needNormals;
  41390. }
  41391. var lightIndex = 0;
  41392. var needNormals = false;
  41393. var needRebuild = false;
  41394. var lightmapMode = false;
  41395. var shadowEnabled = false;
  41396. var specularEnabled = false;
  41397. if (scene.lightsEnabled && !disableLighting) {
  41398. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41399. var light = _a[_i];
  41400. needNormals = true;
  41401. if (defines["LIGHT" + lightIndex] === undefined) {
  41402. needRebuild = true;
  41403. }
  41404. defines["LIGHT" + lightIndex] = true;
  41405. defines["SPOTLIGHT" + lightIndex] = false;
  41406. defines["HEMILIGHT" + lightIndex] = false;
  41407. defines["POINTLIGHT" + lightIndex] = false;
  41408. defines["DIRLIGHT" + lightIndex] = false;
  41409. light.prepareLightSpecificDefines(defines, lightIndex);
  41410. // FallOff.
  41411. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  41412. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  41413. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  41414. switch (light.falloffType) {
  41415. case BABYLON.Light.FALLOFF_GLTF:
  41416. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  41417. break;
  41418. case BABYLON.Light.FALLOFF_PHYSICAL:
  41419. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  41420. break;
  41421. case BABYLON.Light.FALLOFF_STANDARD:
  41422. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  41423. break;
  41424. }
  41425. // Specular
  41426. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41427. specularEnabled = true;
  41428. }
  41429. // Shadows
  41430. defines["SHADOW" + lightIndex] = false;
  41431. defines["SHADOWPCF" + lightIndex] = false;
  41432. defines["SHADOWPCSS" + lightIndex] = false;
  41433. defines["SHADOWPOISSON" + lightIndex] = false;
  41434. defines["SHADOWESM" + lightIndex] = false;
  41435. defines["SHADOWCUBE" + lightIndex] = false;
  41436. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41437. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41438. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41439. var shadowGenerator = light.getShadowGenerator();
  41440. if (shadowGenerator) {
  41441. var shadowMap = shadowGenerator.getShadowMap();
  41442. if (shadowMap) {
  41443. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41444. shadowEnabled = true;
  41445. shadowGenerator.prepareDefines(defines, lightIndex);
  41446. }
  41447. }
  41448. }
  41449. }
  41450. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41451. lightmapMode = true;
  41452. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41453. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41454. }
  41455. else {
  41456. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41457. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41458. }
  41459. lightIndex++;
  41460. if (lightIndex === maxSimultaneousLights)
  41461. break;
  41462. }
  41463. }
  41464. defines["SPECULARTERM"] = specularEnabled;
  41465. defines["SHADOWS"] = shadowEnabled;
  41466. // Resetting all other lights if any
  41467. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41468. if (defines["LIGHT" + index] !== undefined) {
  41469. defines["LIGHT" + index] = false;
  41470. defines["HEMILIGHT" + lightIndex] = false;
  41471. defines["POINTLIGHT" + lightIndex] = false;
  41472. defines["DIRLIGHT" + lightIndex] = false;
  41473. defines["SPOTLIGHT" + lightIndex] = false;
  41474. defines["SHADOW" + lightIndex] = false;
  41475. }
  41476. }
  41477. var caps = scene.getEngine().getCaps();
  41478. if (defines["SHADOWFLOAT"] === undefined) {
  41479. needRebuild = true;
  41480. }
  41481. defines["SHADOWFLOAT"] = shadowEnabled &&
  41482. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41483. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41484. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41485. if (needRebuild) {
  41486. defines.rebuild();
  41487. }
  41488. return needNormals;
  41489. };
  41490. /**
  41491. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41492. * that won t be acctive due to defines being turned off.
  41493. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41494. * @param samplersList The samplers list
  41495. * @param defines The defines helping in the list generation
  41496. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41497. */
  41498. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41499. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41500. var uniformsList;
  41501. var uniformBuffersList = null;
  41502. if (uniformsListOrOptions.uniformsNames) {
  41503. var options = uniformsListOrOptions;
  41504. uniformsList = options.uniformsNames;
  41505. uniformBuffersList = options.uniformBuffersNames;
  41506. samplersList = options.samplers;
  41507. defines = options.defines;
  41508. maxSimultaneousLights = options.maxSimultaneousLights;
  41509. }
  41510. else {
  41511. uniformsList = uniformsListOrOptions;
  41512. if (!samplersList) {
  41513. samplersList = [];
  41514. }
  41515. }
  41516. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41517. if (!defines["LIGHT" + lightIndex]) {
  41518. break;
  41519. }
  41520. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41521. if (uniformBuffersList) {
  41522. uniformBuffersList.push("Light" + lightIndex);
  41523. }
  41524. samplersList.push("shadowSampler" + lightIndex);
  41525. samplersList.push("depthSampler" + lightIndex);
  41526. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41527. samplersList.push("projectionLightSampler" + lightIndex);
  41528. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41529. }
  41530. }
  41531. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41532. uniformsList.push("morphTargetInfluences");
  41533. }
  41534. };
  41535. /**
  41536. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41537. * @param defines The defines to update while falling back
  41538. * @param fallbacks The authorized effect fallbacks
  41539. * @param maxSimultaneousLights The maximum number of lights allowed
  41540. * @param rank the current rank of the Effect
  41541. * @returns The newly affected rank
  41542. */
  41543. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41544. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41545. if (rank === void 0) { rank = 0; }
  41546. var lightFallbackRank = 0;
  41547. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41548. if (!defines["LIGHT" + lightIndex]) {
  41549. break;
  41550. }
  41551. if (lightIndex > 0) {
  41552. lightFallbackRank = rank + lightIndex;
  41553. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41554. }
  41555. if (!defines["SHADOWS"]) {
  41556. if (defines["SHADOW" + lightIndex]) {
  41557. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41558. }
  41559. if (defines["SHADOWPCF" + lightIndex]) {
  41560. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41561. }
  41562. if (defines["SHADOWPCSS" + lightIndex]) {
  41563. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41564. }
  41565. if (defines["SHADOWPOISSON" + lightIndex]) {
  41566. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41567. }
  41568. if (defines["SHADOWESM" + lightIndex]) {
  41569. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41570. }
  41571. }
  41572. }
  41573. return lightFallbackRank++;
  41574. };
  41575. /**
  41576. * Prepares the list of attributes required for morph targets according to the effect defines.
  41577. * @param attribs The current list of supported attribs
  41578. * @param mesh The mesh to prepare the morph targets attributes for
  41579. * @param defines The current Defines of the effect
  41580. */
  41581. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41582. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41583. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41584. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41585. var manager = mesh.morphTargetManager;
  41586. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41587. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41588. for (var index = 0; index < influencers; index++) {
  41589. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41590. if (normal) {
  41591. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41592. }
  41593. if (tangent) {
  41594. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41595. }
  41596. if (attribs.length > maxAttributesCount) {
  41597. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41598. }
  41599. }
  41600. }
  41601. };
  41602. /**
  41603. * Prepares the list of attributes required for bones according to the effect defines.
  41604. * @param attribs The current list of supported attribs
  41605. * @param mesh The mesh to prepare the bones attributes for
  41606. * @param defines The current Defines of the effect
  41607. * @param fallbacks The current efffect fallback strategy
  41608. */
  41609. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41610. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41611. fallbacks.addCPUSkinningFallback(0, mesh);
  41612. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41613. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41614. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41615. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41616. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41617. }
  41618. }
  41619. };
  41620. /**
  41621. * Prepares the list of attributes required for instances according to the effect defines.
  41622. * @param attribs The current list of supported attribs
  41623. * @param defines The current Defines of the effect
  41624. */
  41625. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41626. if (defines["INSTANCES"]) {
  41627. attribs.push("world0");
  41628. attribs.push("world1");
  41629. attribs.push("world2");
  41630. attribs.push("world3");
  41631. }
  41632. };
  41633. /**
  41634. * Binds the light shadow information to the effect for the given mesh.
  41635. * @param light The light containing the generator
  41636. * @param scene The scene the lights belongs to
  41637. * @param mesh The mesh we are binding the information to render
  41638. * @param lightIndex The light index in the effect used to render the mesh
  41639. * @param effect The effect we are binding the data to
  41640. */
  41641. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41642. if (light.shadowEnabled && mesh.receiveShadows) {
  41643. var shadowGenerator = light.getShadowGenerator();
  41644. if (shadowGenerator) {
  41645. shadowGenerator.bindShadowLight(lightIndex, effect);
  41646. }
  41647. }
  41648. };
  41649. /**
  41650. * Binds the light information to the effect.
  41651. * @param light The light containing the generator
  41652. * @param effect The effect we are binding the data to
  41653. * @param lightIndex The light index in the effect used to render
  41654. */
  41655. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41656. light.transferToEffect(effect, lightIndex + "");
  41657. };
  41658. /**
  41659. * Binds the lights information from the scene to the effect for the given mesh.
  41660. * @param scene The scene the lights belongs to
  41661. * @param mesh The mesh we are binding the information to render
  41662. * @param effect The effect we are binding the data to
  41663. * @param defines The generated defines for the effect
  41664. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41665. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41666. */
  41667. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41668. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41669. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41670. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41671. for (var i = 0; i < len; i++) {
  41672. var light = mesh._lightSources[i];
  41673. var iAsString = i.toString();
  41674. var scaledIntensity = light.getScaledIntensity();
  41675. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41676. MaterialHelper.BindLightProperties(light, effect, i);
  41677. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41678. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41679. if (defines["SPECULARTERM"]) {
  41680. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41681. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41682. }
  41683. // Shadows
  41684. if (scene.shadowsEnabled) {
  41685. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41686. }
  41687. light._uniformBuffer.update();
  41688. }
  41689. };
  41690. /**
  41691. * Binds the fog information from the scene to the effect for the given mesh.
  41692. * @param scene The scene the lights belongs to
  41693. * @param mesh The mesh we are binding the information to render
  41694. * @param effect The effect we are binding the data to
  41695. * @param linearSpace Defines if the fog effect is applied in linear space
  41696. */
  41697. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  41698. if (linearSpace === void 0) { linearSpace = false; }
  41699. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41700. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41701. // Convert fog color to linear space if used in a linear space computed shader.
  41702. if (linearSpace) {
  41703. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  41704. effect.setColor3("vFogColor", this._tempFogColor);
  41705. }
  41706. else {
  41707. effect.setColor3("vFogColor", scene.fogColor);
  41708. }
  41709. }
  41710. };
  41711. /**
  41712. * Binds the bones information from the mesh to the effect.
  41713. * @param mesh The mesh we are binding the information to render
  41714. * @param effect The effect we are binding the data to
  41715. */
  41716. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41717. if (!effect || !mesh) {
  41718. return;
  41719. }
  41720. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41721. mesh.computeBonesUsingShaders = false;
  41722. }
  41723. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41724. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41725. if (matrices) {
  41726. effect.setMatrices("mBones", matrices);
  41727. }
  41728. }
  41729. };
  41730. /**
  41731. * Binds the morph targets information from the mesh to the effect.
  41732. * @param abstractMesh The mesh we are binding the information to render
  41733. * @param effect The effect we are binding the data to
  41734. */
  41735. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41736. var manager = abstractMesh.morphTargetManager;
  41737. if (!abstractMesh || !manager) {
  41738. return;
  41739. }
  41740. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41741. };
  41742. /**
  41743. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41744. * @param defines The generated defines used in the effect
  41745. * @param effect The effect we are binding the data to
  41746. * @param scene The scene we are willing to render with logarithmic scale for
  41747. */
  41748. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41749. if (defines["LOGARITHMICDEPTH"]) {
  41750. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41751. }
  41752. };
  41753. /**
  41754. * Binds the clip plane information from the scene to the effect.
  41755. * @param scene The scene the clip plane information are extracted from
  41756. * @param effect The effect we are binding the data to
  41757. */
  41758. MaterialHelper.BindClipPlane = function (effect, scene) {
  41759. if (scene.clipPlane) {
  41760. var clipPlane = scene.clipPlane;
  41761. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41762. }
  41763. if (scene.clipPlane2) {
  41764. var clipPlane = scene.clipPlane2;
  41765. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41766. }
  41767. if (scene.clipPlane3) {
  41768. var clipPlane = scene.clipPlane3;
  41769. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41770. }
  41771. if (scene.clipPlane4) {
  41772. var clipPlane = scene.clipPlane4;
  41773. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41774. }
  41775. };
  41776. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  41777. return MaterialHelper;
  41778. }());
  41779. BABYLON.MaterialHelper = MaterialHelper;
  41780. })(BABYLON || (BABYLON = {}));
  41781. //# sourceMappingURL=babylon.materialHelper.js.map
  41782. var BABYLON;
  41783. (function (BABYLON) {
  41784. var PushMaterial = /** @class */ (function (_super) {
  41785. __extends(PushMaterial, _super);
  41786. function PushMaterial(name, scene) {
  41787. var _this = _super.call(this, name, scene) || this;
  41788. _this._normalMatrix = new BABYLON.Matrix();
  41789. _this.storeEffectOnSubMeshes = true;
  41790. return _this;
  41791. }
  41792. PushMaterial.prototype.getEffect = function () {
  41793. return this._activeEffect;
  41794. };
  41795. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41796. if (!mesh) {
  41797. return false;
  41798. }
  41799. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41800. return true;
  41801. }
  41802. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41803. };
  41804. /**
  41805. * Binds the given world matrix to the active effect
  41806. *
  41807. * @param world the matrix to bind
  41808. */
  41809. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41810. this._activeEffect.setMatrix("world", world);
  41811. };
  41812. /**
  41813. * Binds the given normal matrix to the active effect
  41814. *
  41815. * @param normalMatrix the matrix to bind
  41816. */
  41817. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41818. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41819. };
  41820. PushMaterial.prototype.bind = function (world, mesh) {
  41821. if (!mesh) {
  41822. return;
  41823. }
  41824. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41825. };
  41826. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41827. if (effect === void 0) { effect = null; }
  41828. _super.prototype._afterBind.call(this, mesh);
  41829. this.getScene()._cachedEffect = effect;
  41830. };
  41831. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41832. if (visibility === void 0) { visibility = 1; }
  41833. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41834. };
  41835. return PushMaterial;
  41836. }(BABYLON.Material));
  41837. BABYLON.PushMaterial = PushMaterial;
  41838. })(BABYLON || (BABYLON = {}));
  41839. //# sourceMappingURL=babylon.pushMaterial.js.map
  41840. var BABYLON;
  41841. (function (BABYLON) {
  41842. /** @hidden */
  41843. var StandardMaterialDefines = /** @class */ (function (_super) {
  41844. __extends(StandardMaterialDefines, _super);
  41845. function StandardMaterialDefines() {
  41846. var _this = _super.call(this) || this;
  41847. _this.MAINUV1 = false;
  41848. _this.MAINUV2 = false;
  41849. _this.DIFFUSE = false;
  41850. _this.DIFFUSEDIRECTUV = 0;
  41851. _this.AMBIENT = false;
  41852. _this.AMBIENTDIRECTUV = 0;
  41853. _this.OPACITY = false;
  41854. _this.OPACITYDIRECTUV = 0;
  41855. _this.OPACITYRGB = false;
  41856. _this.REFLECTION = false;
  41857. _this.EMISSIVE = false;
  41858. _this.EMISSIVEDIRECTUV = 0;
  41859. _this.SPECULAR = false;
  41860. _this.SPECULARDIRECTUV = 0;
  41861. _this.BUMP = false;
  41862. _this.BUMPDIRECTUV = 0;
  41863. _this.PARALLAX = false;
  41864. _this.PARALLAXOCCLUSION = false;
  41865. _this.SPECULAROVERALPHA = false;
  41866. _this.CLIPPLANE = false;
  41867. _this.CLIPPLANE2 = false;
  41868. _this.CLIPPLANE3 = false;
  41869. _this.CLIPPLANE4 = false;
  41870. _this.ALPHATEST = false;
  41871. _this.DEPTHPREPASS = false;
  41872. _this.ALPHAFROMDIFFUSE = false;
  41873. _this.POINTSIZE = false;
  41874. _this.FOG = false;
  41875. _this.SPECULARTERM = false;
  41876. _this.DIFFUSEFRESNEL = false;
  41877. _this.OPACITYFRESNEL = false;
  41878. _this.REFLECTIONFRESNEL = false;
  41879. _this.REFRACTIONFRESNEL = false;
  41880. _this.EMISSIVEFRESNEL = false;
  41881. _this.FRESNEL = false;
  41882. _this.NORMAL = false;
  41883. _this.UV1 = false;
  41884. _this.UV2 = false;
  41885. _this.VERTEXCOLOR = false;
  41886. _this.VERTEXALPHA = false;
  41887. _this.NUM_BONE_INFLUENCERS = 0;
  41888. _this.BonesPerMesh = 0;
  41889. _this.INSTANCES = false;
  41890. _this.GLOSSINESS = false;
  41891. _this.ROUGHNESS = false;
  41892. _this.EMISSIVEASILLUMINATION = false;
  41893. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41894. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41895. _this.LIGHTMAP = false;
  41896. _this.LIGHTMAPDIRECTUV = 0;
  41897. _this.OBJECTSPACE_NORMALMAP = false;
  41898. _this.USELIGHTMAPASSHADOWMAP = false;
  41899. _this.REFLECTIONMAP_3D = false;
  41900. _this.REFLECTIONMAP_SPHERICAL = false;
  41901. _this.REFLECTIONMAP_PLANAR = false;
  41902. _this.REFLECTIONMAP_CUBIC = false;
  41903. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41904. _this.REFLECTIONMAP_PROJECTION = false;
  41905. _this.REFLECTIONMAP_SKYBOX = false;
  41906. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41907. _this.REFLECTIONMAP_EXPLICIT = false;
  41908. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41909. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41910. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41911. _this.INVERTCUBICMAP = false;
  41912. _this.LOGARITHMICDEPTH = false;
  41913. _this.REFRACTION = false;
  41914. _this.REFRACTIONMAP_3D = false;
  41915. _this.REFLECTIONOVERALPHA = false;
  41916. _this.TWOSIDEDLIGHTING = false;
  41917. _this.SHADOWFLOAT = false;
  41918. _this.MORPHTARGETS = false;
  41919. _this.MORPHTARGETS_NORMAL = false;
  41920. _this.MORPHTARGETS_TANGENT = false;
  41921. _this.NUM_MORPH_INFLUENCERS = 0;
  41922. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41923. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41924. _this.IMAGEPROCESSING = false;
  41925. _this.VIGNETTE = false;
  41926. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41927. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41928. _this.TONEMAPPING = false;
  41929. _this.TONEMAPPING_ACES = false;
  41930. _this.CONTRAST = false;
  41931. _this.COLORCURVES = false;
  41932. _this.COLORGRADING = false;
  41933. _this.COLORGRADING3D = false;
  41934. _this.SAMPLER3DGREENDEPTH = false;
  41935. _this.SAMPLER3DBGRMAP = false;
  41936. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41937. /**
  41938. * If the reflection texture on this material is in linear color space
  41939. * @hidden
  41940. */
  41941. _this.IS_REFLECTION_LINEAR = false;
  41942. /**
  41943. * If the refraction texture on this material is in linear color space
  41944. * @hidden
  41945. */
  41946. _this.IS_REFRACTION_LINEAR = false;
  41947. _this.EXPOSURE = false;
  41948. _this.rebuild();
  41949. return _this;
  41950. }
  41951. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41952. var modes = [
  41953. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41954. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41955. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41956. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41957. ];
  41958. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41959. var mode = modes_1[_i];
  41960. this[mode] = (mode === modeToEnable);
  41961. }
  41962. };
  41963. return StandardMaterialDefines;
  41964. }(BABYLON.MaterialDefines));
  41965. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41966. var StandardMaterial = /** @class */ (function (_super) {
  41967. __extends(StandardMaterial, _super);
  41968. function StandardMaterial(name, scene) {
  41969. var _this = _super.call(this, name, scene) || this;
  41970. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41971. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41972. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41973. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41974. _this.specularPower = 64;
  41975. _this._useAlphaFromDiffuseTexture = false;
  41976. _this._useEmissiveAsIllumination = false;
  41977. _this._linkEmissiveWithDiffuse = false;
  41978. _this._useSpecularOverAlpha = false;
  41979. _this._useReflectionOverAlpha = false;
  41980. _this._disableLighting = false;
  41981. _this._useObjectSpaceNormalMap = false;
  41982. _this._useParallax = false;
  41983. _this._useParallaxOcclusion = false;
  41984. _this.parallaxScaleBias = 0.05;
  41985. _this._roughness = 0;
  41986. _this.indexOfRefraction = 0.98;
  41987. _this.invertRefractionY = true;
  41988. /**
  41989. * Defines the alpha limits in alpha test mode
  41990. */
  41991. _this.alphaCutOff = 0.4;
  41992. _this._useLightmapAsShadowmap = false;
  41993. _this._useReflectionFresnelFromSpecular = false;
  41994. _this._useGlossinessFromSpecularMapAlpha = false;
  41995. _this._maxSimultaneousLights = 4;
  41996. /**
  41997. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41998. */
  41999. _this._invertNormalMapX = false;
  42000. /**
  42001. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42002. */
  42003. _this._invertNormalMapY = false;
  42004. /**
  42005. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42006. */
  42007. _this._twoSidedLighting = false;
  42008. _this._renderTargets = new BABYLON.SmartArray(16);
  42009. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42010. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42011. // Setup the default processing configuration to the scene.
  42012. _this._attachImageProcessingConfiguration(null);
  42013. _this.getRenderTargetTextures = function () {
  42014. _this._renderTargets.reset();
  42015. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42016. _this._renderTargets.push(_this._reflectionTexture);
  42017. }
  42018. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42019. _this._renderTargets.push(_this._refractionTexture);
  42020. }
  42021. return _this._renderTargets;
  42022. };
  42023. return _this;
  42024. }
  42025. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42026. /**
  42027. * Gets the image processing configuration used either in this material.
  42028. */
  42029. get: function () {
  42030. return this._imageProcessingConfiguration;
  42031. },
  42032. /**
  42033. * Sets the Default image processing configuration used either in the this material.
  42034. *
  42035. * If sets to null, the scene one is in use.
  42036. */
  42037. set: function (value) {
  42038. this._attachImageProcessingConfiguration(value);
  42039. // Ensure the effect will be rebuilt.
  42040. this._markAllSubMeshesAsTexturesDirty();
  42041. },
  42042. enumerable: true,
  42043. configurable: true
  42044. });
  42045. /**
  42046. * Attaches a new image processing configuration to the Standard Material.
  42047. * @param configuration
  42048. */
  42049. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42050. var _this = this;
  42051. if (configuration === this._imageProcessingConfiguration) {
  42052. return;
  42053. }
  42054. // Detaches observer.
  42055. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42056. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42057. }
  42058. // Pick the scene configuration if needed.
  42059. if (!configuration) {
  42060. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42061. }
  42062. else {
  42063. this._imageProcessingConfiguration = configuration;
  42064. }
  42065. // Attaches observer.
  42066. if (this._imageProcessingConfiguration) {
  42067. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42068. _this._markAllSubMeshesAsImageProcessingDirty();
  42069. });
  42070. }
  42071. };
  42072. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42073. /**
  42074. * Gets wether the color curves effect is enabled.
  42075. */
  42076. get: function () {
  42077. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42078. },
  42079. /**
  42080. * Sets wether the color curves effect is enabled.
  42081. */
  42082. set: function (value) {
  42083. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42084. },
  42085. enumerable: true,
  42086. configurable: true
  42087. });
  42088. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42089. /**
  42090. * Gets wether the color grading effect is enabled.
  42091. */
  42092. get: function () {
  42093. return this.imageProcessingConfiguration.colorGradingEnabled;
  42094. },
  42095. /**
  42096. * Gets wether the color grading effect is enabled.
  42097. */
  42098. set: function (value) {
  42099. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42100. },
  42101. enumerable: true,
  42102. configurable: true
  42103. });
  42104. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42105. /**
  42106. * Gets wether tonemapping is enabled or not.
  42107. */
  42108. get: function () {
  42109. return this._imageProcessingConfiguration.toneMappingEnabled;
  42110. },
  42111. /**
  42112. * Sets wether tonemapping is enabled or not
  42113. */
  42114. set: function (value) {
  42115. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42116. },
  42117. enumerable: true,
  42118. configurable: true
  42119. });
  42120. ;
  42121. ;
  42122. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42123. /**
  42124. * The camera exposure used on this material.
  42125. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42126. * This corresponds to a photographic exposure.
  42127. */
  42128. get: function () {
  42129. return this._imageProcessingConfiguration.exposure;
  42130. },
  42131. /**
  42132. * The camera exposure used on this material.
  42133. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42134. * This corresponds to a photographic exposure.
  42135. */
  42136. set: function (value) {
  42137. this._imageProcessingConfiguration.exposure = value;
  42138. },
  42139. enumerable: true,
  42140. configurable: true
  42141. });
  42142. ;
  42143. ;
  42144. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42145. /**
  42146. * Gets The camera contrast used on this material.
  42147. */
  42148. get: function () {
  42149. return this._imageProcessingConfiguration.contrast;
  42150. },
  42151. /**
  42152. * Sets The camera contrast used on this material.
  42153. */
  42154. set: function (value) {
  42155. this._imageProcessingConfiguration.contrast = value;
  42156. },
  42157. enumerable: true,
  42158. configurable: true
  42159. });
  42160. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42161. /**
  42162. * Gets the Color Grading 2D Lookup Texture.
  42163. */
  42164. get: function () {
  42165. return this._imageProcessingConfiguration.colorGradingTexture;
  42166. },
  42167. /**
  42168. * Sets the Color Grading 2D Lookup Texture.
  42169. */
  42170. set: function (value) {
  42171. this._imageProcessingConfiguration.colorGradingTexture = value;
  42172. },
  42173. enumerable: true,
  42174. configurable: true
  42175. });
  42176. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42177. /**
  42178. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42179. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42180. * 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;
  42181. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42182. */
  42183. get: function () {
  42184. return this._imageProcessingConfiguration.colorCurves;
  42185. },
  42186. /**
  42187. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42188. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42189. * 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;
  42190. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42191. */
  42192. set: function (value) {
  42193. this._imageProcessingConfiguration.colorCurves = value;
  42194. },
  42195. enumerable: true,
  42196. configurable: true
  42197. });
  42198. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  42199. /**
  42200. * Gets a boolean indicating that current material needs to register RTT
  42201. */
  42202. get: function () {
  42203. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42204. return true;
  42205. }
  42206. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42207. return true;
  42208. }
  42209. return false;
  42210. },
  42211. enumerable: true,
  42212. configurable: true
  42213. });
  42214. StandardMaterial.prototype.getClassName = function () {
  42215. return "StandardMaterial";
  42216. };
  42217. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42218. get: function () {
  42219. return this._useLogarithmicDepth;
  42220. },
  42221. set: function (value) {
  42222. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42223. this._markAllSubMeshesAsMiscDirty();
  42224. },
  42225. enumerable: true,
  42226. configurable: true
  42227. });
  42228. StandardMaterial.prototype.needAlphaBlending = function () {
  42229. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42230. };
  42231. StandardMaterial.prototype.needAlphaTesting = function () {
  42232. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42233. };
  42234. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42235. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42236. };
  42237. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42238. return this._diffuseTexture;
  42239. };
  42240. /**
  42241. * Child classes can use it to update shaders
  42242. */
  42243. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42244. if (useInstances === void 0) { useInstances = false; }
  42245. if (subMesh.effect && this.isFrozen) {
  42246. if (this._wasPreviouslyReady) {
  42247. return true;
  42248. }
  42249. }
  42250. if (!subMesh._materialDefines) {
  42251. subMesh._materialDefines = new StandardMaterialDefines();
  42252. }
  42253. var scene = this.getScene();
  42254. var defines = subMesh._materialDefines;
  42255. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42256. if (defines._renderId === scene.getRenderId()) {
  42257. return true;
  42258. }
  42259. }
  42260. var engine = scene.getEngine();
  42261. // Lights
  42262. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42263. // Textures
  42264. if (defines._areTexturesDirty) {
  42265. defines._needUVs = false;
  42266. defines.MAINUV1 = false;
  42267. defines.MAINUV2 = false;
  42268. if (scene.texturesEnabled) {
  42269. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42270. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42271. return false;
  42272. }
  42273. else {
  42274. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42275. }
  42276. }
  42277. else {
  42278. defines.DIFFUSE = false;
  42279. }
  42280. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42281. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42282. return false;
  42283. }
  42284. else {
  42285. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42286. }
  42287. }
  42288. else {
  42289. defines.AMBIENT = false;
  42290. }
  42291. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42292. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42293. return false;
  42294. }
  42295. else {
  42296. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42297. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42298. }
  42299. }
  42300. else {
  42301. defines.OPACITY = false;
  42302. }
  42303. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42304. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42305. return false;
  42306. }
  42307. else {
  42308. defines._needNormals = true;
  42309. defines.REFLECTION = true;
  42310. defines.ROUGHNESS = (this._roughness > 0);
  42311. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42312. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42313. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42314. switch (this._reflectionTexture.coordinatesMode) {
  42315. case BABYLON.Texture.EXPLICIT_MODE:
  42316. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42317. break;
  42318. case BABYLON.Texture.PLANAR_MODE:
  42319. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42320. break;
  42321. case BABYLON.Texture.PROJECTION_MODE:
  42322. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42323. break;
  42324. case BABYLON.Texture.SKYBOX_MODE:
  42325. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42326. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  42327. break;
  42328. case BABYLON.Texture.SPHERICAL_MODE:
  42329. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42330. break;
  42331. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42332. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42333. break;
  42334. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42335. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42336. break;
  42337. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42338. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42339. break;
  42340. case BABYLON.Texture.CUBIC_MODE:
  42341. case BABYLON.Texture.INVCUBIC_MODE:
  42342. default:
  42343. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42344. break;
  42345. }
  42346. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42347. }
  42348. }
  42349. else {
  42350. defines.REFLECTION = false;
  42351. }
  42352. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42353. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42354. return false;
  42355. }
  42356. else {
  42357. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42358. }
  42359. }
  42360. else {
  42361. defines.EMISSIVE = false;
  42362. }
  42363. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42364. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42365. return false;
  42366. }
  42367. else {
  42368. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42369. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42370. }
  42371. }
  42372. else {
  42373. defines.LIGHTMAP = false;
  42374. }
  42375. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42376. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42377. return false;
  42378. }
  42379. else {
  42380. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42381. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42382. }
  42383. }
  42384. else {
  42385. defines.SPECULAR = false;
  42386. }
  42387. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42388. // Bump texure can not be not blocking.
  42389. if (!this._bumpTexture.isReady()) {
  42390. return false;
  42391. }
  42392. else {
  42393. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42394. defines.PARALLAX = this._useParallax;
  42395. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42396. }
  42397. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42398. }
  42399. else {
  42400. defines.BUMP = false;
  42401. }
  42402. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42403. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42404. return false;
  42405. }
  42406. else {
  42407. defines._needUVs = true;
  42408. defines.REFRACTION = true;
  42409. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42410. }
  42411. }
  42412. else {
  42413. defines.REFRACTION = false;
  42414. }
  42415. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42416. }
  42417. else {
  42418. defines.DIFFUSE = false;
  42419. defines.AMBIENT = false;
  42420. defines.OPACITY = false;
  42421. defines.REFLECTION = false;
  42422. defines.EMISSIVE = false;
  42423. defines.LIGHTMAP = false;
  42424. defines.BUMP = false;
  42425. defines.REFRACTION = false;
  42426. }
  42427. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42428. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42429. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42430. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42431. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42432. }
  42433. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42434. if (!this._imageProcessingConfiguration.isReady()) {
  42435. return false;
  42436. }
  42437. this._imageProcessingConfiguration.prepareDefines(defines);
  42438. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42439. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42440. }
  42441. if (defines._areFresnelDirty) {
  42442. if (StandardMaterial.FresnelEnabled) {
  42443. // Fresnel
  42444. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42445. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42446. this._reflectionFresnelParameters) {
  42447. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42448. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42449. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42450. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42451. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42452. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42453. defines._needNormals = true;
  42454. defines.FRESNEL = true;
  42455. }
  42456. }
  42457. else {
  42458. defines.FRESNEL = false;
  42459. }
  42460. }
  42461. // Misc.
  42462. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42463. // Attribs
  42464. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42465. // Values that need to be evaluated on every frame
  42466. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42467. // Get correct effect
  42468. if (defines.isDirty) {
  42469. defines.markAsProcessed();
  42470. scene.resetCachedMaterial();
  42471. // Fallbacks
  42472. var fallbacks = new BABYLON.EffectFallbacks();
  42473. if (defines.REFLECTION) {
  42474. fallbacks.addFallback(0, "REFLECTION");
  42475. }
  42476. if (defines.SPECULAR) {
  42477. fallbacks.addFallback(0, "SPECULAR");
  42478. }
  42479. if (defines.BUMP) {
  42480. fallbacks.addFallback(0, "BUMP");
  42481. }
  42482. if (defines.PARALLAX) {
  42483. fallbacks.addFallback(1, "PARALLAX");
  42484. }
  42485. if (defines.PARALLAXOCCLUSION) {
  42486. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42487. }
  42488. if (defines.SPECULAROVERALPHA) {
  42489. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42490. }
  42491. if (defines.FOG) {
  42492. fallbacks.addFallback(1, "FOG");
  42493. }
  42494. if (defines.POINTSIZE) {
  42495. fallbacks.addFallback(0, "POINTSIZE");
  42496. }
  42497. if (defines.LOGARITHMICDEPTH) {
  42498. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42499. }
  42500. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42501. if (defines.SPECULARTERM) {
  42502. fallbacks.addFallback(0, "SPECULARTERM");
  42503. }
  42504. if (defines.DIFFUSEFRESNEL) {
  42505. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42506. }
  42507. if (defines.OPACITYFRESNEL) {
  42508. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42509. }
  42510. if (defines.REFLECTIONFRESNEL) {
  42511. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42512. }
  42513. if (defines.EMISSIVEFRESNEL) {
  42514. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42515. }
  42516. if (defines.FRESNEL) {
  42517. fallbacks.addFallback(4, "FRESNEL");
  42518. }
  42519. //Attributes
  42520. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42521. if (defines.NORMAL) {
  42522. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42523. }
  42524. if (defines.UV1) {
  42525. attribs.push(BABYLON.VertexBuffer.UVKind);
  42526. }
  42527. if (defines.UV2) {
  42528. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42529. }
  42530. if (defines.VERTEXCOLOR) {
  42531. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42532. }
  42533. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42534. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42535. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42536. var shaderName = "default";
  42537. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42538. "vFogInfos", "vFogColor", "pointSize",
  42539. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42540. "mBones",
  42541. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42542. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42543. "vReflectionPosition", "vReflectionSize",
  42544. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42545. ];
  42546. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42547. var uniformBuffers = ["Material", "Scene"];
  42548. if (BABYLON.ImageProcessingConfiguration) {
  42549. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42550. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42551. }
  42552. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42553. uniformsNames: uniforms,
  42554. uniformBuffersNames: uniformBuffers,
  42555. samplers: samplers,
  42556. defines: defines,
  42557. maxSimultaneousLights: this._maxSimultaneousLights
  42558. });
  42559. if (this.customShaderNameResolve) {
  42560. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42561. }
  42562. var join = defines.toString();
  42563. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42564. attributes: attribs,
  42565. uniformsNames: uniforms,
  42566. uniformBuffersNames: uniformBuffers,
  42567. samplers: samplers,
  42568. defines: join,
  42569. fallbacks: fallbacks,
  42570. onCompiled: this.onCompiled,
  42571. onError: this.onError,
  42572. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42573. }, engine), defines);
  42574. this.buildUniformLayout();
  42575. }
  42576. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42577. return false;
  42578. }
  42579. defines._renderId = scene.getRenderId();
  42580. this._wasPreviouslyReady = true;
  42581. return true;
  42582. };
  42583. StandardMaterial.prototype.buildUniformLayout = function () {
  42584. // Order is important !
  42585. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42586. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42587. this._uniformBuffer.addUniform("opacityParts", 4);
  42588. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42589. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42590. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42591. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42592. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42593. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42594. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42595. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42596. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42597. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42598. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42599. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42600. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42601. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42602. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42603. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42604. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42605. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42606. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42607. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42608. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42609. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42610. this._uniformBuffer.addUniform("specularMatrix", 16);
  42611. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42612. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42613. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42614. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42615. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42616. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42617. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42618. this._uniformBuffer.addUniform("pointSize", 1);
  42619. this._uniformBuffer.create();
  42620. };
  42621. StandardMaterial.prototype.unbind = function () {
  42622. if (this._activeEffect) {
  42623. var needFlag = false;
  42624. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42625. this._activeEffect.setTexture("reflection2DSampler", null);
  42626. needFlag = true;
  42627. }
  42628. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42629. this._activeEffect.setTexture("refraction2DSampler", null);
  42630. needFlag = true;
  42631. }
  42632. if (needFlag) {
  42633. this._markAllSubMeshesAsTexturesDirty();
  42634. }
  42635. }
  42636. _super.prototype.unbind.call(this);
  42637. };
  42638. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42639. var scene = this.getScene();
  42640. var defines = subMesh._materialDefines;
  42641. if (!defines) {
  42642. return;
  42643. }
  42644. var effect = subMesh.effect;
  42645. if (!effect) {
  42646. return;
  42647. }
  42648. this._activeEffect = effect;
  42649. // Matrices
  42650. this.bindOnlyWorldMatrix(world);
  42651. // Normal Matrix
  42652. if (defines.OBJECTSPACE_NORMALMAP) {
  42653. world.toNormalMatrix(this._normalMatrix);
  42654. this.bindOnlyNormalMatrix(this._normalMatrix);
  42655. }
  42656. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42657. // Bones
  42658. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42659. if (mustRebind) {
  42660. this._uniformBuffer.bindToEffect(effect, "Material");
  42661. this.bindViewProjection(effect);
  42662. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42663. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42664. // Fresnel
  42665. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42666. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42667. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42668. }
  42669. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42670. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42671. }
  42672. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42673. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42674. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42675. }
  42676. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42677. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42678. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42679. }
  42680. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42681. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42682. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42683. }
  42684. }
  42685. // Textures
  42686. if (scene.texturesEnabled) {
  42687. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42688. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42689. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42690. if (this._diffuseTexture.hasAlpha) {
  42691. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42692. }
  42693. }
  42694. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42695. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42696. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42697. }
  42698. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42699. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42700. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42701. }
  42702. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42703. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42704. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42705. if (this._reflectionTexture.boundingBoxSize) {
  42706. var cubeTexture = this._reflectionTexture;
  42707. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42708. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42709. }
  42710. }
  42711. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42712. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42713. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42714. }
  42715. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42716. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42717. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42718. }
  42719. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42720. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42721. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42722. }
  42723. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42724. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42725. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42726. if (scene._mirroredCameraPosition) {
  42727. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42728. }
  42729. else {
  42730. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42731. }
  42732. }
  42733. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42734. var depth = 1.0;
  42735. if (!this._refractionTexture.isCube) {
  42736. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42737. if (this._refractionTexture.depth) {
  42738. depth = this._refractionTexture.depth;
  42739. }
  42740. }
  42741. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42742. }
  42743. }
  42744. // Point size
  42745. if (this.pointsCloud) {
  42746. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42747. }
  42748. if (defines.SPECULARTERM) {
  42749. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42750. }
  42751. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42752. // Diffuse
  42753. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42754. }
  42755. // Textures
  42756. if (scene.texturesEnabled) {
  42757. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42758. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42759. }
  42760. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42761. effect.setTexture("ambientSampler", this._ambientTexture);
  42762. }
  42763. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42764. effect.setTexture("opacitySampler", this._opacityTexture);
  42765. }
  42766. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42767. if (this._reflectionTexture.isCube) {
  42768. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42769. }
  42770. else {
  42771. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42772. }
  42773. }
  42774. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42775. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42776. }
  42777. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42778. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42779. }
  42780. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42781. effect.setTexture("specularSampler", this._specularTexture);
  42782. }
  42783. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42784. effect.setTexture("bumpSampler", this._bumpTexture);
  42785. }
  42786. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42787. var depth = 1.0;
  42788. if (this._refractionTexture.isCube) {
  42789. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42790. }
  42791. else {
  42792. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42793. }
  42794. }
  42795. }
  42796. // Clip plane
  42797. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42798. // Colors
  42799. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42800. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42801. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42802. }
  42803. if (mustRebind || !this.isFrozen) {
  42804. // Lights
  42805. if (scene.lightsEnabled && !this._disableLighting) {
  42806. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42807. }
  42808. // View
  42809. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42810. this.bindView(effect);
  42811. }
  42812. // Fog
  42813. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42814. // Morph targets
  42815. if (defines.NUM_MORPH_INFLUENCERS) {
  42816. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42817. }
  42818. // Log. depth
  42819. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42820. // image processing
  42821. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42822. this._imageProcessingConfiguration.bind(this._activeEffect);
  42823. }
  42824. }
  42825. this._uniformBuffer.update();
  42826. this._afterBind(mesh, this._activeEffect);
  42827. };
  42828. StandardMaterial.prototype.getAnimatables = function () {
  42829. var results = [];
  42830. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42831. results.push(this._diffuseTexture);
  42832. }
  42833. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42834. results.push(this._ambientTexture);
  42835. }
  42836. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42837. results.push(this._opacityTexture);
  42838. }
  42839. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42840. results.push(this._reflectionTexture);
  42841. }
  42842. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42843. results.push(this._emissiveTexture);
  42844. }
  42845. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42846. results.push(this._specularTexture);
  42847. }
  42848. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42849. results.push(this._bumpTexture);
  42850. }
  42851. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42852. results.push(this._lightmapTexture);
  42853. }
  42854. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42855. results.push(this._refractionTexture);
  42856. }
  42857. return results;
  42858. };
  42859. StandardMaterial.prototype.getActiveTextures = function () {
  42860. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42861. if (this._diffuseTexture) {
  42862. activeTextures.push(this._diffuseTexture);
  42863. }
  42864. if (this._ambientTexture) {
  42865. activeTextures.push(this._ambientTexture);
  42866. }
  42867. if (this._opacityTexture) {
  42868. activeTextures.push(this._opacityTexture);
  42869. }
  42870. if (this._reflectionTexture) {
  42871. activeTextures.push(this._reflectionTexture);
  42872. }
  42873. if (this._emissiveTexture) {
  42874. activeTextures.push(this._emissiveTexture);
  42875. }
  42876. if (this._specularTexture) {
  42877. activeTextures.push(this._specularTexture);
  42878. }
  42879. if (this._bumpTexture) {
  42880. activeTextures.push(this._bumpTexture);
  42881. }
  42882. if (this._lightmapTexture) {
  42883. activeTextures.push(this._lightmapTexture);
  42884. }
  42885. if (this._refractionTexture) {
  42886. activeTextures.push(this._refractionTexture);
  42887. }
  42888. return activeTextures;
  42889. };
  42890. StandardMaterial.prototype.hasTexture = function (texture) {
  42891. if (_super.prototype.hasTexture.call(this, texture)) {
  42892. return true;
  42893. }
  42894. if (this._diffuseTexture === texture) {
  42895. return true;
  42896. }
  42897. if (this._ambientTexture === texture) {
  42898. return true;
  42899. }
  42900. if (this._opacityTexture === texture) {
  42901. return true;
  42902. }
  42903. if (this._reflectionTexture === texture) {
  42904. return true;
  42905. }
  42906. if (this._emissiveTexture === texture) {
  42907. return true;
  42908. }
  42909. if (this._specularTexture === texture) {
  42910. return true;
  42911. }
  42912. if (this._bumpTexture === texture) {
  42913. return true;
  42914. }
  42915. if (this._lightmapTexture === texture) {
  42916. return true;
  42917. }
  42918. if (this._refractionTexture === texture) {
  42919. return true;
  42920. }
  42921. return false;
  42922. };
  42923. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42924. if (forceDisposeTextures) {
  42925. if (this._diffuseTexture) {
  42926. this._diffuseTexture.dispose();
  42927. }
  42928. if (this._ambientTexture) {
  42929. this._ambientTexture.dispose();
  42930. }
  42931. if (this._opacityTexture) {
  42932. this._opacityTexture.dispose();
  42933. }
  42934. if (this._reflectionTexture) {
  42935. this._reflectionTexture.dispose();
  42936. }
  42937. if (this._emissiveTexture) {
  42938. this._emissiveTexture.dispose();
  42939. }
  42940. if (this._specularTexture) {
  42941. this._specularTexture.dispose();
  42942. }
  42943. if (this._bumpTexture) {
  42944. this._bumpTexture.dispose();
  42945. }
  42946. if (this._lightmapTexture) {
  42947. this._lightmapTexture.dispose();
  42948. }
  42949. if (this._refractionTexture) {
  42950. this._refractionTexture.dispose();
  42951. }
  42952. }
  42953. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42954. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42955. }
  42956. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42957. };
  42958. StandardMaterial.prototype.clone = function (name) {
  42959. var _this = this;
  42960. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42961. result.name = name;
  42962. result.id = name;
  42963. return result;
  42964. };
  42965. StandardMaterial.prototype.serialize = function () {
  42966. return BABYLON.SerializationHelper.Serialize(this);
  42967. };
  42968. // Statics
  42969. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42970. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42971. };
  42972. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42973. get: function () {
  42974. return StandardMaterial._DiffuseTextureEnabled;
  42975. },
  42976. set: function (value) {
  42977. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42978. return;
  42979. }
  42980. StandardMaterial._DiffuseTextureEnabled = value;
  42981. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42982. },
  42983. enumerable: true,
  42984. configurable: true
  42985. });
  42986. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42987. get: function () {
  42988. return StandardMaterial._AmbientTextureEnabled;
  42989. },
  42990. set: function (value) {
  42991. if (StandardMaterial._AmbientTextureEnabled === value) {
  42992. return;
  42993. }
  42994. StandardMaterial._AmbientTextureEnabled = value;
  42995. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42996. },
  42997. enumerable: true,
  42998. configurable: true
  42999. });
  43000. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43001. get: function () {
  43002. return StandardMaterial._OpacityTextureEnabled;
  43003. },
  43004. set: function (value) {
  43005. if (StandardMaterial._OpacityTextureEnabled === value) {
  43006. return;
  43007. }
  43008. StandardMaterial._OpacityTextureEnabled = value;
  43009. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43010. },
  43011. enumerable: true,
  43012. configurable: true
  43013. });
  43014. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43015. get: function () {
  43016. return StandardMaterial._ReflectionTextureEnabled;
  43017. },
  43018. set: function (value) {
  43019. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43020. return;
  43021. }
  43022. StandardMaterial._ReflectionTextureEnabled = value;
  43023. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43024. },
  43025. enumerable: true,
  43026. configurable: true
  43027. });
  43028. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43029. get: function () {
  43030. return StandardMaterial._EmissiveTextureEnabled;
  43031. },
  43032. set: function (value) {
  43033. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43034. return;
  43035. }
  43036. StandardMaterial._EmissiveTextureEnabled = value;
  43037. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43038. },
  43039. enumerable: true,
  43040. configurable: true
  43041. });
  43042. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43043. get: function () {
  43044. return StandardMaterial._SpecularTextureEnabled;
  43045. },
  43046. set: function (value) {
  43047. if (StandardMaterial._SpecularTextureEnabled === value) {
  43048. return;
  43049. }
  43050. StandardMaterial._SpecularTextureEnabled = value;
  43051. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43052. },
  43053. enumerable: true,
  43054. configurable: true
  43055. });
  43056. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43057. get: function () {
  43058. return StandardMaterial._BumpTextureEnabled;
  43059. },
  43060. set: function (value) {
  43061. if (StandardMaterial._BumpTextureEnabled === value) {
  43062. return;
  43063. }
  43064. StandardMaterial._BumpTextureEnabled = value;
  43065. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43066. },
  43067. enumerable: true,
  43068. configurable: true
  43069. });
  43070. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43071. get: function () {
  43072. return StandardMaterial._LightmapTextureEnabled;
  43073. },
  43074. set: function (value) {
  43075. if (StandardMaterial._LightmapTextureEnabled === value) {
  43076. return;
  43077. }
  43078. StandardMaterial._LightmapTextureEnabled = value;
  43079. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43080. },
  43081. enumerable: true,
  43082. configurable: true
  43083. });
  43084. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43085. get: function () {
  43086. return StandardMaterial._RefractionTextureEnabled;
  43087. },
  43088. set: function (value) {
  43089. if (StandardMaterial._RefractionTextureEnabled === value) {
  43090. return;
  43091. }
  43092. StandardMaterial._RefractionTextureEnabled = value;
  43093. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43094. },
  43095. enumerable: true,
  43096. configurable: true
  43097. });
  43098. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43099. get: function () {
  43100. return StandardMaterial._ColorGradingTextureEnabled;
  43101. },
  43102. set: function (value) {
  43103. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43104. return;
  43105. }
  43106. StandardMaterial._ColorGradingTextureEnabled = value;
  43107. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43108. },
  43109. enumerable: true,
  43110. configurable: true
  43111. });
  43112. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43113. get: function () {
  43114. return StandardMaterial._FresnelEnabled;
  43115. },
  43116. set: function (value) {
  43117. if (StandardMaterial._FresnelEnabled === value) {
  43118. return;
  43119. }
  43120. StandardMaterial._FresnelEnabled = value;
  43121. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43122. },
  43123. enumerable: true,
  43124. configurable: true
  43125. });
  43126. // Flags used to enable or disable a type of texture for all Standard Materials
  43127. StandardMaterial._DiffuseTextureEnabled = true;
  43128. StandardMaterial._AmbientTextureEnabled = true;
  43129. StandardMaterial._OpacityTextureEnabled = true;
  43130. StandardMaterial._ReflectionTextureEnabled = true;
  43131. StandardMaterial._EmissiveTextureEnabled = true;
  43132. StandardMaterial._SpecularTextureEnabled = true;
  43133. StandardMaterial._BumpTextureEnabled = true;
  43134. StandardMaterial._LightmapTextureEnabled = true;
  43135. StandardMaterial._RefractionTextureEnabled = true;
  43136. StandardMaterial._ColorGradingTextureEnabled = true;
  43137. StandardMaterial._FresnelEnabled = true;
  43138. __decorate([
  43139. BABYLON.serializeAsTexture("diffuseTexture")
  43140. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43141. __decorate([
  43142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43143. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43144. __decorate([
  43145. BABYLON.serializeAsTexture("ambientTexture")
  43146. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43147. __decorate([
  43148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43149. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43150. __decorate([
  43151. BABYLON.serializeAsTexture("opacityTexture")
  43152. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43153. __decorate([
  43154. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43155. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43156. __decorate([
  43157. BABYLON.serializeAsTexture("reflectionTexture")
  43158. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43159. __decorate([
  43160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43161. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43162. __decorate([
  43163. BABYLON.serializeAsTexture("emissiveTexture")
  43164. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43165. __decorate([
  43166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43167. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43168. __decorate([
  43169. BABYLON.serializeAsTexture("specularTexture")
  43170. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43171. __decorate([
  43172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43173. ], StandardMaterial.prototype, "specularTexture", void 0);
  43174. __decorate([
  43175. BABYLON.serializeAsTexture("bumpTexture")
  43176. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43177. __decorate([
  43178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43179. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43180. __decorate([
  43181. BABYLON.serializeAsTexture("lightmapTexture")
  43182. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43183. __decorate([
  43184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43185. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43186. __decorate([
  43187. BABYLON.serializeAsTexture("refractionTexture")
  43188. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43189. __decorate([
  43190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43191. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43192. __decorate([
  43193. BABYLON.serializeAsColor3("ambient")
  43194. ], StandardMaterial.prototype, "ambientColor", void 0);
  43195. __decorate([
  43196. BABYLON.serializeAsColor3("diffuse")
  43197. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43198. __decorate([
  43199. BABYLON.serializeAsColor3("specular")
  43200. ], StandardMaterial.prototype, "specularColor", void 0);
  43201. __decorate([
  43202. BABYLON.serializeAsColor3("emissive")
  43203. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43204. __decorate([
  43205. BABYLON.serialize()
  43206. ], StandardMaterial.prototype, "specularPower", void 0);
  43207. __decorate([
  43208. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43209. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43210. __decorate([
  43211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43212. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43213. __decorate([
  43214. BABYLON.serialize("useEmissiveAsIllumination")
  43215. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43216. __decorate([
  43217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43218. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43219. __decorate([
  43220. BABYLON.serialize("linkEmissiveWithDiffuse")
  43221. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43222. __decorate([
  43223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43224. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43225. __decorate([
  43226. BABYLON.serialize("useSpecularOverAlpha")
  43227. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43228. __decorate([
  43229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43230. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43231. __decorate([
  43232. BABYLON.serialize("useReflectionOverAlpha")
  43233. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43234. __decorate([
  43235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43236. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43237. __decorate([
  43238. BABYLON.serialize("disableLighting")
  43239. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43240. __decorate([
  43241. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43242. ], StandardMaterial.prototype, "disableLighting", void 0);
  43243. __decorate([
  43244. BABYLON.serialize("useObjectSpaceNormalMap")
  43245. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43246. __decorate([
  43247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43248. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43249. __decorate([
  43250. BABYLON.serialize("useParallax")
  43251. ], StandardMaterial.prototype, "_useParallax", void 0);
  43252. __decorate([
  43253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43254. ], StandardMaterial.prototype, "useParallax", void 0);
  43255. __decorate([
  43256. BABYLON.serialize("useParallaxOcclusion")
  43257. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43258. __decorate([
  43259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43260. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43261. __decorate([
  43262. BABYLON.serialize()
  43263. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43264. __decorate([
  43265. BABYLON.serialize("roughness")
  43266. ], StandardMaterial.prototype, "_roughness", void 0);
  43267. __decorate([
  43268. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43269. ], StandardMaterial.prototype, "roughness", void 0);
  43270. __decorate([
  43271. BABYLON.serialize()
  43272. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43273. __decorate([
  43274. BABYLON.serialize()
  43275. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43276. __decorate([
  43277. BABYLON.serialize()
  43278. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43279. __decorate([
  43280. BABYLON.serialize("useLightmapAsShadowmap")
  43281. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43282. __decorate([
  43283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43284. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43285. __decorate([
  43286. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43287. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43288. __decorate([
  43289. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43290. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43291. __decorate([
  43292. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43293. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43294. __decorate([
  43295. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43296. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43297. __decorate([
  43298. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43299. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43300. __decorate([
  43301. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43302. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43303. __decorate([
  43304. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43305. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43306. __decorate([
  43307. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43308. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43309. __decorate([
  43310. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43311. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43312. __decorate([
  43313. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43314. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43315. __decorate([
  43316. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43317. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43318. __decorate([
  43319. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43320. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43321. __decorate([
  43322. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43323. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43324. __decorate([
  43325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43326. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43327. __decorate([
  43328. BABYLON.serialize("maxSimultaneousLights")
  43329. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43330. __decorate([
  43331. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43332. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43333. __decorate([
  43334. BABYLON.serialize("invertNormalMapX")
  43335. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43336. __decorate([
  43337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43338. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43339. __decorate([
  43340. BABYLON.serialize("invertNormalMapY")
  43341. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43342. __decorate([
  43343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43344. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43345. __decorate([
  43346. BABYLON.serialize("twoSidedLighting")
  43347. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43348. __decorate([
  43349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43350. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43351. __decorate([
  43352. BABYLON.serialize()
  43353. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43354. return StandardMaterial;
  43355. }(BABYLON.PushMaterial));
  43356. BABYLON.StandardMaterial = StandardMaterial;
  43357. })(BABYLON || (BABYLON = {}));
  43358. //# sourceMappingURL=babylon.standardMaterial.js.map
  43359. var BABYLON;
  43360. (function (BABYLON) {
  43361. /**
  43362. * Class representing spherical polynomial coefficients to the 3rd degree
  43363. */
  43364. var SphericalPolynomial = /** @class */ (function () {
  43365. function SphericalPolynomial() {
  43366. /**
  43367. * The x coefficients of the spherical polynomial
  43368. */
  43369. this.x = BABYLON.Vector3.Zero();
  43370. /**
  43371. * The y coefficients of the spherical polynomial
  43372. */
  43373. this.y = BABYLON.Vector3.Zero();
  43374. /**
  43375. * The z coefficients of the spherical polynomial
  43376. */
  43377. this.z = BABYLON.Vector3.Zero();
  43378. /**
  43379. * The xx coefficients of the spherical polynomial
  43380. */
  43381. this.xx = BABYLON.Vector3.Zero();
  43382. /**
  43383. * The yy coefficients of the spherical polynomial
  43384. */
  43385. this.yy = BABYLON.Vector3.Zero();
  43386. /**
  43387. * The zz coefficients of the spherical polynomial
  43388. */
  43389. this.zz = BABYLON.Vector3.Zero();
  43390. /**
  43391. * The xy coefficients of the spherical polynomial
  43392. */
  43393. this.xy = BABYLON.Vector3.Zero();
  43394. /**
  43395. * The yz coefficients of the spherical polynomial
  43396. */
  43397. this.yz = BABYLON.Vector3.Zero();
  43398. /**
  43399. * The zx coefficients of the spherical polynomial
  43400. */
  43401. this.zx = BABYLON.Vector3.Zero();
  43402. }
  43403. /**
  43404. * Adds an ambient color to the spherical polynomial
  43405. * @param color the color to add
  43406. */
  43407. SphericalPolynomial.prototype.addAmbient = function (color) {
  43408. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43409. this.xx = this.xx.add(colorVector);
  43410. this.yy = this.yy.add(colorVector);
  43411. this.zz = this.zz.add(colorVector);
  43412. };
  43413. /**
  43414. * Scales the spherical polynomial by the given amount
  43415. * @param scale the amount to scale
  43416. */
  43417. SphericalPolynomial.prototype.scale = function (scale) {
  43418. this.x = this.x.scale(scale);
  43419. this.y = this.y.scale(scale);
  43420. this.z = this.z.scale(scale);
  43421. this.xx = this.xx.scale(scale);
  43422. this.yy = this.yy.scale(scale);
  43423. this.zz = this.zz.scale(scale);
  43424. this.yz = this.yz.scale(scale);
  43425. this.zx = this.zx.scale(scale);
  43426. this.xy = this.xy.scale(scale);
  43427. };
  43428. /**
  43429. * Gets the spherical polynomial from harmonics
  43430. * @param harmonics the spherical harmonics
  43431. * @returns the spherical polynomial
  43432. */
  43433. SphericalPolynomial.FromHarmonics = function (harmonics) {
  43434. var result = new SphericalPolynomial();
  43435. result.x = harmonics.l11.scale(1.02333);
  43436. result.y = harmonics.l1_1.scale(1.02333);
  43437. result.z = harmonics.l10.scale(1.02333);
  43438. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  43439. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  43440. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  43441. result.yz = harmonics.l2_1.scale(0.858086);
  43442. result.zx = harmonics.l21.scale(0.858086);
  43443. result.xy = harmonics.l2_2.scale(0.858086);
  43444. result.scale(1.0 / Math.PI);
  43445. return result;
  43446. };
  43447. /**
  43448. * Constructs a spherical polynomial from an array.
  43449. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  43450. * @returns the spherical polynomial
  43451. */
  43452. SphericalPolynomial.FromArray = function (data) {
  43453. var sp = new SphericalPolynomial();
  43454. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  43455. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  43456. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  43457. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  43458. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  43459. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  43460. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  43461. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  43462. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  43463. return sp;
  43464. };
  43465. return SphericalPolynomial;
  43466. }());
  43467. BABYLON.SphericalPolynomial = SphericalPolynomial;
  43468. /**
  43469. * Class representing spherical harmonics coefficients to the 3rd degree
  43470. */
  43471. var SphericalHarmonics = /** @class */ (function () {
  43472. function SphericalHarmonics() {
  43473. /**
  43474. * The l0,0 coefficients of the spherical harmonics
  43475. */
  43476. this.l00 = BABYLON.Vector3.Zero();
  43477. /**
  43478. * The l1,-1 coefficients of the spherical harmonics
  43479. */
  43480. this.l1_1 = BABYLON.Vector3.Zero();
  43481. /**
  43482. * The l1,0 coefficients of the spherical harmonics
  43483. */
  43484. this.l10 = BABYLON.Vector3.Zero();
  43485. /**
  43486. * The l1,1 coefficients of the spherical harmonics
  43487. */
  43488. this.l11 = BABYLON.Vector3.Zero();
  43489. /**
  43490. * The l2,-2 coefficients of the spherical harmonics
  43491. */
  43492. this.l2_2 = BABYLON.Vector3.Zero();
  43493. /**
  43494. * The l2,-1 coefficients of the spherical harmonics
  43495. */
  43496. this.l2_1 = BABYLON.Vector3.Zero();
  43497. /**
  43498. * The l2,0 coefficients of the spherical harmonics
  43499. */
  43500. this.l20 = BABYLON.Vector3.Zero();
  43501. /**
  43502. * The l2,1 coefficients of the spherical harmonics
  43503. */
  43504. this.l21 = BABYLON.Vector3.Zero();
  43505. /**
  43506. * The l2,2 coefficients of the spherical harmonics
  43507. */
  43508. this.lL22 = BABYLON.Vector3.Zero();
  43509. }
  43510. /**
  43511. * Adds a light to the spherical harmonics
  43512. * @param direction the direction of the light
  43513. * @param color the color of the light
  43514. * @param deltaSolidAngle the delta solid angle of the light
  43515. */
  43516. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43517. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43518. var c = colorVector.scale(deltaSolidAngle);
  43519. this.l00 = this.l00.add(c.scale(0.282095));
  43520. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43521. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43522. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43523. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43524. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43525. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43526. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43527. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43528. };
  43529. /**
  43530. * Scales the spherical harmonics by the given amount
  43531. * @param scale the amount to scale
  43532. */
  43533. SphericalHarmonics.prototype.scale = function (scale) {
  43534. this.l00 = this.l00.scale(scale);
  43535. this.l1_1 = this.l1_1.scale(scale);
  43536. this.l10 = this.l10.scale(scale);
  43537. this.l11 = this.l11.scale(scale);
  43538. this.l2_2 = this.l2_2.scale(scale);
  43539. this.l2_1 = this.l2_1.scale(scale);
  43540. this.l20 = this.l20.scale(scale);
  43541. this.l21 = this.l21.scale(scale);
  43542. this.lL22 = this.lL22.scale(scale);
  43543. };
  43544. /**
  43545. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43546. *
  43547. * ```
  43548. * E_lm = A_l * L_lm
  43549. * ```
  43550. *
  43551. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43552. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43553. * the scaling factors are given in equation 9.
  43554. */
  43555. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43556. // Constant (Band 0)
  43557. this.l00 = this.l00.scale(3.141593);
  43558. // Linear (Band 1)
  43559. this.l1_1 = this.l1_1.scale(2.094395);
  43560. this.l10 = this.l10.scale(2.094395);
  43561. this.l11 = this.l11.scale(2.094395);
  43562. // Quadratic (Band 2)
  43563. this.l2_2 = this.l2_2.scale(0.785398);
  43564. this.l2_1 = this.l2_1.scale(0.785398);
  43565. this.l20 = this.l20.scale(0.785398);
  43566. this.l21 = this.l21.scale(0.785398);
  43567. this.lL22 = this.lL22.scale(0.785398);
  43568. };
  43569. /**
  43570. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43571. *
  43572. * ```
  43573. * L = (1/pi) * E * rho
  43574. * ```
  43575. *
  43576. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43577. */
  43578. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43579. this.scale(1.0 / Math.PI);
  43580. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43581. // (The pixel shader must apply albedo after texture fetches, etc).
  43582. };
  43583. /**
  43584. * Gets the spherical harmonics from polynomial
  43585. * @param polynomial the spherical polynomial
  43586. * @returns the spherical harmonics
  43587. */
  43588. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43589. var result = new SphericalHarmonics();
  43590. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43591. result.l1_1 = polynomial.y.scale(0.977204);
  43592. result.l10 = polynomial.z.scale(0.977204);
  43593. result.l11 = polynomial.x.scale(0.977204);
  43594. result.l2_2 = polynomial.xy.scale(1.16538);
  43595. result.l2_1 = polynomial.yz.scale(1.16538);
  43596. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43597. result.l21 = polynomial.zx.scale(1.16538);
  43598. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43599. result.scale(Math.PI);
  43600. return result;
  43601. };
  43602. /**
  43603. * Constructs a spherical harmonics from an array.
  43604. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43605. * @returns the spherical harmonics
  43606. */
  43607. SphericalHarmonics.FromArray = function (data) {
  43608. var sh = new SphericalHarmonics();
  43609. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43610. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43611. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43612. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43613. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43614. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43615. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43616. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43617. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43618. return sh;
  43619. };
  43620. return SphericalHarmonics;
  43621. }());
  43622. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43623. })(BABYLON || (BABYLON = {}));
  43624. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43625. var BABYLON;
  43626. (function (BABYLON) {
  43627. var FileFaceOrientation = /** @class */ (function () {
  43628. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43629. this.name = name;
  43630. this.worldAxisForNormal = worldAxisForNormal;
  43631. this.worldAxisForFileX = worldAxisForFileX;
  43632. this.worldAxisForFileY = worldAxisForFileY;
  43633. }
  43634. return FileFaceOrientation;
  43635. }());
  43636. ;
  43637. /**
  43638. * Helper class dealing with the extraction of spherical polynomial dataArray
  43639. * from a cube map.
  43640. */
  43641. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43642. function CubeMapToSphericalPolynomialTools() {
  43643. }
  43644. /**
  43645. * Converts a texture to the according Spherical Polynomial data.
  43646. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43647. *
  43648. * @param texture The texture to extract the information from.
  43649. * @return The Spherical Polynomial data.
  43650. */
  43651. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43652. if (!texture.isCube) {
  43653. // Only supports cube Textures currently.
  43654. return null;
  43655. }
  43656. var size = texture.getSize().width;
  43657. var right = texture.readPixels(0);
  43658. var left = texture.readPixels(1);
  43659. var up;
  43660. var down;
  43661. if (texture.isRenderTarget) {
  43662. up = texture.readPixels(3);
  43663. down = texture.readPixels(2);
  43664. }
  43665. else {
  43666. up = texture.readPixels(2);
  43667. down = texture.readPixels(3);
  43668. }
  43669. var front = texture.readPixels(4);
  43670. var back = texture.readPixels(5);
  43671. var gammaSpace = texture.gammaSpace;
  43672. // Always read as RGBA.
  43673. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43674. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43675. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43676. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43677. }
  43678. var cubeInfo = {
  43679. size: size,
  43680. right: right,
  43681. left: left,
  43682. up: up,
  43683. down: down,
  43684. front: front,
  43685. back: back,
  43686. format: format,
  43687. type: type,
  43688. gammaSpace: gammaSpace,
  43689. };
  43690. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43691. };
  43692. /**
  43693. * Converts a cubemap to the according Spherical Polynomial data.
  43694. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43695. *
  43696. * @param cubeInfo The Cube map to extract the information from.
  43697. * @return The Spherical Polynomial data.
  43698. */
  43699. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43700. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43701. var totalSolidAngle = 0.0;
  43702. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43703. var du = 2.0 / cubeInfo.size;
  43704. var dv = du;
  43705. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43706. var minUV = du * 0.5 - 1.0;
  43707. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43708. var fileFace = this.FileFaces[faceIndex];
  43709. var dataArray = cubeInfo[fileFace.name];
  43710. var v = minUV;
  43711. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43712. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43713. // Because SP is still linear, so summation is fine in that basis.
  43714. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43715. for (var y = 0; y < cubeInfo.size; y++) {
  43716. var u = minUV;
  43717. for (var x = 0; x < cubeInfo.size; x++) {
  43718. // World direction (not normalised)
  43719. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43720. worldDirection.normalize();
  43721. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43722. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43723. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43724. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43725. // Handle Integer types.
  43726. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43727. r /= 255;
  43728. g /= 255;
  43729. b /= 255;
  43730. }
  43731. // Handle Gamma space textures.
  43732. if (cubeInfo.gammaSpace) {
  43733. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43734. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43735. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43736. }
  43737. var color = new BABYLON.Color3(r, g, b);
  43738. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43739. totalSolidAngle += deltaSolidAngle;
  43740. u += du;
  43741. }
  43742. v += dv;
  43743. }
  43744. }
  43745. // Solid angle for entire sphere is 4*pi
  43746. var sphereSolidAngle = 4.0 * Math.PI;
  43747. // Adjust the solid angle to allow for how many faces we processed.
  43748. var facesProcessed = 6.0;
  43749. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43750. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43751. // This is needed because the numerical integration over the cube uses a
  43752. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43753. // and also to compensate for accumulative error due to float precision in the summation.
  43754. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43755. sphericalHarmonics.scale(correctionFactor);
  43756. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43757. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43758. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43759. };
  43760. CubeMapToSphericalPolynomialTools.FileFaces = [
  43761. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43762. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43763. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43764. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43765. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43766. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43767. ];
  43768. return CubeMapToSphericalPolynomialTools;
  43769. }());
  43770. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43771. })(BABYLON || (BABYLON = {}));
  43772. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43773. var BABYLON;
  43774. (function (BABYLON) {
  43775. /**
  43776. * Manages the defines for the PBR Material.
  43777. * @hiddenChildren
  43778. */
  43779. var PBRMaterialDefines = /** @class */ (function (_super) {
  43780. __extends(PBRMaterialDefines, _super);
  43781. /**
  43782. * Initializes the PBR Material defines.
  43783. */
  43784. function PBRMaterialDefines() {
  43785. var _this = _super.call(this) || this;
  43786. _this.PBR = true;
  43787. _this.MAINUV1 = false;
  43788. _this.MAINUV2 = false;
  43789. _this.UV1 = false;
  43790. _this.UV2 = false;
  43791. _this.ALBEDO = false;
  43792. _this.ALBEDODIRECTUV = 0;
  43793. _this.VERTEXCOLOR = false;
  43794. _this.AMBIENT = false;
  43795. _this.AMBIENTDIRECTUV = 0;
  43796. _this.AMBIENTINGRAYSCALE = false;
  43797. _this.OPACITY = false;
  43798. _this.VERTEXALPHA = false;
  43799. _this.OPACITYDIRECTUV = 0;
  43800. _this.OPACITYRGB = false;
  43801. _this.ALPHATEST = false;
  43802. _this.DEPTHPREPASS = false;
  43803. _this.ALPHABLEND = false;
  43804. _this.ALPHAFROMALBEDO = false;
  43805. _this.ALPHATESTVALUE = "0.5";
  43806. _this.SPECULAROVERALPHA = false;
  43807. _this.RADIANCEOVERALPHA = false;
  43808. _this.ALPHAFRESNEL = false;
  43809. _this.LINEARALPHAFRESNEL = false;
  43810. _this.PREMULTIPLYALPHA = false;
  43811. _this.EMISSIVE = false;
  43812. _this.EMISSIVEDIRECTUV = 0;
  43813. _this.REFLECTIVITY = false;
  43814. _this.REFLECTIVITYDIRECTUV = 0;
  43815. _this.SPECULARTERM = false;
  43816. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43817. _this.MICROSURFACEAUTOMATIC = false;
  43818. _this.LODBASEDMICROSFURACE = false;
  43819. _this.MICROSURFACEMAP = false;
  43820. _this.MICROSURFACEMAPDIRECTUV = 0;
  43821. _this.METALLICWORKFLOW = false;
  43822. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43823. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43824. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43825. _this.AOSTOREINMETALMAPRED = false;
  43826. _this.ENVIRONMENTBRDF = false;
  43827. _this.NORMAL = false;
  43828. _this.TANGENT = false;
  43829. _this.BUMP = false;
  43830. _this.BUMPDIRECTUV = 0;
  43831. _this.OBJECTSPACE_NORMALMAP = false;
  43832. _this.PARALLAX = false;
  43833. _this.PARALLAXOCCLUSION = false;
  43834. _this.NORMALXYSCALE = true;
  43835. _this.LIGHTMAP = false;
  43836. _this.LIGHTMAPDIRECTUV = 0;
  43837. _this.USELIGHTMAPASSHADOWMAP = false;
  43838. _this.GAMMALIGHTMAP = false;
  43839. _this.REFLECTION = false;
  43840. _this.REFLECTIONMAP_3D = false;
  43841. _this.REFLECTIONMAP_SPHERICAL = false;
  43842. _this.REFLECTIONMAP_PLANAR = false;
  43843. _this.REFLECTIONMAP_CUBIC = false;
  43844. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43845. _this.REFLECTIONMAP_PROJECTION = false;
  43846. _this.REFLECTIONMAP_SKYBOX = false;
  43847. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43848. _this.REFLECTIONMAP_EXPLICIT = false;
  43849. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43850. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43851. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43852. _this.INVERTCUBICMAP = false;
  43853. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43854. _this.USESPHERICALINVERTEX = false;
  43855. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43856. _this.LODINREFLECTIONALPHA = false;
  43857. _this.GAMMAREFLECTION = false;
  43858. _this.RGBDREFLECTION = false;
  43859. _this.RADIANCEOCCLUSION = false;
  43860. _this.HORIZONOCCLUSION = false;
  43861. _this.REFRACTION = false;
  43862. _this.REFRACTIONMAP_3D = false;
  43863. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43864. _this.LODINREFRACTIONALPHA = false;
  43865. _this.GAMMAREFRACTION = false;
  43866. _this.RGBDREFRACTION = false;
  43867. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43868. _this.INSTANCES = false;
  43869. _this.NUM_BONE_INFLUENCERS = 0;
  43870. _this.BonesPerMesh = 0;
  43871. _this.NONUNIFORMSCALING = false;
  43872. _this.MORPHTARGETS = false;
  43873. _this.MORPHTARGETS_NORMAL = false;
  43874. _this.MORPHTARGETS_TANGENT = false;
  43875. _this.NUM_MORPH_INFLUENCERS = 0;
  43876. _this.IMAGEPROCESSING = false;
  43877. _this.VIGNETTE = false;
  43878. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43879. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43880. _this.TONEMAPPING = false;
  43881. _this.TONEMAPPING_ACES = false;
  43882. _this.CONTRAST = false;
  43883. _this.COLORCURVES = false;
  43884. _this.COLORGRADING = false;
  43885. _this.COLORGRADING3D = false;
  43886. _this.SAMPLER3DGREENDEPTH = false;
  43887. _this.SAMPLER3DBGRMAP = false;
  43888. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43889. _this.EXPOSURE = false;
  43890. _this.USEPHYSICALLIGHTFALLOFF = false;
  43891. _this.USEGLTFLIGHTFALLOFF = false;
  43892. _this.TWOSIDEDLIGHTING = false;
  43893. _this.SHADOWFLOAT = false;
  43894. _this.CLIPPLANE = false;
  43895. _this.CLIPPLANE2 = false;
  43896. _this.CLIPPLANE3 = false;
  43897. _this.CLIPPLANE4 = false;
  43898. _this.POINTSIZE = false;
  43899. _this.FOG = false;
  43900. _this.LOGARITHMICDEPTH = false;
  43901. _this.FORCENORMALFORWARD = false;
  43902. _this.SPECULARAA = false;
  43903. _this.UNLIT = false;
  43904. _this.rebuild();
  43905. return _this;
  43906. }
  43907. /**
  43908. * Resets the PBR Material defines.
  43909. */
  43910. PBRMaterialDefines.prototype.reset = function () {
  43911. _super.prototype.reset.call(this);
  43912. this.ALPHATESTVALUE = "0.5";
  43913. this.PBR = true;
  43914. };
  43915. return PBRMaterialDefines;
  43916. }(BABYLON.MaterialDefines));
  43917. /**
  43918. * The Physically based material base class of BJS.
  43919. *
  43920. * This offers the main features of a standard PBR material.
  43921. * For more information, please refer to the documentation :
  43922. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43923. */
  43924. var PBRBaseMaterial = /** @class */ (function (_super) {
  43925. __extends(PBRBaseMaterial, _super);
  43926. /**
  43927. * Instantiates a new PBRMaterial instance.
  43928. *
  43929. * @param name The material name
  43930. * @param scene The scene the material will be use in.
  43931. */
  43932. function PBRBaseMaterial(name, scene) {
  43933. var _this = _super.call(this, name, scene) || this;
  43934. /**
  43935. * Intensity of the direct lights e.g. the four lights available in your scene.
  43936. * This impacts both the direct diffuse and specular highlights.
  43937. */
  43938. _this._directIntensity = 1.0;
  43939. /**
  43940. * Intensity of the emissive part of the material.
  43941. * This helps controlling the emissive effect without modifying the emissive color.
  43942. */
  43943. _this._emissiveIntensity = 1.0;
  43944. /**
  43945. * Intensity of the environment e.g. how much the environment will light the object
  43946. * either through harmonics for rough material or through the refelction for shiny ones.
  43947. */
  43948. _this._environmentIntensity = 1.0;
  43949. /**
  43950. * This is a special control allowing the reduction of the specular highlights coming from the
  43951. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43952. */
  43953. _this._specularIntensity = 1.0;
  43954. /**
  43955. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43956. */
  43957. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43958. /**
  43959. * Debug Control allowing disabling the bump map on this material.
  43960. */
  43961. _this._disableBumpMap = false;
  43962. /**
  43963. * AKA Occlusion Texture Intensity in other nomenclature.
  43964. */
  43965. _this._ambientTextureStrength = 1.0;
  43966. /**
  43967. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43968. * 1 means it completely occludes it
  43969. * 0 mean it has no impact
  43970. */
  43971. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43972. /**
  43973. * The color of a material in ambient lighting.
  43974. */
  43975. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43976. /**
  43977. * AKA Diffuse Color in other nomenclature.
  43978. */
  43979. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43980. /**
  43981. * AKA Specular Color in other nomenclature.
  43982. */
  43983. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43984. /**
  43985. * The color applied when light is reflected from a material.
  43986. */
  43987. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43988. /**
  43989. * The color applied when light is emitted from a material.
  43990. */
  43991. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43992. /**
  43993. * AKA Glossiness in other nomenclature.
  43994. */
  43995. _this._microSurface = 0.9;
  43996. /**
  43997. * source material index of refraction (IOR)' / 'destination material IOR.
  43998. */
  43999. _this._indexOfRefraction = 0.66;
  44000. /**
  44001. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44002. */
  44003. _this._invertRefractionY = false;
  44004. /**
  44005. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44006. * Materials half opaque for instance using refraction could benefit from this control.
  44007. */
  44008. _this._linkRefractionWithTransparency = false;
  44009. /**
  44010. * Specifies that the material will use the light map as a show map.
  44011. */
  44012. _this._useLightmapAsShadowmap = false;
  44013. /**
  44014. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44015. * makes the reflect vector face the model (under horizon).
  44016. */
  44017. _this._useHorizonOcclusion = true;
  44018. /**
  44019. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44020. * too much the area relying on ambient texture to define their ambient occlusion.
  44021. */
  44022. _this._useRadianceOcclusion = true;
  44023. /**
  44024. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44025. */
  44026. _this._useAlphaFromAlbedoTexture = false;
  44027. /**
  44028. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44029. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44030. */
  44031. _this._useSpecularOverAlpha = true;
  44032. /**
  44033. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44034. */
  44035. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44036. /**
  44037. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44038. */
  44039. _this._useRoughnessFromMetallicTextureAlpha = true;
  44040. /**
  44041. * Specifies if the metallic texture contains the roughness information in its green channel.
  44042. */
  44043. _this._useRoughnessFromMetallicTextureGreen = false;
  44044. /**
  44045. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44046. */
  44047. _this._useMetallnessFromMetallicTextureBlue = false;
  44048. /**
  44049. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44050. */
  44051. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44052. /**
  44053. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44054. */
  44055. _this._useAmbientInGrayScale = false;
  44056. /**
  44057. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44058. * The material will try to infer what glossiness each pixel should be.
  44059. */
  44060. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44061. /**
  44062. * Defines the falloff type used in this material.
  44063. * It by default is Physical.
  44064. */
  44065. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  44066. /**
  44067. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44068. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44069. */
  44070. _this._useRadianceOverAlpha = true;
  44071. /**
  44072. * Allows using an object space normal map (instead of tangent space).
  44073. */
  44074. _this._useObjectSpaceNormalMap = false;
  44075. /**
  44076. * Allows using the bump map in parallax mode.
  44077. */
  44078. _this._useParallax = false;
  44079. /**
  44080. * Allows using the bump map in parallax occlusion mode.
  44081. */
  44082. _this._useParallaxOcclusion = false;
  44083. /**
  44084. * Controls the scale bias of the parallax mode.
  44085. */
  44086. _this._parallaxScaleBias = 0.05;
  44087. /**
  44088. * If sets to true, disables all the lights affecting the material.
  44089. */
  44090. _this._disableLighting = false;
  44091. /**
  44092. * Number of Simultaneous lights allowed on the material.
  44093. */
  44094. _this._maxSimultaneousLights = 4;
  44095. /**
  44096. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44097. */
  44098. _this._invertNormalMapX = false;
  44099. /**
  44100. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44101. */
  44102. _this._invertNormalMapY = false;
  44103. /**
  44104. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44105. */
  44106. _this._twoSidedLighting = false;
  44107. /**
  44108. * Defines the alpha limits in alpha test mode.
  44109. */
  44110. _this._alphaCutOff = 0.4;
  44111. /**
  44112. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44113. */
  44114. _this._forceAlphaTest = false;
  44115. /**
  44116. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44117. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44118. */
  44119. _this._useAlphaFresnel = false;
  44120. /**
  44121. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44122. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44123. */
  44124. _this._useLinearAlphaFresnel = false;
  44125. /**
  44126. * The transparency mode of the material.
  44127. */
  44128. _this._transparencyMode = null;
  44129. /**
  44130. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44131. * from cos thetav and roughness:
  44132. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44133. */
  44134. _this._environmentBRDFTexture = null;
  44135. /**
  44136. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44137. */
  44138. _this._forceIrradianceInFragment = false;
  44139. /**
  44140. * Force normal to face away from face.
  44141. */
  44142. _this._forceNormalForward = false;
  44143. /**
  44144. * Enables specular anti aliasing in the PBR shader.
  44145. * It will both interacts on the Geometry for analytical and IBL lighting.
  44146. * It also prefilter the roughness map based on the bump values.
  44147. */
  44148. _this._enableSpecularAntiAliasing = false;
  44149. /**
  44150. * Stores the available render targets.
  44151. */
  44152. _this._renderTargets = new BABYLON.SmartArray(16);
  44153. /**
  44154. * Sets the global ambient color for the material used in lighting calculations.
  44155. */
  44156. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44157. /**
  44158. * If set to true, no lighting calculations will be applied.
  44159. */
  44160. _this._unlit = false;
  44161. // Setup the default processing configuration to the scene.
  44162. _this._attachImageProcessingConfiguration(null);
  44163. _this.getRenderTargetTextures = function () {
  44164. _this._renderTargets.reset();
  44165. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44166. _this._renderTargets.push(_this._reflectionTexture);
  44167. }
  44168. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44169. _this._renderTargets.push(_this._refractionTexture);
  44170. }
  44171. return _this._renderTargets;
  44172. };
  44173. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44174. return _this;
  44175. }
  44176. /**
  44177. * Attaches a new image processing configuration to the PBR Material.
  44178. * @param configuration
  44179. */
  44180. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44181. var _this = this;
  44182. if (configuration === this._imageProcessingConfiguration) {
  44183. return;
  44184. }
  44185. // Detaches observer.
  44186. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44187. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44188. }
  44189. // Pick the scene configuration if needed.
  44190. if (!configuration) {
  44191. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44192. }
  44193. else {
  44194. this._imageProcessingConfiguration = configuration;
  44195. }
  44196. // Attaches observer.
  44197. if (this._imageProcessingConfiguration) {
  44198. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44199. _this._markAllSubMeshesAsImageProcessingDirty();
  44200. });
  44201. }
  44202. };
  44203. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  44204. /**
  44205. * Gets a boolean indicating that current material needs to register RTT
  44206. */
  44207. get: function () {
  44208. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44209. return true;
  44210. }
  44211. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44212. return true;
  44213. }
  44214. return false;
  44215. },
  44216. enumerable: true,
  44217. configurable: true
  44218. });
  44219. /**
  44220. * Gets the name of the material class.
  44221. */
  44222. PBRBaseMaterial.prototype.getClassName = function () {
  44223. return "PBRBaseMaterial";
  44224. };
  44225. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44226. /**
  44227. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44228. */
  44229. get: function () {
  44230. return this._useLogarithmicDepth;
  44231. },
  44232. /**
  44233. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44234. */
  44235. set: function (value) {
  44236. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44237. },
  44238. enumerable: true,
  44239. configurable: true
  44240. });
  44241. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44242. /**
  44243. * Gets the current transparency mode.
  44244. */
  44245. get: function () {
  44246. return this._transparencyMode;
  44247. },
  44248. /**
  44249. * Sets the transparency mode of the material.
  44250. *
  44251. * | Value | Type | Description |
  44252. * | ----- | ----------------------------------- | ----------- |
  44253. * | 0 | OPAQUE | |
  44254. * | 1 | ALPHATEST | |
  44255. * | 2 | ALPHABLEND | |
  44256. * | 3 | ALPHATESTANDBLEND | |
  44257. *
  44258. */
  44259. set: function (value) {
  44260. if (this._transparencyMode === value) {
  44261. return;
  44262. }
  44263. this._transparencyMode = value;
  44264. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44265. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44266. },
  44267. enumerable: true,
  44268. configurable: true
  44269. });
  44270. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44271. /**
  44272. * Returns true if alpha blending should be disabled.
  44273. */
  44274. get: function () {
  44275. return (this._linkRefractionWithTransparency ||
  44276. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44277. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44278. },
  44279. enumerable: true,
  44280. configurable: true
  44281. });
  44282. /**
  44283. * Specifies whether or not this material should be rendered in alpha blend mode.
  44284. */
  44285. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44286. if (this._disableAlphaBlending) {
  44287. return false;
  44288. }
  44289. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44290. };
  44291. /**
  44292. * Specifies if the mesh will require alpha blending.
  44293. * @param mesh - BJS mesh.
  44294. */
  44295. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44296. if (this._disableAlphaBlending) {
  44297. return false;
  44298. }
  44299. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44300. };
  44301. /**
  44302. * Specifies whether or not this material should be rendered in alpha test mode.
  44303. */
  44304. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44305. if (this._forceAlphaTest) {
  44306. return true;
  44307. }
  44308. if (this._linkRefractionWithTransparency) {
  44309. return false;
  44310. }
  44311. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44312. };
  44313. /**
  44314. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44315. */
  44316. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44317. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44318. };
  44319. /**
  44320. * Gets the texture used for the alpha test.
  44321. */
  44322. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44323. return this._albedoTexture;
  44324. };
  44325. /**
  44326. * Specifies that the submesh is ready to be used.
  44327. * @param mesh - BJS mesh.
  44328. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44329. * @param useInstances - Specifies that instances should be used.
  44330. * @returns - boolean indicating that the submesh is ready or not.
  44331. */
  44332. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44333. if (subMesh.effect && this.isFrozen) {
  44334. if (this._wasPreviouslyReady) {
  44335. return true;
  44336. }
  44337. }
  44338. if (!subMesh._materialDefines) {
  44339. subMesh._materialDefines = new PBRMaterialDefines();
  44340. }
  44341. var defines = subMesh._materialDefines;
  44342. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44343. if (defines._renderId === this.getScene().getRenderId()) {
  44344. return true;
  44345. }
  44346. }
  44347. var scene = this.getScene();
  44348. var engine = scene.getEngine();
  44349. if (defines._areTexturesDirty) {
  44350. if (scene.texturesEnabled) {
  44351. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44352. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44353. return false;
  44354. }
  44355. }
  44356. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44357. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44358. return false;
  44359. }
  44360. }
  44361. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44362. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44363. return false;
  44364. }
  44365. }
  44366. var reflectionTexture = this._getReflectionTexture();
  44367. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44368. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44369. return false;
  44370. }
  44371. }
  44372. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44373. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44374. return false;
  44375. }
  44376. }
  44377. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44378. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44379. return false;
  44380. }
  44381. }
  44382. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44383. if (this._metallicTexture) {
  44384. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44385. return false;
  44386. }
  44387. }
  44388. else if (this._reflectivityTexture) {
  44389. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44390. return false;
  44391. }
  44392. }
  44393. if (this._microSurfaceTexture) {
  44394. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44395. return false;
  44396. }
  44397. }
  44398. }
  44399. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44400. // Bump texture cannot be not blocking.
  44401. if (!this._bumpTexture.isReady()) {
  44402. return false;
  44403. }
  44404. }
  44405. var refractionTexture = this._getRefractionTexture();
  44406. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44407. if (!refractionTexture.isReadyOrNotBlocking()) {
  44408. return false;
  44409. }
  44410. }
  44411. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44412. // This is blocking.
  44413. if (!this._environmentBRDFTexture.isReady()) {
  44414. return false;
  44415. }
  44416. }
  44417. }
  44418. }
  44419. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44420. if (!this._imageProcessingConfiguration.isReady()) {
  44421. return false;
  44422. }
  44423. }
  44424. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44425. mesh.createNormals(true);
  44426. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44427. }
  44428. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44429. if (effect) {
  44430. scene.resetCachedMaterial();
  44431. subMesh.setEffect(effect, defines);
  44432. this.buildUniformLayout();
  44433. }
  44434. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44435. return false;
  44436. }
  44437. defines._renderId = scene.getRenderId();
  44438. this._wasPreviouslyReady = true;
  44439. return true;
  44440. };
  44441. /**
  44442. * Specifies if the material uses metallic roughness workflow.
  44443. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44444. */
  44445. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44446. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44447. return true;
  44448. }
  44449. return false;
  44450. };
  44451. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44452. if (onCompiled === void 0) { onCompiled = null; }
  44453. if (onError === void 0) { onError = null; }
  44454. if (useInstances === void 0) { useInstances = null; }
  44455. if (useClipPlane === void 0) { useClipPlane = null; }
  44456. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44457. if (!defines.isDirty) {
  44458. return null;
  44459. }
  44460. defines.markAsProcessed();
  44461. var scene = this.getScene();
  44462. var engine = scene.getEngine();
  44463. // Fallbacks
  44464. var fallbacks = new BABYLON.EffectFallbacks();
  44465. var fallbackRank = 0;
  44466. if (defines.USESPHERICALINVERTEX) {
  44467. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44468. }
  44469. if (defines.FOG) {
  44470. fallbacks.addFallback(fallbackRank, "FOG");
  44471. }
  44472. if (defines.SPECULARAA) {
  44473. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44474. }
  44475. if (defines.POINTSIZE) {
  44476. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44477. }
  44478. if (defines.LOGARITHMICDEPTH) {
  44479. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44480. }
  44481. if (defines.PARALLAX) {
  44482. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44483. }
  44484. if (defines.PARALLAXOCCLUSION) {
  44485. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44486. }
  44487. if (defines.ENVIRONMENTBRDF) {
  44488. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44489. }
  44490. if (defines.TANGENT) {
  44491. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44492. }
  44493. if (defines.BUMP) {
  44494. fallbacks.addFallback(fallbackRank++, "BUMP");
  44495. }
  44496. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44497. if (defines.SPECULARTERM) {
  44498. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44499. }
  44500. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44501. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44502. }
  44503. if (defines.LIGHTMAP) {
  44504. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44505. }
  44506. if (defines.NORMAL) {
  44507. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44508. }
  44509. if (defines.AMBIENT) {
  44510. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44511. }
  44512. if (defines.EMISSIVE) {
  44513. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44514. }
  44515. if (defines.VERTEXCOLOR) {
  44516. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44517. }
  44518. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44519. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44520. }
  44521. if (defines.MORPHTARGETS) {
  44522. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44523. }
  44524. //Attributes
  44525. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44526. if (defines.NORMAL) {
  44527. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44528. }
  44529. if (defines.TANGENT) {
  44530. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44531. }
  44532. if (defines.UV1) {
  44533. attribs.push(BABYLON.VertexBuffer.UVKind);
  44534. }
  44535. if (defines.UV2) {
  44536. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44537. }
  44538. if (defines.VERTEXCOLOR) {
  44539. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44540. }
  44541. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44542. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44543. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44544. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44545. "vFogInfos", "vFogColor", "pointSize",
  44546. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44547. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44548. "mBones",
  44549. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44550. "vLightingIntensity",
  44551. "logarithmicDepthConstant",
  44552. "vSphericalX", "vSphericalY", "vSphericalZ",
  44553. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44554. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44555. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44556. "vTangentSpaceParams"
  44557. ];
  44558. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44559. "bumpSampler", "lightmapSampler", "opacitySampler",
  44560. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44561. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44562. "microSurfaceSampler", "environmentBrdfSampler"];
  44563. var uniformBuffers = ["Material", "Scene"];
  44564. if (BABYLON.ImageProcessingConfiguration) {
  44565. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44566. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44567. }
  44568. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44569. uniformsNames: uniforms,
  44570. uniformBuffersNames: uniformBuffers,
  44571. samplers: samplers,
  44572. defines: defines,
  44573. maxSimultaneousLights: this._maxSimultaneousLights
  44574. });
  44575. var join = defines.toString();
  44576. return engine.createEffect("pbr", {
  44577. attributes: attribs,
  44578. uniformsNames: uniforms,
  44579. uniformBuffersNames: uniformBuffers,
  44580. samplers: samplers,
  44581. defines: join,
  44582. fallbacks: fallbacks,
  44583. onCompiled: onCompiled,
  44584. onError: onError,
  44585. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44586. }, engine);
  44587. };
  44588. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44589. if (useInstances === void 0) { useInstances = null; }
  44590. if (useClipPlane === void 0) { useClipPlane = null; }
  44591. var scene = this.getScene();
  44592. var engine = scene.getEngine();
  44593. // Lights
  44594. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44595. defines._needNormals = true;
  44596. // Textures
  44597. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44598. if (defines._areTexturesDirty) {
  44599. defines._needUVs = false;
  44600. if (scene.texturesEnabled) {
  44601. if (scene.getEngine().getCaps().textureLOD) {
  44602. defines.LODBASEDMICROSFURACE = true;
  44603. }
  44604. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44605. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44606. }
  44607. else {
  44608. defines.ALBEDO = false;
  44609. }
  44610. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44611. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44612. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44613. }
  44614. else {
  44615. defines.AMBIENT = false;
  44616. }
  44617. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44618. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44619. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44620. }
  44621. else {
  44622. defines.OPACITY = false;
  44623. }
  44624. var reflectionTexture = this._getReflectionTexture();
  44625. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44626. defines.REFLECTION = true;
  44627. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44628. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44629. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44630. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44631. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44632. defines.INVERTCUBICMAP = true;
  44633. }
  44634. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44635. switch (reflectionTexture.coordinatesMode) {
  44636. case BABYLON.Texture.EXPLICIT_MODE:
  44637. defines.REFLECTIONMAP_EXPLICIT = true;
  44638. break;
  44639. case BABYLON.Texture.PLANAR_MODE:
  44640. defines.REFLECTIONMAP_PLANAR = true;
  44641. break;
  44642. case BABYLON.Texture.PROJECTION_MODE:
  44643. defines.REFLECTIONMAP_PROJECTION = true;
  44644. break;
  44645. case BABYLON.Texture.SKYBOX_MODE:
  44646. defines.REFLECTIONMAP_SKYBOX = true;
  44647. break;
  44648. case BABYLON.Texture.SPHERICAL_MODE:
  44649. defines.REFLECTIONMAP_SPHERICAL = true;
  44650. break;
  44651. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44652. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44653. break;
  44654. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44655. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44656. break;
  44657. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44658. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44659. break;
  44660. case BABYLON.Texture.CUBIC_MODE:
  44661. case BABYLON.Texture.INVCUBIC_MODE:
  44662. default:
  44663. defines.REFLECTIONMAP_CUBIC = true;
  44664. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44665. break;
  44666. }
  44667. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44668. if (reflectionTexture.sphericalPolynomial) {
  44669. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44670. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44671. defines.USESPHERICALINVERTEX = false;
  44672. }
  44673. else {
  44674. defines.USESPHERICALINVERTEX = true;
  44675. }
  44676. }
  44677. }
  44678. else {
  44679. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  44680. }
  44681. }
  44682. else {
  44683. defines.REFLECTION = false;
  44684. defines.REFLECTIONMAP_3D = false;
  44685. defines.REFLECTIONMAP_SPHERICAL = false;
  44686. defines.REFLECTIONMAP_PLANAR = false;
  44687. defines.REFLECTIONMAP_CUBIC = false;
  44688. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44689. defines.REFLECTIONMAP_PROJECTION = false;
  44690. defines.REFLECTIONMAP_SKYBOX = false;
  44691. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44692. defines.REFLECTIONMAP_EXPLICIT = false;
  44693. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44694. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44695. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44696. defines.INVERTCUBICMAP = false;
  44697. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44698. defines.USESPHERICALINVERTEX = false;
  44699. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44700. defines.LODINREFLECTIONALPHA = false;
  44701. defines.GAMMAREFLECTION = false;
  44702. defines.RGBDREFLECTION = false;
  44703. }
  44704. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44705. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44706. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44707. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44708. }
  44709. else {
  44710. defines.LIGHTMAP = false;
  44711. }
  44712. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44713. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44714. }
  44715. else {
  44716. defines.EMISSIVE = false;
  44717. }
  44718. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44719. if (this._metallicTexture) {
  44720. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44721. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44722. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44723. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44724. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44725. }
  44726. else if (this._reflectivityTexture) {
  44727. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44728. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44729. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44730. }
  44731. else {
  44732. defines.REFLECTIVITY = false;
  44733. }
  44734. if (this._microSurfaceTexture) {
  44735. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44736. }
  44737. else {
  44738. defines.MICROSURFACEMAP = false;
  44739. }
  44740. }
  44741. else {
  44742. defines.REFLECTIVITY = false;
  44743. defines.MICROSURFACEMAP = false;
  44744. }
  44745. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44746. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44747. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44748. defines.PARALLAX = true;
  44749. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44750. }
  44751. else {
  44752. defines.PARALLAX = false;
  44753. }
  44754. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44755. }
  44756. else {
  44757. defines.BUMP = false;
  44758. }
  44759. var refractionTexture = this._getRefractionTexture();
  44760. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44761. defines.REFRACTION = true;
  44762. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44763. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44764. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44765. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44766. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44767. if (this._linkRefractionWithTransparency) {
  44768. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44769. }
  44770. }
  44771. else {
  44772. defines.REFRACTION = false;
  44773. }
  44774. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44775. defines.ENVIRONMENTBRDF = true;
  44776. }
  44777. else {
  44778. defines.ENVIRONMENTBRDF = false;
  44779. }
  44780. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44781. defines.ALPHAFROMALBEDO = true;
  44782. }
  44783. else {
  44784. defines.ALPHAFROMALBEDO = false;
  44785. }
  44786. }
  44787. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44788. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44789. defines.USEPHYSICALLIGHTFALLOFF = false;
  44790. defines.USEGLTFLIGHTFALLOFF = false;
  44791. }
  44792. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44793. defines.USEPHYSICALLIGHTFALLOFF = false;
  44794. defines.USEGLTFLIGHTFALLOFF = true;
  44795. }
  44796. else {
  44797. defines.USEPHYSICALLIGHTFALLOFF = true;
  44798. defines.USEGLTFLIGHTFALLOFF = false;
  44799. }
  44800. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44801. if (!this.backFaceCulling && this._twoSidedLighting) {
  44802. defines.TWOSIDEDLIGHTING = true;
  44803. }
  44804. else {
  44805. defines.TWOSIDEDLIGHTING = false;
  44806. }
  44807. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44808. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44809. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44810. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44811. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44812. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44813. }
  44814. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44815. this._imageProcessingConfiguration.prepareDefines(defines);
  44816. }
  44817. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44818. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44819. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44820. // Misc.
  44821. if (defines._areMiscDirty) {
  44822. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44823. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44824. }
  44825. // Values that need to be evaluated on every frame
  44826. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44827. // Attribs
  44828. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44829. };
  44830. /**
  44831. * Force shader compilation
  44832. */
  44833. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44834. var _this = this;
  44835. var localOptions = __assign({ clipPlane: false }, options);
  44836. var defines = new PBRMaterialDefines();
  44837. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44838. if (effect.isReady()) {
  44839. if (onCompiled) {
  44840. onCompiled(this);
  44841. }
  44842. }
  44843. else {
  44844. effect.onCompileObservable.add(function () {
  44845. if (onCompiled) {
  44846. onCompiled(_this);
  44847. }
  44848. });
  44849. }
  44850. };
  44851. /**
  44852. * Initializes the uniform buffer layout for the shader.
  44853. */
  44854. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44855. // Order is important !
  44856. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44857. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44858. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44859. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44860. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44861. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44862. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44863. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44864. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44865. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44866. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44867. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44868. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44869. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44870. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44871. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44872. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44873. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44874. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44875. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44876. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44877. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44878. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44879. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44880. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44881. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44882. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44883. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44884. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44885. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44886. this._uniformBuffer.addUniform("pointSize", 1);
  44887. this._uniformBuffer.create();
  44888. };
  44889. /**
  44890. * Unbinds the textures.
  44891. */
  44892. PBRBaseMaterial.prototype.unbind = function () {
  44893. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44894. this._uniformBuffer.setTexture("reflectionSampler", null);
  44895. }
  44896. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44897. this._uniformBuffer.setTexture("refractionSampler", null);
  44898. }
  44899. _super.prototype.unbind.call(this);
  44900. };
  44901. /**
  44902. * Binds the submesh data.
  44903. * @param world - The world matrix.
  44904. * @param mesh - The BJS mesh.
  44905. * @param subMesh - A submesh of the BJS mesh.
  44906. */
  44907. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44908. var scene = this.getScene();
  44909. var defines = subMesh._materialDefines;
  44910. if (!defines) {
  44911. return;
  44912. }
  44913. var effect = subMesh.effect;
  44914. if (!effect) {
  44915. return;
  44916. }
  44917. this._activeEffect = effect;
  44918. // Matrices
  44919. this.bindOnlyWorldMatrix(world);
  44920. // Normal Matrix
  44921. if (defines.OBJECTSPACE_NORMALMAP) {
  44922. world.toNormalMatrix(this._normalMatrix);
  44923. this.bindOnlyNormalMatrix(this._normalMatrix);
  44924. }
  44925. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44926. // Bones
  44927. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44928. var reflectionTexture = null;
  44929. if (mustRebind) {
  44930. this._uniformBuffer.bindToEffect(effect, "Material");
  44931. this.bindViewProjection(effect);
  44932. reflectionTexture = this._getReflectionTexture();
  44933. var refractionTexture = this._getRefractionTexture();
  44934. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44935. // Texture uniforms
  44936. if (scene.texturesEnabled) {
  44937. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44938. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44939. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44940. }
  44941. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44942. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44943. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44944. }
  44945. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44946. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44947. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44948. }
  44949. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44950. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44951. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44952. if (reflectionTexture.boundingBoxSize) {
  44953. var cubeTexture = reflectionTexture;
  44954. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44955. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44956. }
  44957. var polynomials = reflectionTexture.sphericalPolynomial;
  44958. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44959. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44960. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44961. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44962. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44963. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44964. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44965. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44966. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44967. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44968. }
  44969. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44970. }
  44971. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44972. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44973. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44974. }
  44975. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44976. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44977. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44978. }
  44979. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44980. if (this._metallicTexture) {
  44981. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44982. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44983. }
  44984. else if (this._reflectivityTexture) {
  44985. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44986. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44987. }
  44988. if (this._microSurfaceTexture) {
  44989. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44990. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44991. }
  44992. }
  44993. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44994. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44995. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44996. if (scene._mirroredCameraPosition) {
  44997. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44998. }
  44999. else {
  45000. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45001. }
  45002. }
  45003. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45004. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45005. var depth = 1.0;
  45006. if (!refractionTexture.isCube) {
  45007. if (refractionTexture.depth) {
  45008. depth = refractionTexture.depth;
  45009. }
  45010. }
  45011. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45012. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45013. }
  45014. }
  45015. // Point size
  45016. if (this.pointsCloud) {
  45017. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45018. }
  45019. // Colors
  45020. if (defines.METALLICWORKFLOW) {
  45021. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45022. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45023. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45024. }
  45025. else {
  45026. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45027. }
  45028. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45029. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45030. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45031. // Misc
  45032. this._lightingInfos.x = this._directIntensity;
  45033. this._lightingInfos.y = this._emissiveIntensity;
  45034. this._lightingInfos.z = this._environmentIntensity;
  45035. this._lightingInfos.w = this._specularIntensity;
  45036. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45037. }
  45038. // Textures
  45039. if (scene.texturesEnabled) {
  45040. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45041. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45042. }
  45043. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45044. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45045. }
  45046. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45047. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45048. }
  45049. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45050. if (defines.LODBASEDMICROSFURACE) {
  45051. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45052. }
  45053. else {
  45054. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45055. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45056. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45057. }
  45058. }
  45059. if (defines.ENVIRONMENTBRDF) {
  45060. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45061. }
  45062. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45063. if (defines.LODBASEDMICROSFURACE) {
  45064. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45065. }
  45066. else {
  45067. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45068. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45069. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45070. }
  45071. }
  45072. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45073. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45074. }
  45075. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45076. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45077. }
  45078. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45079. if (this._metallicTexture) {
  45080. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45081. }
  45082. else if (this._reflectivityTexture) {
  45083. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45084. }
  45085. if (this._microSurfaceTexture) {
  45086. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45087. }
  45088. }
  45089. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45090. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45091. }
  45092. }
  45093. // Clip plane
  45094. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45095. // Colors
  45096. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45097. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45098. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45099. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45100. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45101. }
  45102. if (mustRebind || !this.isFrozen) {
  45103. // Lights
  45104. if (scene.lightsEnabled && !this._disableLighting) {
  45105. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  45106. }
  45107. // View
  45108. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45109. this.bindView(effect);
  45110. }
  45111. // Fog
  45112. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  45113. // Morph targets
  45114. if (defines.NUM_MORPH_INFLUENCERS) {
  45115. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45116. }
  45117. // image processing
  45118. this._imageProcessingConfiguration.bind(this._activeEffect);
  45119. // Log. depth
  45120. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45121. }
  45122. this._uniformBuffer.update();
  45123. this._afterBind(mesh, this._activeEffect);
  45124. };
  45125. /**
  45126. * Returns the animatable textures.
  45127. * @returns - Array of animatable textures.
  45128. */
  45129. PBRBaseMaterial.prototype.getAnimatables = function () {
  45130. var results = [];
  45131. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45132. results.push(this._albedoTexture);
  45133. }
  45134. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45135. results.push(this._ambientTexture);
  45136. }
  45137. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45138. results.push(this._opacityTexture);
  45139. }
  45140. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45141. results.push(this._reflectionTexture);
  45142. }
  45143. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45144. results.push(this._emissiveTexture);
  45145. }
  45146. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45147. results.push(this._metallicTexture);
  45148. }
  45149. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45150. results.push(this._reflectivityTexture);
  45151. }
  45152. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45153. results.push(this._bumpTexture);
  45154. }
  45155. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45156. results.push(this._lightmapTexture);
  45157. }
  45158. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45159. results.push(this._refractionTexture);
  45160. }
  45161. return results;
  45162. };
  45163. /**
  45164. * Returns the texture used for reflections.
  45165. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45166. */
  45167. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45168. if (this._reflectionTexture) {
  45169. return this._reflectionTexture;
  45170. }
  45171. return this.getScene().environmentTexture;
  45172. };
  45173. /**
  45174. * Returns the texture used for refraction or null if none is used.
  45175. * @returns - Refection texture if present. If no refraction texture and refraction
  45176. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45177. */
  45178. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45179. if (this._refractionTexture) {
  45180. return this._refractionTexture;
  45181. }
  45182. if (this._linkRefractionWithTransparency) {
  45183. return this.getScene().environmentTexture;
  45184. }
  45185. return null;
  45186. };
  45187. /**
  45188. * Disposes the resources of the material.
  45189. * @param forceDisposeEffect - Forces the disposal of effects.
  45190. * @param forceDisposeTextures - Forces the disposal of all textures.
  45191. */
  45192. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45193. if (forceDisposeTextures) {
  45194. if (this._albedoTexture) {
  45195. this._albedoTexture.dispose();
  45196. }
  45197. if (this._ambientTexture) {
  45198. this._ambientTexture.dispose();
  45199. }
  45200. if (this._opacityTexture) {
  45201. this._opacityTexture.dispose();
  45202. }
  45203. if (this._reflectionTexture) {
  45204. this._reflectionTexture.dispose();
  45205. }
  45206. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45207. this._environmentBRDFTexture.dispose();
  45208. }
  45209. if (this._emissiveTexture) {
  45210. this._emissiveTexture.dispose();
  45211. }
  45212. if (this._metallicTexture) {
  45213. this._metallicTexture.dispose();
  45214. }
  45215. if (this._reflectivityTexture) {
  45216. this._reflectivityTexture.dispose();
  45217. }
  45218. if (this._bumpTexture) {
  45219. this._bumpTexture.dispose();
  45220. }
  45221. if (this._lightmapTexture) {
  45222. this._lightmapTexture.dispose();
  45223. }
  45224. if (this._refractionTexture) {
  45225. this._refractionTexture.dispose();
  45226. }
  45227. }
  45228. this._renderTargets.dispose();
  45229. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45230. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45231. }
  45232. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45233. };
  45234. /**
  45235. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  45236. */
  45237. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  45238. /**
  45239. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  45240. * to enhance interoperability with other engines.
  45241. */
  45242. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  45243. /**
  45244. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  45245. * to enhance interoperability with other materials.
  45246. */
  45247. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  45248. /**
  45249. * Stores the reflectivity values based on metallic roughness workflow.
  45250. */
  45251. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45252. __decorate([
  45253. BABYLON.serializeAsImageProcessingConfiguration()
  45254. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45255. __decorate([
  45256. BABYLON.serialize()
  45257. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45258. __decorate([
  45259. BABYLON.serialize()
  45260. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45261. return PBRBaseMaterial;
  45262. }(BABYLON.PushMaterial));
  45263. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45264. })(BABYLON || (BABYLON = {}));
  45265. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45266. var BABYLON;
  45267. (function (BABYLON) {
  45268. /**
  45269. * The Physically based simple base material of BJS.
  45270. *
  45271. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45272. * It is used as the base class for both the specGloss and metalRough conventions.
  45273. */
  45274. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45275. __extends(PBRBaseSimpleMaterial, _super);
  45276. /**
  45277. * Instantiates a new PBRMaterial instance.
  45278. *
  45279. * @param name The material name
  45280. * @param scene The scene the material will be use in.
  45281. */
  45282. function PBRBaseSimpleMaterial(name, scene) {
  45283. var _this = _super.call(this, name, scene) || this;
  45284. /**
  45285. * Number of Simultaneous lights allowed on the material.
  45286. */
  45287. _this.maxSimultaneousLights = 4;
  45288. /**
  45289. * If sets to true, disables all the lights affecting the material.
  45290. */
  45291. _this.disableLighting = false;
  45292. /**
  45293. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45294. */
  45295. _this.invertNormalMapX = false;
  45296. /**
  45297. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45298. */
  45299. _this.invertNormalMapY = false;
  45300. /**
  45301. * Emissivie color used to self-illuminate the model.
  45302. */
  45303. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45304. /**
  45305. * Occlusion Channel Strenght.
  45306. */
  45307. _this.occlusionStrength = 1.0;
  45308. _this.useLightmapAsShadowmap = false;
  45309. _this._useAlphaFromAlbedoTexture = true;
  45310. _this._useAmbientInGrayScale = true;
  45311. return _this;
  45312. }
  45313. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45314. /**
  45315. * Gets the current double sided mode.
  45316. */
  45317. get: function () {
  45318. return this._twoSidedLighting;
  45319. },
  45320. /**
  45321. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45322. */
  45323. set: function (value) {
  45324. if (this._twoSidedLighting === value) {
  45325. return;
  45326. }
  45327. this._twoSidedLighting = value;
  45328. this.backFaceCulling = !value;
  45329. this._markAllSubMeshesAsTexturesDirty();
  45330. },
  45331. enumerable: true,
  45332. configurable: true
  45333. });
  45334. /**
  45335. * Return the active textures of the material.
  45336. */
  45337. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45338. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45339. if (this.environmentTexture) {
  45340. activeTextures.push(this.environmentTexture);
  45341. }
  45342. if (this.normalTexture) {
  45343. activeTextures.push(this.normalTexture);
  45344. }
  45345. if (this.emissiveTexture) {
  45346. activeTextures.push(this.emissiveTexture);
  45347. }
  45348. if (this.occlusionTexture) {
  45349. activeTextures.push(this.occlusionTexture);
  45350. }
  45351. if (this.lightmapTexture) {
  45352. activeTextures.push(this.lightmapTexture);
  45353. }
  45354. return activeTextures;
  45355. };
  45356. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45357. if (_super.prototype.hasTexture.call(this, texture)) {
  45358. return true;
  45359. }
  45360. if (this.lightmapTexture === texture) {
  45361. return true;
  45362. }
  45363. return false;
  45364. };
  45365. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45366. return "PBRBaseSimpleMaterial";
  45367. };
  45368. __decorate([
  45369. BABYLON.serialize(),
  45370. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45371. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45372. __decorate([
  45373. BABYLON.serialize(),
  45374. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45375. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45376. __decorate([
  45377. BABYLON.serializeAsTexture(),
  45378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45379. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45380. __decorate([
  45381. BABYLON.serialize(),
  45382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45383. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45384. __decorate([
  45385. BABYLON.serialize(),
  45386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45387. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45388. __decorate([
  45389. BABYLON.serializeAsTexture(),
  45390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45391. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45392. __decorate([
  45393. BABYLON.serializeAsColor3("emissive"),
  45394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45395. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45396. __decorate([
  45397. BABYLON.serializeAsTexture(),
  45398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45399. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45400. __decorate([
  45401. BABYLON.serialize(),
  45402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45403. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45404. __decorate([
  45405. BABYLON.serializeAsTexture(),
  45406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45407. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45408. __decorate([
  45409. BABYLON.serialize(),
  45410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45411. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45412. __decorate([
  45413. BABYLON.serialize()
  45414. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45415. __decorate([
  45416. BABYLON.serializeAsTexture(),
  45417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45418. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45419. __decorate([
  45420. BABYLON.serialize(),
  45421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45422. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45423. return PBRBaseSimpleMaterial;
  45424. }(BABYLON.PBRBaseMaterial));
  45425. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45426. })(BABYLON || (BABYLON = {}));
  45427. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45428. var BABYLON;
  45429. (function (BABYLON) {
  45430. /**
  45431. * The Physically based material of BJS.
  45432. *
  45433. * This offers the main features of a standard PBR material.
  45434. * For more information, please refer to the documentation :
  45435. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45436. */
  45437. var PBRMaterial = /** @class */ (function (_super) {
  45438. __extends(PBRMaterial, _super);
  45439. /**
  45440. * Instantiates a new PBRMaterial instance.
  45441. *
  45442. * @param name The material name
  45443. * @param scene The scene the material will be use in.
  45444. */
  45445. function PBRMaterial(name, scene) {
  45446. var _this = _super.call(this, name, scene) || this;
  45447. /**
  45448. * Intensity of the direct lights e.g. the four lights available in your scene.
  45449. * This impacts both the direct diffuse and specular highlights.
  45450. */
  45451. _this.directIntensity = 1.0;
  45452. /**
  45453. * Intensity of the emissive part of the material.
  45454. * This helps controlling the emissive effect without modifying the emissive color.
  45455. */
  45456. _this.emissiveIntensity = 1.0;
  45457. /**
  45458. * Intensity of the environment e.g. how much the environment will light the object
  45459. * either through harmonics for rough material or through the refelction for shiny ones.
  45460. */
  45461. _this.environmentIntensity = 1.0;
  45462. /**
  45463. * This is a special control allowing the reduction of the specular highlights coming from the
  45464. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45465. */
  45466. _this.specularIntensity = 1.0;
  45467. /**
  45468. * Debug Control allowing disabling the bump map on this material.
  45469. */
  45470. _this.disableBumpMap = false;
  45471. /**
  45472. * AKA Occlusion Texture Intensity in other nomenclature.
  45473. */
  45474. _this.ambientTextureStrength = 1.0;
  45475. /**
  45476. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45477. * 1 means it completely occludes it
  45478. * 0 mean it has no impact
  45479. */
  45480. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45481. /**
  45482. * The color of a material in ambient lighting.
  45483. */
  45484. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45485. /**
  45486. * AKA Diffuse Color in other nomenclature.
  45487. */
  45488. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45489. /**
  45490. * AKA Specular Color in other nomenclature.
  45491. */
  45492. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45493. /**
  45494. * The color reflected from the material.
  45495. */
  45496. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45497. /**
  45498. * The color emitted from the material.
  45499. */
  45500. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45501. /**
  45502. * AKA Glossiness in other nomenclature.
  45503. */
  45504. _this.microSurface = 1.0;
  45505. /**
  45506. * source material index of refraction (IOR)' / 'destination material IOR.
  45507. */
  45508. _this.indexOfRefraction = 0.66;
  45509. /**
  45510. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45511. */
  45512. _this.invertRefractionY = false;
  45513. /**
  45514. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45515. * Materials half opaque for instance using refraction could benefit from this control.
  45516. */
  45517. _this.linkRefractionWithTransparency = false;
  45518. _this.useLightmapAsShadowmap = false;
  45519. /**
  45520. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45521. */
  45522. _this.useAlphaFromAlbedoTexture = false;
  45523. /**
  45524. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45525. */
  45526. _this.forceAlphaTest = false;
  45527. /**
  45528. * Defines the alpha limits in alpha test mode.
  45529. */
  45530. _this.alphaCutOff = 0.4;
  45531. /**
  45532. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45533. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45534. */
  45535. _this.useSpecularOverAlpha = true;
  45536. /**
  45537. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45538. */
  45539. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45540. /**
  45541. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45542. */
  45543. _this.useRoughnessFromMetallicTextureAlpha = true;
  45544. /**
  45545. * Specifies if the metallic texture contains the roughness information in its green channel.
  45546. */
  45547. _this.useRoughnessFromMetallicTextureGreen = false;
  45548. /**
  45549. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45550. */
  45551. _this.useMetallnessFromMetallicTextureBlue = false;
  45552. /**
  45553. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45554. */
  45555. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45556. /**
  45557. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45558. */
  45559. _this.useAmbientInGrayScale = false;
  45560. /**
  45561. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45562. * The material will try to infer what glossiness each pixel should be.
  45563. */
  45564. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45565. /**
  45566. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45567. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45568. */
  45569. _this.useRadianceOverAlpha = true;
  45570. /**
  45571. * Allows using an object space normal map (instead of tangent space).
  45572. */
  45573. _this.useObjectSpaceNormalMap = false;
  45574. /**
  45575. * Allows using the bump map in parallax mode.
  45576. */
  45577. _this.useParallax = false;
  45578. /**
  45579. * Allows using the bump map in parallax occlusion mode.
  45580. */
  45581. _this.useParallaxOcclusion = false;
  45582. /**
  45583. * Controls the scale bias of the parallax mode.
  45584. */
  45585. _this.parallaxScaleBias = 0.05;
  45586. /**
  45587. * If sets to true, disables all the lights affecting the material.
  45588. */
  45589. _this.disableLighting = false;
  45590. /**
  45591. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45592. */
  45593. _this.forceIrradianceInFragment = false;
  45594. /**
  45595. * Number of Simultaneous lights allowed on the material.
  45596. */
  45597. _this.maxSimultaneousLights = 4;
  45598. /**
  45599. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45600. */
  45601. _this.invertNormalMapX = false;
  45602. /**
  45603. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45604. */
  45605. _this.invertNormalMapY = false;
  45606. /**
  45607. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45608. */
  45609. _this.twoSidedLighting = false;
  45610. /**
  45611. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45612. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45613. */
  45614. _this.useAlphaFresnel = false;
  45615. /**
  45616. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45617. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45618. */
  45619. _this.useLinearAlphaFresnel = false;
  45620. /**
  45621. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45622. * And/Or occlude the blended part.
  45623. */
  45624. _this.environmentBRDFTexture = null;
  45625. /**
  45626. * Force normal to face away from face.
  45627. */
  45628. _this.forceNormalForward = false;
  45629. /**
  45630. * Enables specular anti aliasing in the PBR shader.
  45631. * It will both interacts on the Geometry for analytical and IBL lighting.
  45632. * It also prefilter the roughness map based on the bump values.
  45633. */
  45634. _this.enableSpecularAntiAliasing = false;
  45635. /**
  45636. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45637. * makes the reflect vector face the model (under horizon).
  45638. */
  45639. _this.useHorizonOcclusion = true;
  45640. /**
  45641. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45642. * too much the area relying on ambient texture to define their ambient occlusion.
  45643. */
  45644. _this.useRadianceOcclusion = true;
  45645. /**
  45646. * If set to true, no lighting calculations will be applied.
  45647. */
  45648. _this.unlit = false;
  45649. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45650. return _this;
  45651. }
  45652. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45653. /**
  45654. * BJS is using an harcoded light falloff based on a manually sets up range.
  45655. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45656. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45657. */
  45658. get: function () {
  45659. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45660. },
  45661. /**
  45662. * BJS is using an harcoded light falloff based on a manually sets up range.
  45663. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45664. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45665. */
  45666. set: function (value) {
  45667. if (value !== this.usePhysicalLightFalloff) {
  45668. // Ensure the effect will be rebuilt.
  45669. this._markAllSubMeshesAsTexturesDirty();
  45670. if (value) {
  45671. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45672. }
  45673. else {
  45674. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45675. }
  45676. }
  45677. },
  45678. enumerable: true,
  45679. configurable: true
  45680. });
  45681. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45682. /**
  45683. * In order to support the falloff compatibility with gltf, a special mode has been added
  45684. * to reproduce the gltf light falloff.
  45685. */
  45686. get: function () {
  45687. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45688. },
  45689. /**
  45690. * In order to support the falloff compatibility with gltf, a special mode has been added
  45691. * to reproduce the gltf light falloff.
  45692. */
  45693. set: function (value) {
  45694. if (value !== this.useGLTFLightFalloff) {
  45695. // Ensure the effect will be rebuilt.
  45696. this._markAllSubMeshesAsTexturesDirty();
  45697. if (value) {
  45698. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45699. }
  45700. else {
  45701. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45702. }
  45703. }
  45704. },
  45705. enumerable: true,
  45706. configurable: true
  45707. });
  45708. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45709. /**
  45710. * Gets the image processing configuration used either in this material.
  45711. */
  45712. get: function () {
  45713. return this._imageProcessingConfiguration;
  45714. },
  45715. /**
  45716. * Sets the Default image processing configuration used either in the this material.
  45717. *
  45718. * If sets to null, the scene one is in use.
  45719. */
  45720. set: function (value) {
  45721. this._attachImageProcessingConfiguration(value);
  45722. // Ensure the effect will be rebuilt.
  45723. this._markAllSubMeshesAsTexturesDirty();
  45724. },
  45725. enumerable: true,
  45726. configurable: true
  45727. });
  45728. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45729. /**
  45730. * Gets wether the color curves effect is enabled.
  45731. */
  45732. get: function () {
  45733. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45734. },
  45735. /**
  45736. * Sets wether the color curves effect is enabled.
  45737. */
  45738. set: function (value) {
  45739. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45740. },
  45741. enumerable: true,
  45742. configurable: true
  45743. });
  45744. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45745. /**
  45746. * Gets wether the color grading effect is enabled.
  45747. */
  45748. get: function () {
  45749. return this.imageProcessingConfiguration.colorGradingEnabled;
  45750. },
  45751. /**
  45752. * Gets wether the color grading effect is enabled.
  45753. */
  45754. set: function (value) {
  45755. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45756. },
  45757. enumerable: true,
  45758. configurable: true
  45759. });
  45760. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45761. /**
  45762. * Gets wether tonemapping is enabled or not.
  45763. */
  45764. get: function () {
  45765. return this._imageProcessingConfiguration.toneMappingEnabled;
  45766. },
  45767. /**
  45768. * Sets wether tonemapping is enabled or not
  45769. */
  45770. set: function (value) {
  45771. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45772. },
  45773. enumerable: true,
  45774. configurable: true
  45775. });
  45776. ;
  45777. ;
  45778. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45779. /**
  45780. * The camera exposure used on this material.
  45781. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45782. * This corresponds to a photographic exposure.
  45783. */
  45784. get: function () {
  45785. return this._imageProcessingConfiguration.exposure;
  45786. },
  45787. /**
  45788. * The camera exposure used on this material.
  45789. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45790. * This corresponds to a photographic exposure.
  45791. */
  45792. set: function (value) {
  45793. this._imageProcessingConfiguration.exposure = value;
  45794. },
  45795. enumerable: true,
  45796. configurable: true
  45797. });
  45798. ;
  45799. ;
  45800. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45801. /**
  45802. * Gets The camera contrast used on this material.
  45803. */
  45804. get: function () {
  45805. return this._imageProcessingConfiguration.contrast;
  45806. },
  45807. /**
  45808. * Sets The camera contrast used on this material.
  45809. */
  45810. set: function (value) {
  45811. this._imageProcessingConfiguration.contrast = value;
  45812. },
  45813. enumerable: true,
  45814. configurable: true
  45815. });
  45816. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45817. /**
  45818. * Gets the Color Grading 2D Lookup Texture.
  45819. */
  45820. get: function () {
  45821. return this._imageProcessingConfiguration.colorGradingTexture;
  45822. },
  45823. /**
  45824. * Sets the Color Grading 2D Lookup Texture.
  45825. */
  45826. set: function (value) {
  45827. this._imageProcessingConfiguration.colorGradingTexture = value;
  45828. },
  45829. enumerable: true,
  45830. configurable: true
  45831. });
  45832. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45833. /**
  45834. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45835. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45836. * 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;
  45837. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45838. */
  45839. get: function () {
  45840. return this._imageProcessingConfiguration.colorCurves;
  45841. },
  45842. /**
  45843. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45844. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45845. * 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;
  45846. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45847. */
  45848. set: function (value) {
  45849. this._imageProcessingConfiguration.colorCurves = value;
  45850. },
  45851. enumerable: true,
  45852. configurable: true
  45853. });
  45854. /**
  45855. * Returns the name of this material class.
  45856. */
  45857. PBRMaterial.prototype.getClassName = function () {
  45858. return "PBRMaterial";
  45859. };
  45860. /**
  45861. * Returns an array of the actively used textures.
  45862. * @returns - Array of BaseTextures
  45863. */
  45864. PBRMaterial.prototype.getActiveTextures = function () {
  45865. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45866. if (this._albedoTexture) {
  45867. activeTextures.push(this._albedoTexture);
  45868. }
  45869. if (this._ambientTexture) {
  45870. activeTextures.push(this._ambientTexture);
  45871. }
  45872. if (this._opacityTexture) {
  45873. activeTextures.push(this._opacityTexture);
  45874. }
  45875. if (this._reflectionTexture) {
  45876. activeTextures.push(this._reflectionTexture);
  45877. }
  45878. if (this._emissiveTexture) {
  45879. activeTextures.push(this._emissiveTexture);
  45880. }
  45881. if (this._reflectivityTexture) {
  45882. activeTextures.push(this._reflectivityTexture);
  45883. }
  45884. if (this._metallicTexture) {
  45885. activeTextures.push(this._metallicTexture);
  45886. }
  45887. if (this._microSurfaceTexture) {
  45888. activeTextures.push(this._microSurfaceTexture);
  45889. }
  45890. if (this._bumpTexture) {
  45891. activeTextures.push(this._bumpTexture);
  45892. }
  45893. if (this._lightmapTexture) {
  45894. activeTextures.push(this._lightmapTexture);
  45895. }
  45896. if (this._refractionTexture) {
  45897. activeTextures.push(this._refractionTexture);
  45898. }
  45899. return activeTextures;
  45900. };
  45901. /**
  45902. * Checks to see if a texture is used in the material.
  45903. * @param texture - Base texture to use.
  45904. * @returns - Boolean specifying if a texture is used in the material.
  45905. */
  45906. PBRMaterial.prototype.hasTexture = function (texture) {
  45907. if (_super.prototype.hasTexture.call(this, texture)) {
  45908. return true;
  45909. }
  45910. if (this._albedoTexture === texture) {
  45911. return true;
  45912. }
  45913. if (this._ambientTexture === texture) {
  45914. return true;
  45915. }
  45916. if (this._opacityTexture === texture) {
  45917. return true;
  45918. }
  45919. if (this._reflectionTexture === texture) {
  45920. return true;
  45921. }
  45922. if (this._reflectivityTexture === texture) {
  45923. return true;
  45924. }
  45925. if (this._metallicTexture === texture) {
  45926. return true;
  45927. }
  45928. if (this._microSurfaceTexture === texture) {
  45929. return true;
  45930. }
  45931. if (this._bumpTexture === texture) {
  45932. return true;
  45933. }
  45934. if (this._lightmapTexture === texture) {
  45935. return true;
  45936. }
  45937. if (this._refractionTexture === texture) {
  45938. return true;
  45939. }
  45940. return false;
  45941. };
  45942. /**
  45943. * Makes a duplicate of the current material.
  45944. * @param name - name to use for the new material.
  45945. */
  45946. PBRMaterial.prototype.clone = function (name) {
  45947. var _this = this;
  45948. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45949. clone.id = name;
  45950. clone.name = name;
  45951. return clone;
  45952. };
  45953. /**
  45954. * Serializes this PBR Material.
  45955. * @returns - An object with the serialized material.
  45956. */
  45957. PBRMaterial.prototype.serialize = function () {
  45958. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45959. serializationObject.customType = "BABYLON.PBRMaterial";
  45960. return serializationObject;
  45961. };
  45962. // Statics
  45963. /**
  45964. * Parses a PBR Material from a serialized object.
  45965. * @param source - Serialized object.
  45966. * @param scene - BJS scene instance.
  45967. * @param rootUrl - url for the scene object
  45968. * @returns - PBRMaterial
  45969. */
  45970. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45971. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45972. };
  45973. /**
  45974. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45975. */
  45976. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45977. /**
  45978. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45979. */
  45980. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45981. /**
  45982. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45983. */
  45984. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45985. /**
  45986. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45987. * They are also discarded below the alpha cutoff threshold to improve performances.
  45988. */
  45989. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45990. /**
  45991. * Defines the default value of how much AO map is occluding the analytical lights
  45992. * (point spot...).
  45993. */
  45994. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45995. __decorate([
  45996. BABYLON.serialize(),
  45997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45998. ], PBRMaterial.prototype, "directIntensity", void 0);
  45999. __decorate([
  46000. BABYLON.serialize(),
  46001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46002. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46003. __decorate([
  46004. BABYLON.serialize(),
  46005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46006. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46007. __decorate([
  46008. BABYLON.serialize(),
  46009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46010. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46011. __decorate([
  46012. BABYLON.serialize(),
  46013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46014. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46015. __decorate([
  46016. BABYLON.serializeAsTexture(),
  46017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46018. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46019. __decorate([
  46020. BABYLON.serializeAsTexture(),
  46021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46022. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46023. __decorate([
  46024. BABYLON.serialize(),
  46025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46026. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46027. __decorate([
  46028. BABYLON.serialize(),
  46029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46030. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  46031. __decorate([
  46032. BABYLON.serializeAsTexture(),
  46033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46034. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46035. __decorate([
  46036. BABYLON.serializeAsTexture(),
  46037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46038. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46039. __decorate([
  46040. BABYLON.serializeAsTexture(),
  46041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46042. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46043. __decorate([
  46044. BABYLON.serializeAsTexture(),
  46045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46046. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46047. __decorate([
  46048. BABYLON.serializeAsTexture(),
  46049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46050. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46051. __decorate([
  46052. BABYLON.serialize(),
  46053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46054. ], PBRMaterial.prototype, "metallic", void 0);
  46055. __decorate([
  46056. BABYLON.serialize(),
  46057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46058. ], PBRMaterial.prototype, "roughness", void 0);
  46059. __decorate([
  46060. BABYLON.serializeAsTexture(),
  46061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46062. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46063. __decorate([
  46064. BABYLON.serializeAsTexture(),
  46065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46066. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46067. __decorate([
  46068. BABYLON.serializeAsTexture(),
  46069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46070. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46071. __decorate([
  46072. BABYLON.serializeAsTexture(),
  46073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46074. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46075. __decorate([
  46076. BABYLON.serializeAsColor3("ambient"),
  46077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46078. ], PBRMaterial.prototype, "ambientColor", void 0);
  46079. __decorate([
  46080. BABYLON.serializeAsColor3("albedo"),
  46081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46082. ], PBRMaterial.prototype, "albedoColor", void 0);
  46083. __decorate([
  46084. BABYLON.serializeAsColor3("reflectivity"),
  46085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46086. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46087. __decorate([
  46088. BABYLON.serializeAsColor3("reflection"),
  46089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46090. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46091. __decorate([
  46092. BABYLON.serializeAsColor3("emissive"),
  46093. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46094. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46095. __decorate([
  46096. BABYLON.serialize(),
  46097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46098. ], PBRMaterial.prototype, "microSurface", void 0);
  46099. __decorate([
  46100. BABYLON.serialize(),
  46101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46102. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46103. __decorate([
  46104. BABYLON.serialize(),
  46105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46106. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46107. __decorate([
  46108. BABYLON.serialize(),
  46109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46110. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46111. __decorate([
  46112. BABYLON.serialize(),
  46113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46114. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46115. __decorate([
  46116. BABYLON.serialize(),
  46117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46118. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46119. __decorate([
  46120. BABYLON.serialize(),
  46121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46122. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46123. __decorate([
  46124. BABYLON.serialize(),
  46125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46126. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46127. __decorate([
  46128. BABYLON.serialize(),
  46129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46130. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46131. __decorate([
  46132. BABYLON.serialize(),
  46133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46134. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46135. __decorate([
  46136. BABYLON.serialize(),
  46137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46138. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46139. __decorate([
  46140. BABYLON.serialize(),
  46141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46142. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46143. __decorate([
  46144. BABYLON.serialize(),
  46145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46146. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46147. __decorate([
  46148. BABYLON.serialize(),
  46149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46150. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46151. __decorate([
  46152. BABYLON.serialize(),
  46153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46154. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46155. __decorate([
  46156. BABYLON.serialize(),
  46157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46158. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46159. __decorate([
  46160. BABYLON.serialize()
  46161. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  46162. __decorate([
  46163. BABYLON.serialize()
  46164. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  46165. __decorate([
  46166. BABYLON.serialize(),
  46167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46168. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46169. __decorate([
  46170. BABYLON.serialize(),
  46171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46172. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46173. __decorate([
  46174. BABYLON.serialize(),
  46175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46176. ], PBRMaterial.prototype, "useParallax", void 0);
  46177. __decorate([
  46178. BABYLON.serialize(),
  46179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46180. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46181. __decorate([
  46182. BABYLON.serialize(),
  46183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46184. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46185. __decorate([
  46186. BABYLON.serialize(),
  46187. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46188. ], PBRMaterial.prototype, "disableLighting", void 0);
  46189. __decorate([
  46190. BABYLON.serialize(),
  46191. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46192. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46193. __decorate([
  46194. BABYLON.serialize(),
  46195. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46196. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46197. __decorate([
  46198. BABYLON.serialize(),
  46199. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46200. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46201. __decorate([
  46202. BABYLON.serialize(),
  46203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46204. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46205. __decorate([
  46206. BABYLON.serialize(),
  46207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46208. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46209. __decorate([
  46210. BABYLON.serialize(),
  46211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46212. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46213. __decorate([
  46214. BABYLON.serialize(),
  46215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46216. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46217. __decorate([
  46218. BABYLON.serializeAsTexture(),
  46219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46220. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46221. __decorate([
  46222. BABYLON.serialize(),
  46223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46224. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46225. __decorate([
  46226. BABYLON.serialize(),
  46227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46228. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46229. __decorate([
  46230. BABYLON.serialize(),
  46231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46232. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46233. __decorate([
  46234. BABYLON.serialize(),
  46235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46236. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46237. __decorate([
  46238. BABYLON.serialize(),
  46239. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46240. ], PBRMaterial.prototype, "unlit", void 0);
  46241. return PBRMaterial;
  46242. }(BABYLON.PBRBaseMaterial));
  46243. BABYLON.PBRMaterial = PBRMaterial;
  46244. })(BABYLON || (BABYLON = {}));
  46245. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46246. var BABYLON;
  46247. (function (BABYLON) {
  46248. /**
  46249. * The PBR material of BJS following the metal roughness convention.
  46250. *
  46251. * This fits to the PBR convention in the GLTF definition:
  46252. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46253. */
  46254. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46255. __extends(PBRMetallicRoughnessMaterial, _super);
  46256. /**
  46257. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46258. *
  46259. * @param name The material name
  46260. * @param scene The scene the material will be use in.
  46261. */
  46262. function PBRMetallicRoughnessMaterial(name, scene) {
  46263. var _this = _super.call(this, name, scene) || this;
  46264. _this._useRoughnessFromMetallicTextureAlpha = false;
  46265. _this._useRoughnessFromMetallicTextureGreen = true;
  46266. _this._useMetallnessFromMetallicTextureBlue = true;
  46267. _this.metallic = 1.0;
  46268. _this.roughness = 1.0;
  46269. return _this;
  46270. }
  46271. /**
  46272. * Return the currrent class name of the material.
  46273. */
  46274. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46275. return "PBRMetallicRoughnessMaterial";
  46276. };
  46277. /**
  46278. * Return the active textures of the material.
  46279. */
  46280. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46281. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46282. if (this.baseTexture) {
  46283. activeTextures.push(this.baseTexture);
  46284. }
  46285. if (this.metallicRoughnessTexture) {
  46286. activeTextures.push(this.metallicRoughnessTexture);
  46287. }
  46288. return activeTextures;
  46289. };
  46290. /**
  46291. * Checks to see if a texture is used in the material.
  46292. * @param texture - Base texture to use.
  46293. * @returns - Boolean specifying if a texture is used in the material.
  46294. */
  46295. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46296. if (_super.prototype.hasTexture.call(this, texture)) {
  46297. return true;
  46298. }
  46299. if (this.baseTexture === texture) {
  46300. return true;
  46301. }
  46302. if (this.metallicRoughnessTexture === texture) {
  46303. return true;
  46304. }
  46305. return false;
  46306. };
  46307. /**
  46308. * Makes a duplicate of the current material.
  46309. * @param name - name to use for the new material.
  46310. */
  46311. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46312. var _this = this;
  46313. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46314. clone.id = name;
  46315. clone.name = name;
  46316. return clone;
  46317. };
  46318. /**
  46319. * Serialize the material to a parsable JSON object.
  46320. */
  46321. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46322. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46323. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46324. return serializationObject;
  46325. };
  46326. /**
  46327. * Parses a JSON object correponding to the serialize function.
  46328. */
  46329. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46330. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46331. };
  46332. __decorate([
  46333. BABYLON.serializeAsColor3(),
  46334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46335. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46336. __decorate([
  46337. BABYLON.serializeAsTexture(),
  46338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46339. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46340. __decorate([
  46341. BABYLON.serialize(),
  46342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46343. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46344. __decorate([
  46345. BABYLON.serialize(),
  46346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46347. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46348. __decorate([
  46349. BABYLON.serializeAsTexture(),
  46350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46351. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46352. return PBRMetallicRoughnessMaterial;
  46353. }(BABYLON.PBRBaseSimpleMaterial));
  46354. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46355. })(BABYLON || (BABYLON = {}));
  46356. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46357. var BABYLON;
  46358. (function (BABYLON) {
  46359. /**
  46360. * The PBR material of BJS following the specular glossiness convention.
  46361. *
  46362. * This fits to the PBR convention in the GLTF definition:
  46363. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46364. */
  46365. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46366. __extends(PBRSpecularGlossinessMaterial, _super);
  46367. /**
  46368. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46369. *
  46370. * @param name The material name
  46371. * @param scene The scene the material will be use in.
  46372. */
  46373. function PBRSpecularGlossinessMaterial(name, scene) {
  46374. var _this = _super.call(this, name, scene) || this;
  46375. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46376. return _this;
  46377. }
  46378. /**
  46379. * Return the currrent class name of the material.
  46380. */
  46381. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46382. return "PBRSpecularGlossinessMaterial";
  46383. };
  46384. /**
  46385. * Return the active textures of the material.
  46386. */
  46387. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46388. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46389. if (this.diffuseTexture) {
  46390. activeTextures.push(this.diffuseTexture);
  46391. }
  46392. if (this.specularGlossinessTexture) {
  46393. activeTextures.push(this.specularGlossinessTexture);
  46394. }
  46395. return activeTextures;
  46396. };
  46397. /**
  46398. * Checks to see if a texture is used in the material.
  46399. * @param texture - Base texture to use.
  46400. * @returns - Boolean specifying if a texture is used in the material.
  46401. */
  46402. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46403. if (_super.prototype.hasTexture.call(this, texture)) {
  46404. return true;
  46405. }
  46406. if (this.diffuseTexture === texture) {
  46407. return true;
  46408. }
  46409. if (this.specularGlossinessTexture === texture) {
  46410. return true;
  46411. }
  46412. return false;
  46413. };
  46414. /**
  46415. * Makes a duplicate of the current material.
  46416. * @param name - name to use for the new material.
  46417. */
  46418. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46419. var _this = this;
  46420. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46421. clone.id = name;
  46422. clone.name = name;
  46423. return clone;
  46424. };
  46425. /**
  46426. * Serialize the material to a parsable JSON object.
  46427. */
  46428. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46429. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46430. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46431. return serializationObject;
  46432. };
  46433. /**
  46434. * Parses a JSON object correponding to the serialize function.
  46435. */
  46436. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46437. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46438. };
  46439. __decorate([
  46440. BABYLON.serializeAsColor3("diffuse"),
  46441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46442. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46443. __decorate([
  46444. BABYLON.serializeAsTexture(),
  46445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46446. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46447. __decorate([
  46448. BABYLON.serializeAsColor3("specular"),
  46449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46450. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46451. __decorate([
  46452. BABYLON.serialize(),
  46453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46454. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46455. __decorate([
  46456. BABYLON.serializeAsTexture(),
  46457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46458. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46459. return PBRSpecularGlossinessMaterial;
  46460. }(BABYLON.PBRBaseSimpleMaterial));
  46461. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46462. })(BABYLON || (BABYLON = {}));
  46463. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46464. var BABYLON;
  46465. (function (BABYLON) {
  46466. /**
  46467. * This is a list of all the different input types that are available in the application.
  46468. * Fo instance: ArcRotateCameraGamepadInput...
  46469. */
  46470. BABYLON.CameraInputTypes = {};
  46471. /**
  46472. * This represents the input manager used within a camera.
  46473. * It helps dealing with all the different kind of input attached to a camera.
  46474. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46475. */
  46476. var CameraInputsManager = /** @class */ (function () {
  46477. /**
  46478. * Instantiate a new Camera Input Manager.
  46479. * @param camera Defines the camera the input manager blongs to
  46480. */
  46481. function CameraInputsManager(camera) {
  46482. this.attached = {};
  46483. this.camera = camera;
  46484. this.checkInputs = function () { };
  46485. }
  46486. /**
  46487. * Add an input method to a camera
  46488. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46489. * @param input camera input method
  46490. */
  46491. CameraInputsManager.prototype.add = function (input) {
  46492. var type = input.getSimpleName();
  46493. if (this.attached[type]) {
  46494. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46495. return;
  46496. }
  46497. this.attached[type] = input;
  46498. input.camera = this.camera;
  46499. //for checkInputs, we are dynamically creating a function
  46500. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46501. if (input.checkInputs) {
  46502. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46503. }
  46504. if (this.attachedElement) {
  46505. input.attachControl(this.attachedElement);
  46506. }
  46507. };
  46508. /**
  46509. * Remove a specific input method from a camera
  46510. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46511. * @param inputToRemove camera input method
  46512. */
  46513. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46514. for (var cam in this.attached) {
  46515. var input = this.attached[cam];
  46516. if (input === inputToRemove) {
  46517. input.detachControl(this.attachedElement);
  46518. input.camera = null;
  46519. delete this.attached[cam];
  46520. this.rebuildInputCheck();
  46521. }
  46522. }
  46523. };
  46524. /**
  46525. * Remove a specific input type from a camera
  46526. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  46527. * @param inputType the type of the input to remove
  46528. */
  46529. CameraInputsManager.prototype.removeByType = function (inputType) {
  46530. for (var cam in this.attached) {
  46531. var input = this.attached[cam];
  46532. if (input.getClassName() === inputType) {
  46533. input.detachControl(this.attachedElement);
  46534. input.camera = null;
  46535. delete this.attached[cam];
  46536. this.rebuildInputCheck();
  46537. }
  46538. }
  46539. };
  46540. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46541. var current = this.checkInputs;
  46542. return function () {
  46543. current();
  46544. fn();
  46545. };
  46546. };
  46547. /**
  46548. * Attach the input controls to the currently attached dom element to listen the events from.
  46549. * @param input Defines the input to attach
  46550. */
  46551. CameraInputsManager.prototype.attachInput = function (input) {
  46552. if (this.attachedElement) {
  46553. input.attachControl(this.attachedElement, this.noPreventDefault);
  46554. }
  46555. };
  46556. /**
  46557. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  46558. * @param element Defines the dom element to collect the events from
  46559. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46560. */
  46561. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46562. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46563. if (this.attachedElement) {
  46564. return;
  46565. }
  46566. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46567. this.attachedElement = element;
  46568. this.noPreventDefault = noPreventDefault;
  46569. for (var cam in this.attached) {
  46570. this.attached[cam].attachControl(element, noPreventDefault);
  46571. }
  46572. };
  46573. /**
  46574. * Detach the current manager inputs controls from a specific dom element.
  46575. * @param element Defines the dom element to collect the events from
  46576. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  46577. */
  46578. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46579. if (disconnect === void 0) { disconnect = false; }
  46580. if (this.attachedElement !== element) {
  46581. return;
  46582. }
  46583. for (var cam in this.attached) {
  46584. this.attached[cam].detachControl(element);
  46585. if (disconnect) {
  46586. this.attached[cam].camera = null;
  46587. }
  46588. }
  46589. this.attachedElement = null;
  46590. };
  46591. /**
  46592. * Rebuild the dynamic inputCheck function from the current list of
  46593. * defined inputs in the manager.
  46594. */
  46595. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46596. this.checkInputs = function () { };
  46597. for (var cam in this.attached) {
  46598. var input = this.attached[cam];
  46599. if (input.checkInputs) {
  46600. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46601. }
  46602. }
  46603. };
  46604. /**
  46605. * Remove all attached input methods from a camera
  46606. */
  46607. CameraInputsManager.prototype.clear = function () {
  46608. if (this.attachedElement) {
  46609. this.detachElement(this.attachedElement, true);
  46610. }
  46611. this.attached = {};
  46612. this.attachedElement = null;
  46613. this.checkInputs = function () { };
  46614. };
  46615. /**
  46616. * Serialize the current input manager attached to a camera.
  46617. * This ensures than once parsed,
  46618. * the input associated to the camera will be identical to the current ones
  46619. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  46620. */
  46621. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46622. var inputs = {};
  46623. for (var cam in this.attached) {
  46624. var input = this.attached[cam];
  46625. var res = BABYLON.SerializationHelper.Serialize(input);
  46626. inputs[input.getClassName()] = res;
  46627. }
  46628. serializedCamera.inputsmgr = inputs;
  46629. };
  46630. /**
  46631. * Parses an input manager serialized JSON to restore the previous list of inputs
  46632. * and states associated to a camera.
  46633. * @param parsedCamera Defines the JSON to parse
  46634. */
  46635. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46636. var parsedInputs = parsedCamera.inputsmgr;
  46637. if (parsedInputs) {
  46638. this.clear();
  46639. for (var n in parsedInputs) {
  46640. var construct = BABYLON.CameraInputTypes[n];
  46641. if (construct) {
  46642. var parsedinput = parsedInputs[n];
  46643. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46644. this.add(input);
  46645. }
  46646. }
  46647. }
  46648. else {
  46649. //2016-03-08 this part is for managing backward compatibility
  46650. for (var n in this.attached) {
  46651. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46652. if (construct) {
  46653. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46654. this.remove(this.attached[n]);
  46655. this.add(input);
  46656. }
  46657. }
  46658. }
  46659. };
  46660. return CameraInputsManager;
  46661. }());
  46662. BABYLON.CameraInputsManager = CameraInputsManager;
  46663. })(BABYLON || (BABYLON = {}));
  46664. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46665. var BABYLON;
  46666. (function (BABYLON) {
  46667. /**
  46668. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  46669. * This is the base of the follow, arc rotate cameras and Free camera
  46670. * @see http://doc.babylonjs.com/features/cameras
  46671. */
  46672. var TargetCamera = /** @class */ (function (_super) {
  46673. __extends(TargetCamera, _super);
  46674. /**
  46675. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  46676. * This is the base of the follow, arc rotate cameras and Free camera
  46677. * @see http://doc.babylonjs.com/features/cameras
  46678. * @param name Defines the name of the camera in the scene
  46679. * @param position Defines the start position of the camera in the scene
  46680. * @param scene Defines the scene the camera belongs to
  46681. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  46682. */
  46683. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46684. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46685. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46686. /**
  46687. * Define the current direction the camera is moving to
  46688. */
  46689. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46690. /**
  46691. * Define the current rotation the camera is rotating to
  46692. */
  46693. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46694. /**
  46695. * Define the current rotation of the camera
  46696. */
  46697. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46698. /**
  46699. * Define the current speed of the camera
  46700. */
  46701. _this.speed = 2.0;
  46702. /**
  46703. * Add cconstraint to the camera to prevent it to move freely in all directions and
  46704. * around all axis.
  46705. */
  46706. _this.noRotationConstraint = false;
  46707. /**
  46708. * Define the current target of the camera as an object or a position.
  46709. */
  46710. _this.lockedTarget = null;
  46711. /** @hidden */
  46712. _this._currentTarget = BABYLON.Vector3.Zero();
  46713. /** @hidden */
  46714. _this._viewMatrix = BABYLON.Matrix.Zero();
  46715. /** @hidden */
  46716. _this._camMatrix = BABYLON.Matrix.Zero();
  46717. /** @hidden */
  46718. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46719. /** @hidden */
  46720. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46721. /** @hidden */
  46722. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46723. /** @hidden */
  46724. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46725. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46726. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46727. _this._defaultUp = BABYLON.Vector3.Up();
  46728. _this._cachedRotationZ = 0;
  46729. return _this;
  46730. }
  46731. /**
  46732. * Gets the position in front of the camera at a given distance.
  46733. * @param distance The distance from the camera we want the position to be
  46734. * @returns the position
  46735. */
  46736. TargetCamera.prototype.getFrontPosition = function (distance) {
  46737. this.getWorldMatrix();
  46738. var direction = this.getTarget().subtract(this.position);
  46739. direction.normalize();
  46740. direction.scaleInPlace(distance);
  46741. return this.globalPosition.add(direction);
  46742. };
  46743. /** @hidden */
  46744. TargetCamera.prototype._getLockedTargetPosition = function () {
  46745. if (!this.lockedTarget) {
  46746. return null;
  46747. }
  46748. if (this.lockedTarget.absolutePosition) {
  46749. this.lockedTarget.computeWorldMatrix();
  46750. }
  46751. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46752. };
  46753. /**
  46754. * Store current camera state of the camera (fov, position, rotation, etc..)
  46755. * @returns the camera
  46756. */
  46757. TargetCamera.prototype.storeState = function () {
  46758. this._storedPosition = this.position.clone();
  46759. this._storedRotation = this.rotation.clone();
  46760. if (this.rotationQuaternion) {
  46761. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46762. }
  46763. return _super.prototype.storeState.call(this);
  46764. };
  46765. /**
  46766. * Restored camera state. You must call storeState() first
  46767. * @returns whether it was successful or not
  46768. * @hidden
  46769. */
  46770. TargetCamera.prototype._restoreStateValues = function () {
  46771. if (!_super.prototype._restoreStateValues.call(this)) {
  46772. return false;
  46773. }
  46774. this.position = this._storedPosition.clone();
  46775. this.rotation = this._storedRotation.clone();
  46776. if (this.rotationQuaternion) {
  46777. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46778. }
  46779. this.cameraDirection.copyFromFloats(0, 0, 0);
  46780. this.cameraRotation.copyFromFloats(0, 0);
  46781. return true;
  46782. };
  46783. /** @hidden */
  46784. TargetCamera.prototype._initCache = function () {
  46785. _super.prototype._initCache.call(this);
  46786. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46787. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46788. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46789. };
  46790. /** @hidden */
  46791. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46792. if (!ignoreParentClass) {
  46793. _super.prototype._updateCache.call(this);
  46794. }
  46795. var lockedTargetPosition = this._getLockedTargetPosition();
  46796. if (!lockedTargetPosition) {
  46797. this._cache.lockedTarget = null;
  46798. }
  46799. else {
  46800. if (!this._cache.lockedTarget) {
  46801. this._cache.lockedTarget = lockedTargetPosition.clone();
  46802. }
  46803. else {
  46804. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46805. }
  46806. }
  46807. this._cache.rotation.copyFrom(this.rotation);
  46808. if (this.rotationQuaternion)
  46809. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46810. };
  46811. // Synchronized
  46812. /** @hidden */
  46813. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46814. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46815. return false;
  46816. }
  46817. var lockedTargetPosition = this._getLockedTargetPosition();
  46818. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46819. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46820. };
  46821. // Methods
  46822. /** @hidden */
  46823. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46824. var engine = this.getEngine();
  46825. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46826. };
  46827. // Target
  46828. /** @hidden */
  46829. TargetCamera.prototype.setTarget = function (target) {
  46830. this.upVector.normalize();
  46831. if (this.position.z === target.z) {
  46832. this.position.z += BABYLON.Epsilon;
  46833. }
  46834. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46835. this._camMatrix.invert();
  46836. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46837. var vDir = target.subtract(this.position);
  46838. if (vDir.x >= 0.0) {
  46839. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46840. }
  46841. else {
  46842. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46843. }
  46844. this.rotation.z = 0;
  46845. if (isNaN(this.rotation.x)) {
  46846. this.rotation.x = 0;
  46847. }
  46848. if (isNaN(this.rotation.y)) {
  46849. this.rotation.y = 0;
  46850. }
  46851. if (isNaN(this.rotation.z)) {
  46852. this.rotation.z = 0;
  46853. }
  46854. if (this.rotationQuaternion) {
  46855. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46856. }
  46857. };
  46858. /**
  46859. * Return the current target position of the camera. This value is expressed in local space.
  46860. * @returns the target position
  46861. */
  46862. TargetCamera.prototype.getTarget = function () {
  46863. return this._currentTarget;
  46864. };
  46865. /** @hidden */
  46866. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46867. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46868. };
  46869. /** @hidden */
  46870. TargetCamera.prototype._updatePosition = function () {
  46871. if (this.parent) {
  46872. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46873. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46874. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46875. return;
  46876. }
  46877. this.position.addInPlace(this.cameraDirection);
  46878. };
  46879. /** @hidden */
  46880. TargetCamera.prototype._checkInputs = function () {
  46881. var needToMove = this._decideIfNeedsToMove();
  46882. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46883. // Move
  46884. if (needToMove) {
  46885. this._updatePosition();
  46886. }
  46887. // Rotate
  46888. if (needToRotate) {
  46889. this.rotation.x += this.cameraRotation.x;
  46890. this.rotation.y += this.cameraRotation.y;
  46891. //rotate, if quaternion is set and rotation was used
  46892. if (this.rotationQuaternion) {
  46893. var len = this.rotation.lengthSquared();
  46894. if (len) {
  46895. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46896. }
  46897. }
  46898. if (!this.noRotationConstraint) {
  46899. var limit = (Math.PI / 2) * 0.95;
  46900. if (this.rotation.x > limit)
  46901. this.rotation.x = limit;
  46902. if (this.rotation.x < -limit)
  46903. this.rotation.x = -limit;
  46904. }
  46905. }
  46906. // Inertia
  46907. if (needToMove) {
  46908. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46909. this.cameraDirection.x = 0;
  46910. }
  46911. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46912. this.cameraDirection.y = 0;
  46913. }
  46914. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46915. this.cameraDirection.z = 0;
  46916. }
  46917. this.cameraDirection.scaleInPlace(this.inertia);
  46918. }
  46919. if (needToRotate) {
  46920. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46921. this.cameraRotation.x = 0;
  46922. }
  46923. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46924. this.cameraRotation.y = 0;
  46925. }
  46926. this.cameraRotation.scaleInPlace(this.inertia);
  46927. }
  46928. _super.prototype._checkInputs.call(this);
  46929. };
  46930. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46931. if (this.rotationQuaternion) {
  46932. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46933. }
  46934. else {
  46935. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46936. }
  46937. };
  46938. /**
  46939. * 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)
  46940. * @returns the current camera
  46941. */
  46942. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46943. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46944. return this;
  46945. };
  46946. /** @hidden */
  46947. TargetCamera.prototype._getViewMatrix = function () {
  46948. if (this.lockedTarget) {
  46949. this.setTarget(this._getLockedTargetPosition());
  46950. }
  46951. // Compute
  46952. this._updateCameraRotationMatrix();
  46953. // Apply the changed rotation to the upVector.
  46954. if (this._cachedRotationZ != this.rotation.z) {
  46955. this._rotateUpVectorWithCameraRotationMatrix();
  46956. this._cachedRotationZ = this.rotation.z;
  46957. }
  46958. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46959. // Computing target and final matrix
  46960. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46961. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46962. return this._viewMatrix;
  46963. };
  46964. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46965. if (this.parent) {
  46966. var parentWorldMatrix = this.parent.getWorldMatrix();
  46967. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46968. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46969. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46970. this._markSyncedWithParent();
  46971. }
  46972. else {
  46973. this._globalPosition.copyFrom(position);
  46974. this._globalCurrentTarget.copyFrom(target);
  46975. this._globalCurrentUpVector.copyFrom(up);
  46976. }
  46977. if (this.getScene().useRightHandedSystem) {
  46978. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46979. }
  46980. else {
  46981. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46982. }
  46983. };
  46984. /**
  46985. * @hidden
  46986. */
  46987. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46988. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46989. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46990. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46991. if (!this.rotationQuaternion) {
  46992. this.rotationQuaternion = new BABYLON.Quaternion();
  46993. }
  46994. rigCamera._cameraRigParams = {};
  46995. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46996. }
  46997. return rigCamera;
  46998. }
  46999. return null;
  47000. };
  47001. /**
  47002. * @hidden
  47003. */
  47004. TargetCamera.prototype._updateRigCameras = function () {
  47005. var camLeft = this._rigCameras[0];
  47006. var camRight = this._rigCameras[1];
  47007. switch (this.cameraRigMode) {
  47008. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47009. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47010. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47011. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47012. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47013. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47014. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47015. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47016. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47017. camLeft.setTarget(this.getTarget());
  47018. camRight.setTarget(this.getTarget());
  47019. break;
  47020. case BABYLON.Camera.RIG_MODE_VR:
  47021. if (camLeft.rotationQuaternion) {
  47022. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47023. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47024. }
  47025. else {
  47026. camLeft.rotation.copyFrom(this.rotation);
  47027. camRight.rotation.copyFrom(this.rotation);
  47028. }
  47029. camLeft.position.copyFrom(this.position);
  47030. camRight.position.copyFrom(this.position);
  47031. break;
  47032. }
  47033. _super.prototype._updateRigCameras.call(this);
  47034. };
  47035. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47036. if (!this._rigCamTransformMatrix) {
  47037. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47038. }
  47039. var target = this.getTarget();
  47040. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47041. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47042. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47043. };
  47044. /**
  47045. * Gets the current object class name.
  47046. * @return the class name
  47047. */
  47048. TargetCamera.prototype.getClassName = function () {
  47049. return "TargetCamera";
  47050. };
  47051. __decorate([
  47052. BABYLON.serializeAsVector3()
  47053. ], TargetCamera.prototype, "rotation", void 0);
  47054. __decorate([
  47055. BABYLON.serialize()
  47056. ], TargetCamera.prototype, "speed", void 0);
  47057. __decorate([
  47058. BABYLON.serializeAsMeshReference("lockedTargetId")
  47059. ], TargetCamera.prototype, "lockedTarget", void 0);
  47060. return TargetCamera;
  47061. }(BABYLON.Camera));
  47062. BABYLON.TargetCamera = TargetCamera;
  47063. })(BABYLON || (BABYLON = {}));
  47064. //# sourceMappingURL=babylon.targetCamera.js.map
  47065. var BABYLON;
  47066. (function (BABYLON) {
  47067. /**
  47068. * Manage the mouse inputs to control the movement of a free camera.
  47069. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47070. */
  47071. var FreeCameraMouseInput = /** @class */ (function () {
  47072. /**
  47073. * Manage the mouse inputs to control the movement of a free camera.
  47074. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47075. * @param touchEnabled Defines if touch is enabled or not
  47076. */
  47077. function FreeCameraMouseInput(
  47078. /**
  47079. * Define if touch is enabled in the mouse input
  47080. */
  47081. touchEnabled) {
  47082. if (touchEnabled === void 0) { touchEnabled = true; }
  47083. this.touchEnabled = touchEnabled;
  47084. /**
  47085. * Defines the buttons associated with the input to handle camera move.
  47086. */
  47087. this.buttons = [0, 1, 2];
  47088. /**
  47089. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  47090. */
  47091. this.angularSensibility = 2000.0;
  47092. this.previousPosition = null;
  47093. }
  47094. /**
  47095. * Attach the input controls to a specific dom element to get the input from.
  47096. * @param element Defines the element the controls should be listened from
  47097. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47098. */
  47099. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47100. var _this = this;
  47101. var engine = this.camera.getEngine();
  47102. if (!this._pointerInput) {
  47103. this._pointerInput = function (p, s) {
  47104. var evt = p.event;
  47105. if (engine.isInVRExclusivePointerMode) {
  47106. return;
  47107. }
  47108. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47109. return;
  47110. }
  47111. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47112. return;
  47113. }
  47114. var srcElement = (evt.srcElement || evt.target);
  47115. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47116. try {
  47117. srcElement.setPointerCapture(evt.pointerId);
  47118. }
  47119. catch (e) {
  47120. //Nothing to do with the error. Execution will continue.
  47121. }
  47122. _this.previousPosition = {
  47123. x: evt.clientX,
  47124. y: evt.clientY
  47125. };
  47126. if (!noPreventDefault) {
  47127. evt.preventDefault();
  47128. element.focus();
  47129. }
  47130. }
  47131. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47132. try {
  47133. srcElement.releasePointerCapture(evt.pointerId);
  47134. }
  47135. catch (e) {
  47136. //Nothing to do with the error.
  47137. }
  47138. _this.previousPosition = null;
  47139. if (!noPreventDefault) {
  47140. evt.preventDefault();
  47141. }
  47142. }
  47143. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47144. if (!_this.previousPosition || engine.isPointerLock) {
  47145. return;
  47146. }
  47147. var offsetX = evt.clientX - _this.previousPosition.x;
  47148. if (_this.camera.getScene().useRightHandedSystem)
  47149. offsetX *= -1;
  47150. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47151. offsetX *= -1;
  47152. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47153. var offsetY = evt.clientY - _this.previousPosition.y;
  47154. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47155. _this.previousPosition = {
  47156. x: evt.clientX,
  47157. y: evt.clientY
  47158. };
  47159. if (!noPreventDefault) {
  47160. evt.preventDefault();
  47161. }
  47162. }
  47163. };
  47164. }
  47165. this._onMouseMove = function (evt) {
  47166. if (!engine.isPointerLock) {
  47167. return;
  47168. }
  47169. if (engine.isInVRExclusivePointerMode) {
  47170. return;
  47171. }
  47172. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47173. if (_this.camera.getScene().useRightHandedSystem)
  47174. offsetX *= -1;
  47175. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47176. offsetX *= -1;
  47177. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47178. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47179. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47180. _this.previousPosition = null;
  47181. if (!noPreventDefault) {
  47182. evt.preventDefault();
  47183. }
  47184. };
  47185. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47186. element.addEventListener("mousemove", this._onMouseMove, false);
  47187. };
  47188. /**
  47189. * Detach the current controls from the specified dom element.
  47190. * @param element Defines the element to stop listening the inputs from
  47191. */
  47192. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47193. if (this._observer && element) {
  47194. this.camera.getScene().onPointerObservable.remove(this._observer);
  47195. if (this._onMouseMove) {
  47196. element.removeEventListener("mousemove", this._onMouseMove);
  47197. }
  47198. this._observer = null;
  47199. this._onMouseMove = null;
  47200. this.previousPosition = null;
  47201. }
  47202. };
  47203. /**
  47204. * Gets the class name of the current intput.
  47205. * @returns the class name
  47206. */
  47207. FreeCameraMouseInput.prototype.getClassName = function () {
  47208. return "FreeCameraMouseInput";
  47209. };
  47210. /**
  47211. * Get the friendly name associated with the input class.
  47212. * @returns the input friendly name
  47213. */
  47214. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47215. return "mouse";
  47216. };
  47217. __decorate([
  47218. BABYLON.serialize()
  47219. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47220. __decorate([
  47221. BABYLON.serialize()
  47222. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47223. return FreeCameraMouseInput;
  47224. }());
  47225. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47226. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47227. })(BABYLON || (BABYLON = {}));
  47228. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47229. var BABYLON;
  47230. (function (BABYLON) {
  47231. /**
  47232. * Manage the keyboard inputs to control the movement of a free camera.
  47233. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47234. */
  47235. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47236. function FreeCameraKeyboardMoveInput() {
  47237. /**
  47238. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  47239. */
  47240. this.keysUp = [38];
  47241. /**
  47242. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  47243. */
  47244. this.keysDown = [40];
  47245. /**
  47246. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  47247. */
  47248. this.keysLeft = [37];
  47249. /**
  47250. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  47251. */
  47252. this.keysRight = [39];
  47253. this._keys = new Array();
  47254. }
  47255. /**
  47256. * Attach the input controls to a specific dom element to get the input from.
  47257. * @param element Defines the element the controls should be listened from
  47258. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47259. */
  47260. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47261. var _this = this;
  47262. if (this._onCanvasBlurObserver) {
  47263. return;
  47264. }
  47265. this._scene = this.camera.getScene();
  47266. this._engine = this._scene.getEngine();
  47267. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47268. _this._keys = [];
  47269. });
  47270. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47271. var evt = info.event;
  47272. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47273. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47274. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47275. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47276. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47277. var index = _this._keys.indexOf(evt.keyCode);
  47278. if (index === -1) {
  47279. _this._keys.push(evt.keyCode);
  47280. }
  47281. if (!noPreventDefault) {
  47282. evt.preventDefault();
  47283. }
  47284. }
  47285. }
  47286. else {
  47287. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47288. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47289. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47290. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47291. var index = _this._keys.indexOf(evt.keyCode);
  47292. if (index >= 0) {
  47293. _this._keys.splice(index, 1);
  47294. }
  47295. if (!noPreventDefault) {
  47296. evt.preventDefault();
  47297. }
  47298. }
  47299. }
  47300. });
  47301. };
  47302. /**
  47303. * Detach the current controls from the specified dom element.
  47304. * @param element Defines the element to stop listening the inputs from
  47305. */
  47306. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47307. if (this._scene) {
  47308. if (this._onKeyboardObserver) {
  47309. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47310. }
  47311. if (this._onCanvasBlurObserver) {
  47312. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47313. }
  47314. this._onKeyboardObserver = null;
  47315. this._onCanvasBlurObserver = null;
  47316. }
  47317. this._keys = [];
  47318. };
  47319. /**
  47320. * Update the current camera state depending on the inputs that have been used this frame.
  47321. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  47322. */
  47323. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47324. if (this._onKeyboardObserver) {
  47325. var camera = this.camera;
  47326. // Keyboard
  47327. for (var index = 0; index < this._keys.length; index++) {
  47328. var keyCode = this._keys[index];
  47329. var speed = camera._computeLocalCameraSpeed();
  47330. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47331. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47332. }
  47333. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47334. camera._localDirection.copyFromFloats(0, 0, speed);
  47335. }
  47336. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47337. camera._localDirection.copyFromFloats(speed, 0, 0);
  47338. }
  47339. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47340. camera._localDirection.copyFromFloats(0, 0, -speed);
  47341. }
  47342. if (camera.getScene().useRightHandedSystem) {
  47343. camera._localDirection.z *= -1;
  47344. }
  47345. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47346. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47347. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47348. }
  47349. }
  47350. };
  47351. /**
  47352. * Gets the class name of the current intput.
  47353. * @returns the class name
  47354. */
  47355. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47356. return "FreeCameraKeyboardMoveInput";
  47357. };
  47358. /** @hidden */
  47359. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47360. this._keys = [];
  47361. };
  47362. /**
  47363. * Get the friendly name associated with the input class.
  47364. * @returns the input friendly name
  47365. */
  47366. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47367. return "keyboard";
  47368. };
  47369. __decorate([
  47370. BABYLON.serialize()
  47371. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47372. __decorate([
  47373. BABYLON.serialize()
  47374. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47375. __decorate([
  47376. BABYLON.serialize()
  47377. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47378. __decorate([
  47379. BABYLON.serialize()
  47380. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47381. return FreeCameraKeyboardMoveInput;
  47382. }());
  47383. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47384. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47385. })(BABYLON || (BABYLON = {}));
  47386. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47387. var BABYLON;
  47388. (function (BABYLON) {
  47389. /**
  47390. * Default Inputs manager for the FreeCamera.
  47391. * It groups all the default supported inputs for ease of use.
  47392. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47393. */
  47394. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47395. __extends(FreeCameraInputsManager, _super);
  47396. /**
  47397. * Instantiates a new FreeCameraInputsManager.
  47398. * @param camera Defines the camera the inputs belong to
  47399. */
  47400. function FreeCameraInputsManager(camera) {
  47401. return _super.call(this, camera) || this;
  47402. }
  47403. /**
  47404. * Add keyboard input support to the input manager.
  47405. * @returns the current input manager
  47406. */
  47407. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47408. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47409. return this;
  47410. };
  47411. /**
  47412. * Add mouse input support to the input manager.
  47413. * @returns the current input manager
  47414. */
  47415. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47416. if (touchEnabled === void 0) { touchEnabled = true; }
  47417. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47418. return this;
  47419. };
  47420. /**
  47421. * Add orientation input support to the input manager.
  47422. * @returns the current input manager
  47423. */
  47424. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47425. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47426. return this;
  47427. };
  47428. /**
  47429. * Add touch input support to the input manager.
  47430. * @returns the current input manager
  47431. */
  47432. FreeCameraInputsManager.prototype.addTouch = function () {
  47433. this.add(new BABYLON.FreeCameraTouchInput());
  47434. return this;
  47435. };
  47436. /**
  47437. * Add virtual joystick input support to the input manager.
  47438. * @returns the current input manager
  47439. */
  47440. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47441. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47442. return this;
  47443. };
  47444. return FreeCameraInputsManager;
  47445. }(BABYLON.CameraInputsManager));
  47446. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47447. })(BABYLON || (BABYLON = {}));
  47448. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47449. var BABYLON;
  47450. (function (BABYLON) {
  47451. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  47452. // Forcing to use the Universal camera
  47453. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  47454. });
  47455. /**
  47456. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  47457. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  47458. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  47459. */
  47460. var FreeCamera = /** @class */ (function (_super) {
  47461. __extends(FreeCamera, _super);
  47462. /**
  47463. * Instantiates a Free Camera.
  47464. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  47465. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  47466. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  47467. * @param name Define the name of the camera in the scene
  47468. * @param position Define the start position of the camera in the scene
  47469. * @param scene Define the scene the camera belongs to
  47470. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47471. */
  47472. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47473. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47474. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47475. /**
  47476. * Define the collision ellipsoid of the camera.
  47477. * This is helpful to simulate a camera body like the player body around the camera
  47478. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  47479. */
  47480. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47481. /**
  47482. * Define an offset for the position of the ellipsoid around the camera.
  47483. * This can be helpful to determine the center of the body near the gravity center of the body
  47484. * instead of its head.
  47485. */
  47486. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47487. /**
  47488. * Enable or disable collisions of the camera with the rest of the scene objects.
  47489. */
  47490. _this.checkCollisions = false;
  47491. /**
  47492. * Enable or disable gravity on the camera.
  47493. */
  47494. _this.applyGravity = false;
  47495. _this._needMoveForGravity = false;
  47496. _this._oldPosition = BABYLON.Vector3.Zero();
  47497. _this._diffPosition = BABYLON.Vector3.Zero();
  47498. _this._newPosition = BABYLON.Vector3.Zero();
  47499. // Collisions
  47500. _this._collisionMask = -1;
  47501. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47502. if (collidedMesh === void 0) { collidedMesh = null; }
  47503. //TODO move this to the collision coordinator!
  47504. if (_this.getScene().workerCollisions)
  47505. newPosition.multiplyInPlace(_this._collider._radius);
  47506. var updatePosition = function (newPos) {
  47507. _this._newPosition.copyFrom(newPos);
  47508. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47509. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47510. _this.position.addInPlace(_this._diffPosition);
  47511. if (_this.onCollide && collidedMesh) {
  47512. _this.onCollide(collidedMesh);
  47513. }
  47514. }
  47515. };
  47516. updatePosition(newPosition);
  47517. };
  47518. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47519. _this.inputs.addKeyboard().addMouse();
  47520. return _this;
  47521. }
  47522. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47523. /**
  47524. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47525. * Higher values reduce sensitivity.
  47526. */
  47527. get: function () {
  47528. var mouse = this.inputs.attached["mouse"];
  47529. if (mouse)
  47530. return mouse.angularSensibility;
  47531. return 0;
  47532. },
  47533. /**
  47534. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47535. * Higher values reduce sensitivity.
  47536. */
  47537. set: function (value) {
  47538. var mouse = this.inputs.attached["mouse"];
  47539. if (mouse)
  47540. mouse.angularSensibility = value;
  47541. },
  47542. enumerable: true,
  47543. configurable: true
  47544. });
  47545. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47546. /**
  47547. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  47548. */
  47549. get: function () {
  47550. var keyboard = this.inputs.attached["keyboard"];
  47551. if (keyboard)
  47552. return keyboard.keysUp;
  47553. return [];
  47554. },
  47555. set: function (value) {
  47556. var keyboard = this.inputs.attached["keyboard"];
  47557. if (keyboard)
  47558. keyboard.keysUp = value;
  47559. },
  47560. enumerable: true,
  47561. configurable: true
  47562. });
  47563. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47564. /**
  47565. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  47566. */
  47567. get: function () {
  47568. var keyboard = this.inputs.attached["keyboard"];
  47569. if (keyboard)
  47570. return keyboard.keysDown;
  47571. return [];
  47572. },
  47573. set: function (value) {
  47574. var keyboard = this.inputs.attached["keyboard"];
  47575. if (keyboard)
  47576. keyboard.keysDown = value;
  47577. },
  47578. enumerable: true,
  47579. configurable: true
  47580. });
  47581. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47582. /**
  47583. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  47584. */
  47585. get: function () {
  47586. var keyboard = this.inputs.attached["keyboard"];
  47587. if (keyboard)
  47588. return keyboard.keysLeft;
  47589. return [];
  47590. },
  47591. set: function (value) {
  47592. var keyboard = this.inputs.attached["keyboard"];
  47593. if (keyboard)
  47594. keyboard.keysLeft = value;
  47595. },
  47596. enumerable: true,
  47597. configurable: true
  47598. });
  47599. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47600. /**
  47601. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  47602. */
  47603. get: function () {
  47604. var keyboard = this.inputs.attached["keyboard"];
  47605. if (keyboard)
  47606. return keyboard.keysRight;
  47607. return [];
  47608. },
  47609. set: function (value) {
  47610. var keyboard = this.inputs.attached["keyboard"];
  47611. if (keyboard)
  47612. keyboard.keysRight = value;
  47613. },
  47614. enumerable: true,
  47615. configurable: true
  47616. });
  47617. /**
  47618. * Attached controls to the current camera.
  47619. * @param element Defines the element the controls should be listened from
  47620. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47621. */
  47622. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47623. this.inputs.attachElement(element, noPreventDefault);
  47624. };
  47625. /**
  47626. * Detach the current controls from the camera.
  47627. * The camera will stop reacting to inputs.
  47628. * @param element Defines the element to stop listening the inputs from
  47629. */
  47630. FreeCamera.prototype.detachControl = function (element) {
  47631. this.inputs.detachElement(element);
  47632. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47633. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47634. };
  47635. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47636. /**
  47637. * Define a collision mask to limit the list of object the camera can collide with
  47638. */
  47639. get: function () {
  47640. return this._collisionMask;
  47641. },
  47642. set: function (mask) {
  47643. this._collisionMask = !isNaN(mask) ? mask : -1;
  47644. },
  47645. enumerable: true,
  47646. configurable: true
  47647. });
  47648. /** @hidden */
  47649. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47650. var globalPosition;
  47651. if (this.parent) {
  47652. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47653. }
  47654. else {
  47655. globalPosition = this.position;
  47656. }
  47657. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47658. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47659. if (!this._collider) {
  47660. this._collider = new BABYLON.Collider();
  47661. }
  47662. this._collider._radius = this.ellipsoid;
  47663. this._collider.collisionMask = this._collisionMask;
  47664. //no need for clone, as long as gravity is not on.
  47665. var actualDisplacement = displacement;
  47666. //add gravity to the direction to prevent the dual-collision checking
  47667. if (this.applyGravity) {
  47668. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47669. actualDisplacement = displacement.add(this.getScene().gravity);
  47670. }
  47671. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47672. };
  47673. /** @hidden */
  47674. FreeCamera.prototype._checkInputs = function () {
  47675. if (!this._localDirection) {
  47676. this._localDirection = BABYLON.Vector3.Zero();
  47677. this._transformedDirection = BABYLON.Vector3.Zero();
  47678. }
  47679. this.inputs.checkInputs();
  47680. _super.prototype._checkInputs.call(this);
  47681. };
  47682. /** @hidden */
  47683. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47684. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47685. };
  47686. /** @hidden */
  47687. FreeCamera.prototype._updatePosition = function () {
  47688. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47689. this._collideWithWorld(this.cameraDirection);
  47690. }
  47691. else {
  47692. _super.prototype._updatePosition.call(this);
  47693. }
  47694. };
  47695. /**
  47696. * Destroy the camera and release the current resources hold by it.
  47697. */
  47698. FreeCamera.prototype.dispose = function () {
  47699. this.inputs.clear();
  47700. _super.prototype.dispose.call(this);
  47701. };
  47702. /**
  47703. * Gets the current object class name.
  47704. * @return the class name
  47705. */
  47706. FreeCamera.prototype.getClassName = function () {
  47707. return "FreeCamera";
  47708. };
  47709. __decorate([
  47710. BABYLON.serializeAsVector3()
  47711. ], FreeCamera.prototype, "ellipsoid", void 0);
  47712. __decorate([
  47713. BABYLON.serializeAsVector3()
  47714. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47715. __decorate([
  47716. BABYLON.serialize()
  47717. ], FreeCamera.prototype, "checkCollisions", void 0);
  47718. __decorate([
  47719. BABYLON.serialize()
  47720. ], FreeCamera.prototype, "applyGravity", void 0);
  47721. return FreeCamera;
  47722. }(BABYLON.TargetCamera));
  47723. BABYLON.FreeCamera = FreeCamera;
  47724. })(BABYLON || (BABYLON = {}));
  47725. //# sourceMappingURL=babylon.freeCamera.js.map
  47726. var BABYLON;
  47727. (function (BABYLON) {
  47728. /**
  47729. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  47730. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47731. */
  47732. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47733. function ArcRotateCameraKeyboardMoveInput() {
  47734. /**
  47735. * Defines the list of key codes associated with the up action (increase alpha)
  47736. */
  47737. this.keysUp = [38];
  47738. /**
  47739. * Defines the list of key codes associated with the down action (decrease alpha)
  47740. */
  47741. this.keysDown = [40];
  47742. /**
  47743. * Defines the list of key codes associated with the left action (increase beta)
  47744. */
  47745. this.keysLeft = [37];
  47746. /**
  47747. * Defines the list of key codes associated with the right action (decrease beta)
  47748. */
  47749. this.keysRight = [39];
  47750. /**
  47751. * Defines the list of key codes associated with the reset action.
  47752. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  47753. */
  47754. this.keysReset = [220];
  47755. /**
  47756. * Defines the panning sensibility of the inputs.
  47757. * (How fast is the camera paning)
  47758. */
  47759. this.panningSensibility = 50.0;
  47760. /**
  47761. * Defines the zooming sensibility of the inputs.
  47762. * (How fast is the camera zooming)
  47763. */
  47764. this.zoomingSensibility = 25.0;
  47765. /**
  47766. * Defines wether maintaining the alt key down switch the movement mode from
  47767. * orientation to zoom.
  47768. */
  47769. this.useAltToZoom = true;
  47770. this._keys = new Array();
  47771. }
  47772. /**
  47773. * Attach the input controls to a specific dom element to get the input from.
  47774. * @param element Defines the element the controls should be listened from
  47775. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47776. */
  47777. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47778. var _this = this;
  47779. if (this._onCanvasBlurObserver) {
  47780. return;
  47781. }
  47782. this._scene = this.camera.getScene();
  47783. this._engine = this._scene.getEngine();
  47784. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47785. _this._keys = [];
  47786. });
  47787. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47788. var evt = info.event;
  47789. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47790. _this._ctrlPressed = evt.ctrlKey;
  47791. _this._altPressed = evt.altKey;
  47792. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47793. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47794. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47795. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47796. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47797. var index = _this._keys.indexOf(evt.keyCode);
  47798. if (index === -1) {
  47799. _this._keys.push(evt.keyCode);
  47800. }
  47801. if (evt.preventDefault) {
  47802. if (!noPreventDefault) {
  47803. evt.preventDefault();
  47804. }
  47805. }
  47806. }
  47807. }
  47808. else {
  47809. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47810. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47811. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47812. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47813. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47814. var index = _this._keys.indexOf(evt.keyCode);
  47815. if (index >= 0) {
  47816. _this._keys.splice(index, 1);
  47817. }
  47818. if (evt.preventDefault) {
  47819. if (!noPreventDefault) {
  47820. evt.preventDefault();
  47821. }
  47822. }
  47823. }
  47824. }
  47825. });
  47826. };
  47827. /**
  47828. * Detach the current controls from the specified dom element.
  47829. * @param element Defines the element to stop listening the inputs from
  47830. */
  47831. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47832. if (this._scene) {
  47833. if (this._onKeyboardObserver) {
  47834. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47835. }
  47836. if (this._onCanvasBlurObserver) {
  47837. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47838. }
  47839. this._onKeyboardObserver = null;
  47840. this._onCanvasBlurObserver = null;
  47841. }
  47842. this._keys = [];
  47843. };
  47844. /**
  47845. * Update the current camera state depending on the inputs that have been used this frame.
  47846. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  47847. */
  47848. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47849. if (this._onKeyboardObserver) {
  47850. var camera = this.camera;
  47851. for (var index = 0; index < this._keys.length; index++) {
  47852. var keyCode = this._keys[index];
  47853. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47854. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47855. camera.inertialPanningX -= 1 / this.panningSensibility;
  47856. }
  47857. else {
  47858. camera.inertialAlphaOffset -= 0.01;
  47859. }
  47860. }
  47861. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47862. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47863. camera.inertialPanningY += 1 / this.panningSensibility;
  47864. }
  47865. else if (this._altPressed && this.useAltToZoom) {
  47866. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47867. }
  47868. else {
  47869. camera.inertialBetaOffset -= 0.01;
  47870. }
  47871. }
  47872. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47873. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47874. camera.inertialPanningX += 1 / this.panningSensibility;
  47875. }
  47876. else {
  47877. camera.inertialAlphaOffset += 0.01;
  47878. }
  47879. }
  47880. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47881. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47882. camera.inertialPanningY -= 1 / this.panningSensibility;
  47883. }
  47884. else if (this._altPressed && this.useAltToZoom) {
  47885. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47886. }
  47887. else {
  47888. camera.inertialBetaOffset += 0.01;
  47889. }
  47890. }
  47891. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47892. if (camera.useInputToRestoreState) {
  47893. camera.restoreState();
  47894. }
  47895. }
  47896. }
  47897. }
  47898. };
  47899. /**
  47900. * Gets the class name of the current intput.
  47901. * @returns the class name
  47902. */
  47903. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47904. return "ArcRotateCameraKeyboardMoveInput";
  47905. };
  47906. /**
  47907. * Get the friendly name associated with the input class.
  47908. * @returns the input friendly name
  47909. */
  47910. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47911. return "keyboard";
  47912. };
  47913. __decorate([
  47914. BABYLON.serialize()
  47915. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47916. __decorate([
  47917. BABYLON.serialize()
  47918. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47919. __decorate([
  47920. BABYLON.serialize()
  47921. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47922. __decorate([
  47923. BABYLON.serialize()
  47924. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47925. __decorate([
  47926. BABYLON.serialize()
  47927. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47928. __decorate([
  47929. BABYLON.serialize()
  47930. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47931. __decorate([
  47932. BABYLON.serialize()
  47933. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47934. __decorate([
  47935. BABYLON.serialize()
  47936. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47937. return ArcRotateCameraKeyboardMoveInput;
  47938. }());
  47939. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47940. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47941. })(BABYLON || (BABYLON = {}));
  47942. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47943. var BABYLON;
  47944. (function (BABYLON) {
  47945. /**
  47946. * Manage the mouse wheel inputs to control an arc rotate camera.
  47947. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47948. */
  47949. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47950. function ArcRotateCameraMouseWheelInput() {
  47951. /**
  47952. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  47953. */
  47954. this.wheelPrecision = 3.0;
  47955. /**
  47956. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47957. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47958. */
  47959. this.wheelDeltaPercentage = 0;
  47960. }
  47961. /**
  47962. * Attach the input controls to a specific dom element to get the input from.
  47963. * @param element Defines the element the controls should be listened from
  47964. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47965. */
  47966. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47967. var _this = this;
  47968. this._wheel = function (p, s) {
  47969. //sanity check - this should be a PointerWheel event.
  47970. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47971. return;
  47972. var event = p.event;
  47973. var delta = 0;
  47974. if (event.wheelDelta) {
  47975. if (_this.wheelDeltaPercentage) {
  47976. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47977. if (event.wheelDelta > 0) {
  47978. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47979. }
  47980. else {
  47981. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47982. }
  47983. }
  47984. else {
  47985. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47986. }
  47987. }
  47988. else if (event.detail) {
  47989. delta = -event.detail / _this.wheelPrecision;
  47990. }
  47991. if (delta)
  47992. _this.camera.inertialRadiusOffset += delta;
  47993. if (event.preventDefault) {
  47994. if (!noPreventDefault) {
  47995. event.preventDefault();
  47996. }
  47997. }
  47998. };
  47999. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48000. };
  48001. /**
  48002. * Detach the current controls from the specified dom element.
  48003. * @param element Defines the element to stop listening the inputs from
  48004. */
  48005. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48006. if (this._observer && element) {
  48007. this.camera.getScene().onPointerObservable.remove(this._observer);
  48008. this._observer = null;
  48009. this._wheel = null;
  48010. }
  48011. };
  48012. /**
  48013. * Gets the class name of the current intput.
  48014. * @returns the class name
  48015. */
  48016. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48017. return "ArcRotateCameraMouseWheelInput";
  48018. };
  48019. /**
  48020. * Get the friendly name associated with the input class.
  48021. * @returns the input friendly name
  48022. */
  48023. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48024. return "mousewheel";
  48025. };
  48026. __decorate([
  48027. BABYLON.serialize()
  48028. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48029. __decorate([
  48030. BABYLON.serialize()
  48031. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48032. return ArcRotateCameraMouseWheelInput;
  48033. }());
  48034. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48035. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48036. })(BABYLON || (BABYLON = {}));
  48037. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48038. var BABYLON;
  48039. (function (BABYLON) {
  48040. /**
  48041. * Manage the pointers inputs to control an arc rotate camera.
  48042. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48043. */
  48044. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48045. function ArcRotateCameraPointersInput() {
  48046. /**
  48047. * Defines the buttons associated with the input to handle camera move.
  48048. */
  48049. this.buttons = [0, 1, 2];
  48050. /**
  48051. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  48052. */
  48053. this.angularSensibilityX = 1000.0;
  48054. /**
  48055. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  48056. */
  48057. this.angularSensibilityY = 1000.0;
  48058. /**
  48059. * Defines the pointer pinch precision or how fast is the camera zooming.
  48060. */
  48061. this.pinchPrecision = 12.0;
  48062. /**
  48063. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48064. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48065. */
  48066. this.pinchDeltaPercentage = 0;
  48067. /**
  48068. * Defines the pointer panning sensibility or how fast is the camera moving.
  48069. */
  48070. this.panningSensibility = 1000.0;
  48071. /**
  48072. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  48073. */
  48074. this.multiTouchPanning = true;
  48075. /**
  48076. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  48077. */
  48078. this.multiTouchPanAndZoom = true;
  48079. /**
  48080. * Revers pinch action direction.
  48081. */
  48082. this.pinchInwards = true;
  48083. this._isPanClick = false;
  48084. }
  48085. /**
  48086. * Attach the input controls to a specific dom element to get the input from.
  48087. * @param element Defines the element the controls should be listened from
  48088. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48089. */
  48090. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48091. var _this = this;
  48092. var engine = this.camera.getEngine();
  48093. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48094. var pointA = null;
  48095. var pointB = null;
  48096. var previousPinchSquaredDistance = 0;
  48097. var initialDistance = 0;
  48098. var twoFingerActivityCount = 0;
  48099. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48100. this._pointerInput = function (p, s) {
  48101. var evt = p.event;
  48102. var isTouch = p.event.pointerType === "touch";
  48103. if (engine.isInVRExclusivePointerMode) {
  48104. return;
  48105. }
  48106. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48107. return;
  48108. }
  48109. var srcElement = (evt.srcElement || evt.target);
  48110. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48111. try {
  48112. srcElement.setPointerCapture(evt.pointerId);
  48113. }
  48114. catch (e) {
  48115. //Nothing to do with the error. Execution will continue.
  48116. }
  48117. // Manage panning with pan button click
  48118. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48119. // manage pointers
  48120. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48121. if (pointA === null) {
  48122. pointA = cacheSoloPointer;
  48123. }
  48124. else if (pointB === null) {
  48125. pointB = cacheSoloPointer;
  48126. }
  48127. if (!noPreventDefault) {
  48128. evt.preventDefault();
  48129. element.focus();
  48130. }
  48131. }
  48132. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48133. if (_this.camera.useInputToRestoreState) {
  48134. _this.camera.restoreState();
  48135. }
  48136. }
  48137. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48138. try {
  48139. srcElement.releasePointerCapture(evt.pointerId);
  48140. }
  48141. catch (e) {
  48142. //Nothing to do with the error.
  48143. }
  48144. cacheSoloPointer = null;
  48145. previousPinchSquaredDistance = 0;
  48146. previousMultiTouchPanPosition.isPaning = false;
  48147. previousMultiTouchPanPosition.isPinching = false;
  48148. twoFingerActivityCount = 0;
  48149. initialDistance = 0;
  48150. if (!isTouch) {
  48151. pointB = null; // Mouse and pen are mono pointer
  48152. }
  48153. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48154. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48155. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48156. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48157. if (engine._badOS) {
  48158. pointA = pointB = null;
  48159. }
  48160. else {
  48161. //only remove the impacted pointer in case of multitouch allowing on most
  48162. //platforms switching from rotate to zoom and pan seamlessly.
  48163. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48164. pointA = pointB;
  48165. pointB = null;
  48166. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48167. }
  48168. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48169. pointB = null;
  48170. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48171. }
  48172. else {
  48173. pointA = pointB = null;
  48174. }
  48175. }
  48176. if (!noPreventDefault) {
  48177. evt.preventDefault();
  48178. }
  48179. }
  48180. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48181. if (!noPreventDefault) {
  48182. evt.preventDefault();
  48183. }
  48184. // One button down
  48185. if (pointA && pointB === null && cacheSoloPointer) {
  48186. if (_this.panningSensibility !== 0 &&
  48187. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48188. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48189. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48190. }
  48191. else {
  48192. var offsetX = evt.clientX - cacheSoloPointer.x;
  48193. var offsetY = evt.clientY - cacheSoloPointer.y;
  48194. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48195. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48196. }
  48197. cacheSoloPointer.x = evt.clientX;
  48198. cacheSoloPointer.y = evt.clientY;
  48199. }
  48200. // Two buttons down: pinch/pan
  48201. else if (pointA && pointB) {
  48202. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48203. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48204. ed.x = evt.clientX;
  48205. ed.y = evt.clientY;
  48206. var direction = _this.pinchInwards ? 1 : -1;
  48207. var distX = pointA.x - pointB.x;
  48208. var distY = pointA.y - pointB.y;
  48209. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48210. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48211. if (previousPinchSquaredDistance === 0) {
  48212. initialDistance = pinchDistance;
  48213. previousPinchSquaredDistance = pinchSquaredDistance;
  48214. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48215. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48216. return;
  48217. }
  48218. if (_this.multiTouchPanAndZoom) {
  48219. if (_this.pinchDeltaPercentage) {
  48220. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48221. }
  48222. else {
  48223. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48224. (_this.pinchPrecision *
  48225. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48226. direction);
  48227. }
  48228. if (_this.panningSensibility !== 0) {
  48229. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48230. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48231. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48232. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48233. previousMultiTouchPanPosition.x = pointersCenterX;
  48234. previousMultiTouchPanPosition.y = pointersCenterY;
  48235. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48236. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48237. }
  48238. }
  48239. else {
  48240. twoFingerActivityCount++;
  48241. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48242. if (_this.pinchDeltaPercentage) {
  48243. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48244. }
  48245. else {
  48246. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48247. (_this.pinchPrecision *
  48248. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48249. direction);
  48250. }
  48251. previousMultiTouchPanPosition.isPaning = false;
  48252. previousMultiTouchPanPosition.isPinching = true;
  48253. }
  48254. else {
  48255. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48256. if (!previousMultiTouchPanPosition.isPaning) {
  48257. previousMultiTouchPanPosition.isPaning = true;
  48258. previousMultiTouchPanPosition.isPinching = false;
  48259. previousMultiTouchPanPosition.x = ed.x;
  48260. previousMultiTouchPanPosition.y = ed.y;
  48261. return;
  48262. }
  48263. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48264. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48265. }
  48266. }
  48267. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48268. previousMultiTouchPanPosition.x = ed.x;
  48269. previousMultiTouchPanPosition.y = ed.y;
  48270. }
  48271. }
  48272. previousPinchSquaredDistance = pinchSquaredDistance;
  48273. }
  48274. }
  48275. };
  48276. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  48277. this._onContextMenu = function (evt) {
  48278. evt.preventDefault();
  48279. };
  48280. if (!this.camera._useCtrlForPanning) {
  48281. element.addEventListener("contextmenu", this._onContextMenu, false);
  48282. }
  48283. this._onLostFocus = function () {
  48284. //this._keys = [];
  48285. pointA = pointB = null;
  48286. previousPinchSquaredDistance = 0;
  48287. previousMultiTouchPanPosition.isPaning = false;
  48288. previousMultiTouchPanPosition.isPinching = false;
  48289. twoFingerActivityCount = 0;
  48290. cacheSoloPointer = null;
  48291. initialDistance = 0;
  48292. };
  48293. this._onMouseMove = function (evt) {
  48294. if (!engine.isPointerLock) {
  48295. return;
  48296. }
  48297. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48298. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48299. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48300. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48301. if (!noPreventDefault) {
  48302. evt.preventDefault();
  48303. }
  48304. };
  48305. this._onGestureStart = function (e) {
  48306. if (window.MSGesture === undefined) {
  48307. return;
  48308. }
  48309. if (!_this._MSGestureHandler) {
  48310. _this._MSGestureHandler = new MSGesture();
  48311. _this._MSGestureHandler.target = element;
  48312. }
  48313. _this._MSGestureHandler.addPointer(e.pointerId);
  48314. };
  48315. this._onGesture = function (e) {
  48316. _this.camera.radius *= e.scale;
  48317. if (e.preventDefault) {
  48318. if (!noPreventDefault) {
  48319. e.stopPropagation();
  48320. e.preventDefault();
  48321. }
  48322. }
  48323. };
  48324. element.addEventListener("mousemove", this._onMouseMove, false);
  48325. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48326. element.addEventListener("MSGestureChange", this._onGesture, false);
  48327. BABYLON.Tools.RegisterTopRootEvents([
  48328. { name: "blur", handler: this._onLostFocus }
  48329. ]);
  48330. };
  48331. /**
  48332. * Detach the current controls from the specified dom element.
  48333. * @param element Defines the element to stop listening the inputs from
  48334. */
  48335. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48336. if (this._onLostFocus) {
  48337. BABYLON.Tools.UnregisterTopRootEvents([
  48338. { name: "blur", handler: this._onLostFocus }
  48339. ]);
  48340. }
  48341. if (element && this._observer) {
  48342. this.camera.getScene().onPointerObservable.remove(this._observer);
  48343. this._observer = null;
  48344. if (this._onContextMenu) {
  48345. element.removeEventListener("contextmenu", this._onContextMenu);
  48346. }
  48347. if (this._onMouseMove) {
  48348. element.removeEventListener("mousemove", this._onMouseMove);
  48349. }
  48350. if (this._onGestureStart) {
  48351. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48352. }
  48353. if (this._onGesture) {
  48354. element.removeEventListener("MSGestureChange", this._onGesture);
  48355. }
  48356. this._isPanClick = false;
  48357. this.pinchInwards = true;
  48358. this._onMouseMove = null;
  48359. this._onGestureStart = null;
  48360. this._onGesture = null;
  48361. this._MSGestureHandler = null;
  48362. this._onLostFocus = null;
  48363. this._onContextMenu = null;
  48364. }
  48365. };
  48366. /**
  48367. * Gets the class name of the current intput.
  48368. * @returns the class name
  48369. */
  48370. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48371. return "ArcRotateCameraPointersInput";
  48372. };
  48373. /**
  48374. * Get the friendly name associated with the input class.
  48375. * @returns the input friendly name
  48376. */
  48377. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48378. return "pointers";
  48379. };
  48380. __decorate([
  48381. BABYLON.serialize()
  48382. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48383. __decorate([
  48384. BABYLON.serialize()
  48385. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48386. __decorate([
  48387. BABYLON.serialize()
  48388. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48389. __decorate([
  48390. BABYLON.serialize()
  48391. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48392. __decorate([
  48393. BABYLON.serialize()
  48394. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48395. __decorate([
  48396. BABYLON.serialize()
  48397. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48398. __decorate([
  48399. BABYLON.serialize()
  48400. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48401. __decorate([
  48402. BABYLON.serialize()
  48403. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48404. return ArcRotateCameraPointersInput;
  48405. }());
  48406. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48407. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48408. })(BABYLON || (BABYLON = {}));
  48409. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48410. var BABYLON;
  48411. (function (BABYLON) {
  48412. /**
  48413. * Default Inputs manager for the ArcRotateCamera.
  48414. * It groups all the default supported inputs for ease of use.
  48415. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48416. */
  48417. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48418. __extends(ArcRotateCameraInputsManager, _super);
  48419. /**
  48420. * Instantiates a new ArcRotateCameraInputsManager.
  48421. * @param camera Defines the camera the inputs belong to
  48422. */
  48423. function ArcRotateCameraInputsManager(camera) {
  48424. return _super.call(this, camera) || this;
  48425. }
  48426. /**
  48427. * Add mouse wheel input support to the input manager.
  48428. * @returns the current input manager
  48429. */
  48430. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48431. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48432. return this;
  48433. };
  48434. /**
  48435. * Add pointers input support to the input manager.
  48436. * @returns the current input manager
  48437. */
  48438. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48439. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48440. return this;
  48441. };
  48442. /**
  48443. * Add keyboard input support to the input manager.
  48444. * @returns the current input manager
  48445. */
  48446. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48447. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48448. return this;
  48449. };
  48450. /**
  48451. * Add orientation input support to the input manager.
  48452. * @returns the current input manager
  48453. */
  48454. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48455. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48456. return this;
  48457. };
  48458. return ArcRotateCameraInputsManager;
  48459. }(BABYLON.CameraInputsManager));
  48460. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48461. })(BABYLON || (BABYLON = {}));
  48462. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48463. var BABYLON;
  48464. (function (BABYLON) {
  48465. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  48466. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  48467. });
  48468. /**
  48469. * This represents an orbital type of camera.
  48470. *
  48471. * 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.
  48472. * 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.
  48473. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  48474. */
  48475. var ArcRotateCamera = /** @class */ (function (_super) {
  48476. __extends(ArcRotateCamera, _super);
  48477. /**
  48478. * Instantiates a new ArcRotateCamera in a given scene
  48479. * @param name Defines the name of the camera
  48480. * @param alpha Defines the camera rotation along the logitudinal axis
  48481. * @param beta Defines the camera rotation along the latitudinal axis
  48482. * @param radius Defines the camera distance from its target
  48483. * @param target Defines the camera target
  48484. * @param scene Defines the scene the camera belongs to
  48485. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48486. */
  48487. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48488. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48489. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48490. /**
  48491. * Current inertia value on the longitudinal axis.
  48492. * The bigger this number the longer it will take for the camera to stop.
  48493. */
  48494. _this.inertialAlphaOffset = 0;
  48495. /**
  48496. * Current inertia value on the latitudinal axis.
  48497. * The bigger this number the longer it will take for the camera to stop.
  48498. */
  48499. _this.inertialBetaOffset = 0;
  48500. /**
  48501. * Current inertia value on the radius axis.
  48502. * The bigger this number the longer it will take for the camera to stop.
  48503. */
  48504. _this.inertialRadiusOffset = 0;
  48505. /**
  48506. * Minimum allowed angle on the longitudinal axis.
  48507. * This can help limiting how the Camera is able to move in the scene.
  48508. */
  48509. _this.lowerAlphaLimit = null;
  48510. /**
  48511. * Maximum allowed angle on the longitudinal axis.
  48512. * This can help limiting how the Camera is able to move in the scene.
  48513. */
  48514. _this.upperAlphaLimit = null;
  48515. /**
  48516. * Minimum allowed angle on the latitudinal axis.
  48517. * This can help limiting how the Camera is able to move in the scene.
  48518. */
  48519. _this.lowerBetaLimit = 0.01;
  48520. /**
  48521. * Maximum allowed angle on the latitudinal axis.
  48522. * This can help limiting how the Camera is able to move in the scene.
  48523. */
  48524. _this.upperBetaLimit = Math.PI;
  48525. /**
  48526. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  48527. * This can help limiting how the Camera is able to move in the scene.
  48528. */
  48529. _this.lowerRadiusLimit = null;
  48530. /**
  48531. * Maximum allowed distance of the camera to the target (The camera can not get further).
  48532. * This can help limiting how the Camera is able to move in the scene.
  48533. */
  48534. _this.upperRadiusLimit = null;
  48535. /**
  48536. * Defines the current inertia value used during panning of the camera along the X axis.
  48537. */
  48538. _this.inertialPanningX = 0;
  48539. /**
  48540. * Defines the current inertia value used during panning of the camera along the Y axis.
  48541. */
  48542. _this.inertialPanningY = 0;
  48543. /**
  48544. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  48545. * Basically if your fingers moves away from more than this distance you will be considered
  48546. * in pinch mode.
  48547. */
  48548. _this.pinchToPanMaxDistance = 20;
  48549. /**
  48550. * Defines the maximum distance the camera can pan.
  48551. * This could help keeping the cammera always in your scene.
  48552. */
  48553. _this.panningDistanceLimit = null;
  48554. /**
  48555. * Defines the target of the camera before paning.
  48556. */
  48557. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48558. /**
  48559. * Defines the value of the inertia used during panning.
  48560. * 0 would mean stop inertia and one would mean no decelleration at all.
  48561. */
  48562. _this.panningInertia = 0.9;
  48563. //-- end properties for backward compatibility for inputs
  48564. /**
  48565. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  48566. */
  48567. _this.zoomOnFactor = 1;
  48568. /**
  48569. * Defines a screen offset for the camera position.
  48570. */
  48571. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48572. /**
  48573. * Allows the camera to be completely reversed.
  48574. * If false the camera can not arrive upside down.
  48575. */
  48576. _this.allowUpsideDown = true;
  48577. /**
  48578. * Define if double tap/click is used to restore the previously saved state of the camera.
  48579. */
  48580. _this.useInputToRestoreState = true;
  48581. /** @hidden */
  48582. _this._viewMatrix = new BABYLON.Matrix();
  48583. /**
  48584. * Defines the allowed panning axis.
  48585. */
  48586. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48587. /**
  48588. * Observable triggered when the mesh target has been changed on the camera.
  48589. */
  48590. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48591. /**
  48592. * Defines whether the camera should check collision with the objects oh the scene.
  48593. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  48594. */
  48595. _this.checkCollisions = false;
  48596. /**
  48597. * Defines the collision radius of the camera.
  48598. * This simulates a sphere around the camera.
  48599. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  48600. */
  48601. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48602. _this._previousPosition = BABYLON.Vector3.Zero();
  48603. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48604. _this._newPosition = BABYLON.Vector3.Zero();
  48605. _this._computationVector = BABYLON.Vector3.Zero();
  48606. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48607. if (collidedMesh === void 0) { collidedMesh = null; }
  48608. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48609. newPosition.multiplyInPlace(_this._collider._radius);
  48610. }
  48611. if (!collidedMesh) {
  48612. _this._previousPosition.copyFrom(_this.position);
  48613. }
  48614. else {
  48615. _this.setPosition(newPosition);
  48616. if (_this.onCollide) {
  48617. _this.onCollide(collidedMesh);
  48618. }
  48619. }
  48620. // Recompute because of constraints
  48621. var cosa = Math.cos(_this.alpha);
  48622. var sina = Math.sin(_this.alpha);
  48623. var cosb = Math.cos(_this.beta);
  48624. var sinb = Math.sin(_this.beta);
  48625. if (sinb === 0) {
  48626. sinb = 0.0001;
  48627. }
  48628. var target = _this._getTargetPosition();
  48629. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48630. target.addToRef(_this._computationVector, _this._newPosition);
  48631. _this.position.copyFrom(_this._newPosition);
  48632. var up = _this.upVector;
  48633. if (_this.allowUpsideDown && _this.beta < 0) {
  48634. up = up.clone();
  48635. up = up.negate();
  48636. }
  48637. _this._computeViewMatrix(_this.position, target, up);
  48638. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48639. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48640. _this._collisionTriggered = false;
  48641. };
  48642. _this._target = BABYLON.Vector3.Zero();
  48643. if (target) {
  48644. _this.setTarget(target);
  48645. }
  48646. _this.alpha = alpha;
  48647. _this.beta = beta;
  48648. _this.radius = radius;
  48649. _this.getViewMatrix();
  48650. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48651. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48652. return _this;
  48653. }
  48654. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48655. /**
  48656. * Defines the target point of the camera.
  48657. * The camera looks towards it form the radius distance.
  48658. */
  48659. get: function () {
  48660. return this._target;
  48661. },
  48662. set: function (value) {
  48663. this.setTarget(value);
  48664. },
  48665. enumerable: true,
  48666. configurable: true
  48667. });
  48668. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48669. //-- begin properties for backward compatibility for inputs
  48670. /**
  48671. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  48672. */
  48673. get: function () {
  48674. var pointers = this.inputs.attached["pointers"];
  48675. if (pointers)
  48676. return pointers.angularSensibilityX;
  48677. return 0;
  48678. },
  48679. set: function (value) {
  48680. var pointers = this.inputs.attached["pointers"];
  48681. if (pointers) {
  48682. pointers.angularSensibilityX = value;
  48683. }
  48684. },
  48685. enumerable: true,
  48686. configurable: true
  48687. });
  48688. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48689. /**
  48690. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  48691. */
  48692. get: function () {
  48693. var pointers = this.inputs.attached["pointers"];
  48694. if (pointers)
  48695. return pointers.angularSensibilityY;
  48696. return 0;
  48697. },
  48698. set: function (value) {
  48699. var pointers = this.inputs.attached["pointers"];
  48700. if (pointers) {
  48701. pointers.angularSensibilityY = value;
  48702. }
  48703. },
  48704. enumerable: true,
  48705. configurable: true
  48706. });
  48707. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48708. /**
  48709. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  48710. */
  48711. get: function () {
  48712. var pointers = this.inputs.attached["pointers"];
  48713. if (pointers)
  48714. return pointers.pinchPrecision;
  48715. return 0;
  48716. },
  48717. set: function (value) {
  48718. var pointers = this.inputs.attached["pointers"];
  48719. if (pointers) {
  48720. pointers.pinchPrecision = value;
  48721. }
  48722. },
  48723. enumerable: true,
  48724. configurable: true
  48725. });
  48726. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48727. /**
  48728. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  48729. * It will be used instead of pinchDeltaPrecision if different from 0.
  48730. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48731. */
  48732. get: function () {
  48733. var pointers = this.inputs.attached["pointers"];
  48734. if (pointers)
  48735. return pointers.pinchDeltaPercentage;
  48736. return 0;
  48737. },
  48738. set: function (value) {
  48739. var pointers = this.inputs.attached["pointers"];
  48740. if (pointers) {
  48741. pointers.pinchDeltaPercentage = value;
  48742. }
  48743. },
  48744. enumerable: true,
  48745. configurable: true
  48746. });
  48747. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48748. /**
  48749. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  48750. */
  48751. get: function () {
  48752. var pointers = this.inputs.attached["pointers"];
  48753. if (pointers)
  48754. return pointers.panningSensibility;
  48755. return 0;
  48756. },
  48757. set: function (value) {
  48758. var pointers = this.inputs.attached["pointers"];
  48759. if (pointers) {
  48760. pointers.panningSensibility = value;
  48761. }
  48762. },
  48763. enumerable: true,
  48764. configurable: true
  48765. });
  48766. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48767. /**
  48768. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  48769. */
  48770. get: function () {
  48771. var keyboard = this.inputs.attached["keyboard"];
  48772. if (keyboard)
  48773. return keyboard.keysUp;
  48774. return [];
  48775. },
  48776. set: function (value) {
  48777. var keyboard = this.inputs.attached["keyboard"];
  48778. if (keyboard)
  48779. keyboard.keysUp = value;
  48780. },
  48781. enumerable: true,
  48782. configurable: true
  48783. });
  48784. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48785. /**
  48786. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  48787. */
  48788. get: function () {
  48789. var keyboard = this.inputs.attached["keyboard"];
  48790. if (keyboard)
  48791. return keyboard.keysDown;
  48792. return [];
  48793. },
  48794. set: function (value) {
  48795. var keyboard = this.inputs.attached["keyboard"];
  48796. if (keyboard)
  48797. keyboard.keysDown = value;
  48798. },
  48799. enumerable: true,
  48800. configurable: true
  48801. });
  48802. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48803. /**
  48804. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  48805. */
  48806. get: function () {
  48807. var keyboard = this.inputs.attached["keyboard"];
  48808. if (keyboard)
  48809. return keyboard.keysLeft;
  48810. return [];
  48811. },
  48812. set: function (value) {
  48813. var keyboard = this.inputs.attached["keyboard"];
  48814. if (keyboard)
  48815. keyboard.keysLeft = value;
  48816. },
  48817. enumerable: true,
  48818. configurable: true
  48819. });
  48820. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48821. /**
  48822. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  48823. */
  48824. get: function () {
  48825. var keyboard = this.inputs.attached["keyboard"];
  48826. if (keyboard)
  48827. return keyboard.keysRight;
  48828. return [];
  48829. },
  48830. set: function (value) {
  48831. var keyboard = this.inputs.attached["keyboard"];
  48832. if (keyboard)
  48833. keyboard.keysRight = value;
  48834. },
  48835. enumerable: true,
  48836. configurable: true
  48837. });
  48838. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48839. /**
  48840. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  48841. */
  48842. get: function () {
  48843. var mousewheel = this.inputs.attached["mousewheel"];
  48844. if (mousewheel)
  48845. return mousewheel.wheelPrecision;
  48846. return 0;
  48847. },
  48848. set: function (value) {
  48849. var mousewheel = this.inputs.attached["mousewheel"];
  48850. if (mousewheel)
  48851. mousewheel.wheelPrecision = value;
  48852. },
  48853. enumerable: true,
  48854. configurable: true
  48855. });
  48856. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48857. /**
  48858. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  48859. * It will be used instead of pinchDeltaPrecision if different from 0.
  48860. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48861. */
  48862. get: function () {
  48863. var mousewheel = this.inputs.attached["mousewheel"];
  48864. if (mousewheel)
  48865. return mousewheel.wheelDeltaPercentage;
  48866. return 0;
  48867. },
  48868. set: function (value) {
  48869. var mousewheel = this.inputs.attached["mousewheel"];
  48870. if (mousewheel)
  48871. mousewheel.wheelDeltaPercentage = value;
  48872. },
  48873. enumerable: true,
  48874. configurable: true
  48875. });
  48876. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48877. /**
  48878. * Gets the bouncing behavior of the camera if it has been enabled.
  48879. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  48880. */
  48881. get: function () {
  48882. return this._bouncingBehavior;
  48883. },
  48884. enumerable: true,
  48885. configurable: true
  48886. });
  48887. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48888. /**
  48889. * Defines if the bouncing behavior of the camera is enabled on the camera.
  48890. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  48891. */
  48892. get: function () {
  48893. return this._bouncingBehavior != null;
  48894. },
  48895. set: function (value) {
  48896. if (value === this.useBouncingBehavior) {
  48897. return;
  48898. }
  48899. if (value) {
  48900. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48901. this.addBehavior(this._bouncingBehavior);
  48902. }
  48903. else if (this._bouncingBehavior) {
  48904. this.removeBehavior(this._bouncingBehavior);
  48905. this._bouncingBehavior = null;
  48906. }
  48907. },
  48908. enumerable: true,
  48909. configurable: true
  48910. });
  48911. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48912. /**
  48913. * Gets the framing behavior of the camera if it has been enabled.
  48914. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  48915. */
  48916. get: function () {
  48917. return this._framingBehavior;
  48918. },
  48919. enumerable: true,
  48920. configurable: true
  48921. });
  48922. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48923. /**
  48924. * Defines if the framing behavior of the camera is enabled on the camera.
  48925. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  48926. */
  48927. get: function () {
  48928. return this._framingBehavior != null;
  48929. },
  48930. set: function (value) {
  48931. if (value === this.useFramingBehavior) {
  48932. return;
  48933. }
  48934. if (value) {
  48935. this._framingBehavior = new BABYLON.FramingBehavior();
  48936. this.addBehavior(this._framingBehavior);
  48937. }
  48938. else if (this._framingBehavior) {
  48939. this.removeBehavior(this._framingBehavior);
  48940. this._framingBehavior = null;
  48941. }
  48942. },
  48943. enumerable: true,
  48944. configurable: true
  48945. });
  48946. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48947. /**
  48948. * Gets the auto rotation behavior of the camera if it has been enabled.
  48949. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  48950. */
  48951. get: function () {
  48952. return this._autoRotationBehavior;
  48953. },
  48954. enumerable: true,
  48955. configurable: true
  48956. });
  48957. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48958. /**
  48959. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  48960. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  48961. */
  48962. get: function () {
  48963. return this._autoRotationBehavior != null;
  48964. },
  48965. set: function (value) {
  48966. if (value === this.useAutoRotationBehavior) {
  48967. return;
  48968. }
  48969. if (value) {
  48970. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48971. this.addBehavior(this._autoRotationBehavior);
  48972. }
  48973. else if (this._autoRotationBehavior) {
  48974. this.removeBehavior(this._autoRotationBehavior);
  48975. this._autoRotationBehavior = null;
  48976. }
  48977. },
  48978. enumerable: true,
  48979. configurable: true
  48980. });
  48981. // Cache
  48982. /** @hidden */
  48983. ArcRotateCamera.prototype._initCache = function () {
  48984. _super.prototype._initCache.call(this);
  48985. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48986. this._cache.alpha = undefined;
  48987. this._cache.beta = undefined;
  48988. this._cache.radius = undefined;
  48989. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48990. };
  48991. /** @hidden */
  48992. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48993. if (!ignoreParentClass) {
  48994. _super.prototype._updateCache.call(this);
  48995. }
  48996. this._cache._target.copyFrom(this._getTargetPosition());
  48997. this._cache.alpha = this.alpha;
  48998. this._cache.beta = this.beta;
  48999. this._cache.radius = this.radius;
  49000. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  49001. };
  49002. ArcRotateCamera.prototype._getTargetPosition = function () {
  49003. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  49004. var pos = this._targetHost.getAbsolutePosition();
  49005. if (this._targetBoundingCenter) {
  49006. pos.addToRef(this._targetBoundingCenter, this._target);
  49007. }
  49008. else {
  49009. this._target.copyFrom(pos);
  49010. }
  49011. }
  49012. var lockedTargetPosition = this._getLockedTargetPosition();
  49013. if (lockedTargetPosition) {
  49014. return lockedTargetPosition;
  49015. }
  49016. return this._target;
  49017. };
  49018. /**
  49019. * Stores the current state of the camera (alpha, beta, radius and target)
  49020. * @returns the camera itself
  49021. */
  49022. ArcRotateCamera.prototype.storeState = function () {
  49023. this._storedAlpha = this.alpha;
  49024. this._storedBeta = this.beta;
  49025. this._storedRadius = this.radius;
  49026. this._storedTarget = this._getTargetPosition().clone();
  49027. return _super.prototype.storeState.call(this);
  49028. };
  49029. /**
  49030. * @hidden
  49031. * Restored camera state. You must call storeState() first
  49032. */
  49033. ArcRotateCamera.prototype._restoreStateValues = function () {
  49034. if (!_super.prototype._restoreStateValues.call(this)) {
  49035. return false;
  49036. }
  49037. this.alpha = this._storedAlpha;
  49038. this.beta = this._storedBeta;
  49039. this.radius = this._storedRadius;
  49040. this.setTarget(this._storedTarget.clone());
  49041. this.inertialAlphaOffset = 0;
  49042. this.inertialBetaOffset = 0;
  49043. this.inertialRadiusOffset = 0;
  49044. this.inertialPanningX = 0;
  49045. this.inertialPanningY = 0;
  49046. return true;
  49047. };
  49048. // Synchronized
  49049. /** @hidden */
  49050. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  49051. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  49052. return false;
  49053. return this._cache._target.equals(this._getTargetPosition())
  49054. && this._cache.alpha === this.alpha
  49055. && this._cache.beta === this.beta
  49056. && this._cache.radius === this.radius
  49057. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  49058. };
  49059. /**
  49060. * Attached controls to the current camera.
  49061. * @param element Defines the element the controls should be listened from
  49062. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49063. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  49064. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  49065. */
  49066. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  49067. var _this = this;
  49068. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  49069. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  49070. this._useCtrlForPanning = useCtrlForPanning;
  49071. this._panningMouseButton = panningMouseButton;
  49072. this.inputs.attachElement(element, noPreventDefault);
  49073. this._reset = function () {
  49074. _this.inertialAlphaOffset = 0;
  49075. _this.inertialBetaOffset = 0;
  49076. _this.inertialRadiusOffset = 0;
  49077. _this.inertialPanningX = 0;
  49078. _this.inertialPanningY = 0;
  49079. };
  49080. };
  49081. /**
  49082. * Detach the current controls from the camera.
  49083. * The camera will stop reacting to inputs.
  49084. * @param element Defines the element to stop listening the inputs from
  49085. */
  49086. ArcRotateCamera.prototype.detachControl = function (element) {
  49087. this.inputs.detachElement(element);
  49088. if (this._reset) {
  49089. this._reset();
  49090. }
  49091. };
  49092. /** @hidden */
  49093. ArcRotateCamera.prototype._checkInputs = function () {
  49094. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  49095. if (this._collisionTriggered) {
  49096. return;
  49097. }
  49098. this.inputs.checkInputs();
  49099. // Inertia
  49100. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  49101. var inertialAlphaOffset = this.inertialAlphaOffset;
  49102. if (this.beta <= 0)
  49103. inertialAlphaOffset *= -1;
  49104. if (this.getScene().useRightHandedSystem)
  49105. inertialAlphaOffset *= -1;
  49106. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  49107. inertialAlphaOffset *= -1;
  49108. this.alpha += inertialAlphaOffset;
  49109. this.beta += this.inertialBetaOffset;
  49110. this.radius -= this.inertialRadiusOffset;
  49111. this.inertialAlphaOffset *= this.inertia;
  49112. this.inertialBetaOffset *= this.inertia;
  49113. this.inertialRadiusOffset *= this.inertia;
  49114. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  49115. this.inertialAlphaOffset = 0;
  49116. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  49117. this.inertialBetaOffset = 0;
  49118. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49119. this.inertialRadiusOffset = 0;
  49120. }
  49121. // Panning inertia
  49122. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49123. if (!this._localDirection) {
  49124. this._localDirection = BABYLON.Vector3.Zero();
  49125. this._transformedDirection = BABYLON.Vector3.Zero();
  49126. }
  49127. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49128. this._localDirection.multiplyInPlace(this.panningAxis);
  49129. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49130. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49131. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49132. if (!this.panningAxis.y) {
  49133. this._transformedDirection.y = 0;
  49134. }
  49135. if (!this._targetHost) {
  49136. if (this.panningDistanceLimit) {
  49137. this._transformedDirection.addInPlace(this._target);
  49138. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49139. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49140. this._target.copyFrom(this._transformedDirection);
  49141. }
  49142. }
  49143. else {
  49144. this._target.addInPlace(this._transformedDirection);
  49145. }
  49146. }
  49147. this.inertialPanningX *= this.panningInertia;
  49148. this.inertialPanningY *= this.panningInertia;
  49149. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49150. this.inertialPanningX = 0;
  49151. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49152. this.inertialPanningY = 0;
  49153. }
  49154. // Limits
  49155. this._checkLimits();
  49156. _super.prototype._checkInputs.call(this);
  49157. };
  49158. ArcRotateCamera.prototype._checkLimits = function () {
  49159. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49160. if (this.allowUpsideDown && this.beta > Math.PI) {
  49161. this.beta = this.beta - (2 * Math.PI);
  49162. }
  49163. }
  49164. else {
  49165. if (this.beta < this.lowerBetaLimit) {
  49166. this.beta = this.lowerBetaLimit;
  49167. }
  49168. }
  49169. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49170. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49171. this.beta = this.beta + (2 * Math.PI);
  49172. }
  49173. }
  49174. else {
  49175. if (this.beta > this.upperBetaLimit) {
  49176. this.beta = this.upperBetaLimit;
  49177. }
  49178. }
  49179. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  49180. this.alpha = this.lowerAlphaLimit;
  49181. }
  49182. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  49183. this.alpha = this.upperAlphaLimit;
  49184. }
  49185. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  49186. this.radius = this.lowerRadiusLimit;
  49187. }
  49188. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  49189. this.radius = this.upperRadiusLimit;
  49190. }
  49191. };
  49192. /**
  49193. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  49194. */
  49195. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49196. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49197. this.radius = this._computationVector.length();
  49198. if (this.radius === 0) {
  49199. this.radius = 0.0001; // Just to avoid division by zero
  49200. }
  49201. // Alpha
  49202. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49203. if (this._computationVector.z < 0) {
  49204. this.alpha = 2 * Math.PI - this.alpha;
  49205. }
  49206. // Beta
  49207. this.beta = Math.acos(this._computationVector.y / this.radius);
  49208. this._checkLimits();
  49209. };
  49210. /**
  49211. * Use a position to define the current camera related information like aplha, beta and radius
  49212. * @param position Defines the position to set the camera at
  49213. */
  49214. ArcRotateCamera.prototype.setPosition = function (position) {
  49215. if (this.position.equals(position)) {
  49216. return;
  49217. }
  49218. this.position.copyFrom(position);
  49219. this.rebuildAnglesAndRadius();
  49220. };
  49221. /**
  49222. * Defines the target the camera should look at.
  49223. * This will automatically adapt alpha beta and radius to fit within the new target.
  49224. * @param target Defines the new target as a Vector or a mesh
  49225. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  49226. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  49227. */
  49228. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49229. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49230. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49231. if (target.getBoundingInfo) {
  49232. if (toBoundingCenter) {
  49233. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49234. }
  49235. else {
  49236. this._targetBoundingCenter = null;
  49237. }
  49238. this._targetHost = target;
  49239. this._target = this._getTargetPosition();
  49240. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49241. }
  49242. else {
  49243. var newTarget = target;
  49244. var currentTarget = this._getTargetPosition();
  49245. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49246. return;
  49247. }
  49248. this._targetHost = null;
  49249. this._target = newTarget;
  49250. this._targetBoundingCenter = null;
  49251. this.onMeshTargetChangedObservable.notifyObservers(null);
  49252. }
  49253. this.rebuildAnglesAndRadius();
  49254. };
  49255. /** @hidden */
  49256. ArcRotateCamera.prototype._getViewMatrix = function () {
  49257. // Compute
  49258. var cosa = Math.cos(this.alpha);
  49259. var sina = Math.sin(this.alpha);
  49260. var cosb = Math.cos(this.beta);
  49261. var sinb = Math.sin(this.beta);
  49262. if (sinb === 0) {
  49263. sinb = 0.0001;
  49264. }
  49265. var target = this._getTargetPosition();
  49266. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49267. target.addToRef(this._computationVector, this._newPosition);
  49268. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49269. if (!this._collider) {
  49270. this._collider = new BABYLON.Collider();
  49271. }
  49272. this._collider._radius = this.collisionRadius;
  49273. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49274. this._collisionTriggered = true;
  49275. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49276. }
  49277. else {
  49278. this.position.copyFrom(this._newPosition);
  49279. var up = this.upVector;
  49280. if (this.allowUpsideDown && sinb < 0) {
  49281. up = up.clone();
  49282. up = up.negate();
  49283. }
  49284. this._computeViewMatrix(this.position, target, up);
  49285. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49286. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49287. }
  49288. this._currentTarget = target;
  49289. return this._viewMatrix;
  49290. };
  49291. /**
  49292. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  49293. * @param meshes Defines the mesh to zoom on
  49294. * @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)
  49295. */
  49296. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49297. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49298. meshes = meshes || this.getScene().meshes;
  49299. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49300. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49301. this.radius = distance * this.zoomOnFactor;
  49302. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49303. };
  49304. /**
  49305. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  49306. * The target will be changed but the radius
  49307. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  49308. * @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)
  49309. */
  49310. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49311. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49312. var meshesOrMinMaxVector;
  49313. var distance;
  49314. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49315. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49316. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49317. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49318. }
  49319. else { //minMaxVector and distance
  49320. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49321. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49322. distance = minMaxVectorAndDistance.distance;
  49323. }
  49324. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49325. if (!doNotUpdateMaxZ) {
  49326. this.maxZ = distance * 2;
  49327. }
  49328. };
  49329. /**
  49330. * @override
  49331. * Override Camera.createRigCamera
  49332. */
  49333. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49334. var alphaShift = 0;
  49335. switch (this.cameraRigMode) {
  49336. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49337. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49338. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49339. case BABYLON.Camera.RIG_MODE_VR:
  49340. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49341. break;
  49342. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49343. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49344. break;
  49345. }
  49346. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49347. rigCam._cameraRigParams = {};
  49348. return rigCam;
  49349. };
  49350. /**
  49351. * @hidden
  49352. * @override
  49353. * Override Camera._updateRigCameras
  49354. */
  49355. ArcRotateCamera.prototype._updateRigCameras = function () {
  49356. var camLeft = this._rigCameras[0];
  49357. var camRight = this._rigCameras[1];
  49358. camLeft.beta = camRight.beta = this.beta;
  49359. camLeft.radius = camRight.radius = this.radius;
  49360. switch (this.cameraRigMode) {
  49361. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49362. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49363. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49364. case BABYLON.Camera.RIG_MODE_VR:
  49365. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49366. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49367. break;
  49368. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49369. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49370. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49371. break;
  49372. }
  49373. _super.prototype._updateRigCameras.call(this);
  49374. };
  49375. /**
  49376. * Destroy the camera and release the current resources hold by it.
  49377. */
  49378. ArcRotateCamera.prototype.dispose = function () {
  49379. this.inputs.clear();
  49380. _super.prototype.dispose.call(this);
  49381. };
  49382. /**
  49383. * Gets the current object class name.
  49384. * @return the class name
  49385. */
  49386. ArcRotateCamera.prototype.getClassName = function () {
  49387. return "ArcRotateCamera";
  49388. };
  49389. __decorate([
  49390. BABYLON.serialize()
  49391. ], ArcRotateCamera.prototype, "alpha", void 0);
  49392. __decorate([
  49393. BABYLON.serialize()
  49394. ], ArcRotateCamera.prototype, "beta", void 0);
  49395. __decorate([
  49396. BABYLON.serialize()
  49397. ], ArcRotateCamera.prototype, "radius", void 0);
  49398. __decorate([
  49399. BABYLON.serializeAsVector3("target")
  49400. ], ArcRotateCamera.prototype, "_target", void 0);
  49401. __decorate([
  49402. BABYLON.serialize()
  49403. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49404. __decorate([
  49405. BABYLON.serialize()
  49406. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49407. __decorate([
  49408. BABYLON.serialize()
  49409. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49410. __decorate([
  49411. BABYLON.serialize()
  49412. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49413. __decorate([
  49414. BABYLON.serialize()
  49415. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49416. __decorate([
  49417. BABYLON.serialize()
  49418. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49419. __decorate([
  49420. BABYLON.serialize()
  49421. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49422. __decorate([
  49423. BABYLON.serialize()
  49424. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49425. __decorate([
  49426. BABYLON.serialize()
  49427. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49428. __decorate([
  49429. BABYLON.serialize()
  49430. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49431. __decorate([
  49432. BABYLON.serialize()
  49433. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49434. __decorate([
  49435. BABYLON.serialize()
  49436. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49437. __decorate([
  49438. BABYLON.serialize()
  49439. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49440. __decorate([
  49441. BABYLON.serializeAsVector3()
  49442. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49443. __decorate([
  49444. BABYLON.serialize()
  49445. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49446. __decorate([
  49447. BABYLON.serialize()
  49448. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49449. __decorate([
  49450. BABYLON.serialize()
  49451. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  49452. __decorate([
  49453. BABYLON.serialize()
  49454. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49455. __decorate([
  49456. BABYLON.serialize()
  49457. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  49458. return ArcRotateCamera;
  49459. }(BABYLON.TargetCamera));
  49460. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49461. })(BABYLON || (BABYLON = {}));
  49462. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49463. var BABYLON;
  49464. (function (BABYLON) {
  49465. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  49466. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  49467. });
  49468. /**
  49469. * The HemisphericLight simulates the ambient environment light,
  49470. * so the passed direction is the light reflection direction, not the incoming direction.
  49471. */
  49472. var HemisphericLight = /** @class */ (function (_super) {
  49473. __extends(HemisphericLight, _super);
  49474. /**
  49475. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49476. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49477. * The HemisphericLight can't cast shadows.
  49478. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49479. * @param name The friendly name of the light
  49480. * @param direction The direction of the light reflection
  49481. * @param scene The scene the light belongs to
  49482. */
  49483. function HemisphericLight(name, direction, scene) {
  49484. var _this = _super.call(this, name, scene) || this;
  49485. /**
  49486. * The groundColor is the light in the opposite direction to the one specified during creation.
  49487. * 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.
  49488. */
  49489. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49490. _this.direction = direction || BABYLON.Vector3.Up();
  49491. return _this;
  49492. }
  49493. HemisphericLight.prototype._buildUniformLayout = function () {
  49494. this._uniformBuffer.addUniform("vLightData", 4);
  49495. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49496. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49497. this._uniformBuffer.addUniform("vLightGround", 3);
  49498. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49499. this._uniformBuffer.addUniform("depthValues", 2);
  49500. this._uniformBuffer.create();
  49501. };
  49502. /**
  49503. * Returns the string "HemisphericLight".
  49504. * @return The class name
  49505. */
  49506. HemisphericLight.prototype.getClassName = function () {
  49507. return "HemisphericLight";
  49508. };
  49509. /**
  49510. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49511. * Returns the updated direction.
  49512. * @param target The target the direction should point to
  49513. * @return The computed direction
  49514. */
  49515. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49516. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49517. return this.direction;
  49518. };
  49519. /**
  49520. * Returns the shadow generator associated to the light.
  49521. * @returns Always null for hemispheric lights because it does not support shadows.
  49522. */
  49523. HemisphericLight.prototype.getShadowGenerator = function () {
  49524. return null;
  49525. };
  49526. /**
  49527. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49528. * @param effect The effect to update
  49529. * @param lightIndex The index of the light in the effect to update
  49530. * @returns The hemispheric light
  49531. */
  49532. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49533. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49534. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49535. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49536. return this;
  49537. };
  49538. /**
  49539. * Computes the world matrix of the node
  49540. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  49541. * @param useWasUpdatedFlag defines a reserved property
  49542. * @returns the world matrix
  49543. */
  49544. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  49545. if (!this._worldMatrix) {
  49546. this._worldMatrix = BABYLON.Matrix.Identity();
  49547. }
  49548. return this._worldMatrix;
  49549. };
  49550. /**
  49551. * Returns the integer 3.
  49552. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49553. */
  49554. HemisphericLight.prototype.getTypeID = function () {
  49555. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49556. };
  49557. /**
  49558. * Prepares the list of defines specific to the light type.
  49559. * @param defines the list of defines
  49560. * @param lightIndex defines the index of the light for the effect
  49561. */
  49562. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49563. defines["HEMILIGHT" + lightIndex] = true;
  49564. };
  49565. __decorate([
  49566. BABYLON.serializeAsColor3()
  49567. ], HemisphericLight.prototype, "groundColor", void 0);
  49568. __decorate([
  49569. BABYLON.serializeAsVector3()
  49570. ], HemisphericLight.prototype, "direction", void 0);
  49571. return HemisphericLight;
  49572. }(BABYLON.Light));
  49573. BABYLON.HemisphericLight = HemisphericLight;
  49574. })(BABYLON || (BABYLON = {}));
  49575. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49576. var BABYLON;
  49577. (function (BABYLON) {
  49578. /**
  49579. * Base implementation IShadowLight
  49580. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49581. */
  49582. var ShadowLight = /** @class */ (function (_super) {
  49583. __extends(ShadowLight, _super);
  49584. function ShadowLight() {
  49585. var _this = _super !== null && _super.apply(this, arguments) || this;
  49586. _this._needProjectionMatrixCompute = true;
  49587. return _this;
  49588. }
  49589. ShadowLight.prototype._setPosition = function (value) {
  49590. this._position = value;
  49591. };
  49592. Object.defineProperty(ShadowLight.prototype, "position", {
  49593. /**
  49594. * Sets the position the shadow will be casted from. Also use as the light position for both
  49595. * point and spot lights.
  49596. */
  49597. get: function () {
  49598. return this._position;
  49599. },
  49600. /**
  49601. * Sets the position the shadow will be casted from. Also use as the light position for both
  49602. * point and spot lights.
  49603. */
  49604. set: function (value) {
  49605. this._setPosition(value);
  49606. },
  49607. enumerable: true,
  49608. configurable: true
  49609. });
  49610. ShadowLight.prototype._setDirection = function (value) {
  49611. this._direction = value;
  49612. };
  49613. Object.defineProperty(ShadowLight.prototype, "direction", {
  49614. /**
  49615. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49616. * Also use as the light direction on spot and directional lights.
  49617. */
  49618. get: function () {
  49619. return this._direction;
  49620. },
  49621. /**
  49622. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49623. * Also use as the light direction on spot and directional lights.
  49624. */
  49625. set: function (value) {
  49626. this._setDirection(value);
  49627. },
  49628. enumerable: true,
  49629. configurable: true
  49630. });
  49631. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49632. /**
  49633. * Gets the shadow projection clipping minimum z value.
  49634. */
  49635. get: function () {
  49636. return this._shadowMinZ;
  49637. },
  49638. /**
  49639. * Sets the shadow projection clipping minimum z value.
  49640. */
  49641. set: function (value) {
  49642. this._shadowMinZ = value;
  49643. this.forceProjectionMatrixCompute();
  49644. },
  49645. enumerable: true,
  49646. configurable: true
  49647. });
  49648. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49649. /**
  49650. * Sets the shadow projection clipping maximum z value.
  49651. */
  49652. get: function () {
  49653. return this._shadowMaxZ;
  49654. },
  49655. /**
  49656. * Gets the shadow projection clipping maximum z value.
  49657. */
  49658. set: function (value) {
  49659. this._shadowMaxZ = value;
  49660. this.forceProjectionMatrixCompute();
  49661. },
  49662. enumerable: true,
  49663. configurable: true
  49664. });
  49665. /**
  49666. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49667. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49668. */
  49669. ShadowLight.prototype.computeTransformedInformation = function () {
  49670. if (this.parent && this.parent.getWorldMatrix) {
  49671. if (!this.transformedPosition) {
  49672. this.transformedPosition = BABYLON.Vector3.Zero();
  49673. }
  49674. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49675. // In case the direction is present.
  49676. if (this.direction) {
  49677. if (!this.transformedDirection) {
  49678. this.transformedDirection = BABYLON.Vector3.Zero();
  49679. }
  49680. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49681. }
  49682. return true;
  49683. }
  49684. return false;
  49685. };
  49686. /**
  49687. * Return the depth scale used for the shadow map.
  49688. * @returns the depth scale.
  49689. */
  49690. ShadowLight.prototype.getDepthScale = function () {
  49691. return 50.0;
  49692. };
  49693. /**
  49694. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49695. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49696. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49697. */
  49698. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49699. return this.transformedDirection ? this.transformedDirection : this.direction;
  49700. };
  49701. /**
  49702. * Returns the ShadowLight absolute position in the World.
  49703. * @returns the position vector in world space
  49704. */
  49705. ShadowLight.prototype.getAbsolutePosition = function () {
  49706. return this.transformedPosition ? this.transformedPosition : this.position;
  49707. };
  49708. /**
  49709. * Sets the ShadowLight direction toward the passed target.
  49710. * @param target The point tot target in local space
  49711. * @returns the updated ShadowLight direction
  49712. */
  49713. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49714. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49715. return this.direction;
  49716. };
  49717. /**
  49718. * Returns the light rotation in euler definition.
  49719. * @returns the x y z rotation in local space.
  49720. */
  49721. ShadowLight.prototype.getRotation = function () {
  49722. this.direction.normalize();
  49723. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49724. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49725. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49726. };
  49727. /**
  49728. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49729. * @returns true if a cube texture needs to be use
  49730. */
  49731. ShadowLight.prototype.needCube = function () {
  49732. return false;
  49733. };
  49734. /**
  49735. * Detects if the projection matrix requires to be recomputed this frame.
  49736. * @returns true if it requires to be recomputed otherwise, false.
  49737. */
  49738. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49739. return this._needProjectionMatrixCompute;
  49740. };
  49741. /**
  49742. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49743. */
  49744. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49745. this._needProjectionMatrixCompute = true;
  49746. };
  49747. /** @hidden */
  49748. ShadowLight.prototype._initCache = function () {
  49749. _super.prototype._initCache.call(this);
  49750. this._cache.position = BABYLON.Vector3.Zero();
  49751. };
  49752. /** @hidden */
  49753. ShadowLight.prototype._isSynchronized = function () {
  49754. if (!this._cache.position.equals(this.position))
  49755. return false;
  49756. return true;
  49757. };
  49758. /**
  49759. * Computes the world matrix of the node
  49760. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  49761. * @returns the world matrix
  49762. */
  49763. ShadowLight.prototype.computeWorldMatrix = function (force) {
  49764. if (!force && this.isSynchronized()) {
  49765. this._currentRenderId = this.getScene().getRenderId();
  49766. return this._worldMatrix;
  49767. }
  49768. this._updateCache();
  49769. this._cache.position.copyFrom(this.position);
  49770. if (!this._worldMatrix) {
  49771. this._worldMatrix = BABYLON.Matrix.Identity();
  49772. }
  49773. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49774. if (this.parent && this.parent.getWorldMatrix) {
  49775. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  49776. this._markSyncedWithParent();
  49777. }
  49778. // Cache the determinant
  49779. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  49780. return this._worldMatrix;
  49781. };
  49782. /**
  49783. * Gets the minZ used for shadow according to both the scene and the light.
  49784. * @param activeCamera The camera we are returning the min for
  49785. * @returns the depth min z
  49786. */
  49787. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49788. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49789. };
  49790. /**
  49791. * Gets the maxZ used for shadow according to both the scene and the light.
  49792. * @param activeCamera The camera we are returning the max for
  49793. * @returns the depth max z
  49794. */
  49795. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49796. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49797. };
  49798. /**
  49799. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49800. * @param matrix The materix to updated with the projection information
  49801. * @param viewMatrix The transform matrix of the light
  49802. * @param renderList The list of mesh to render in the map
  49803. * @returns The current light
  49804. */
  49805. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49806. if (this.customProjectionMatrixBuilder) {
  49807. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49808. }
  49809. else {
  49810. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49811. }
  49812. return this;
  49813. };
  49814. __decorate([
  49815. BABYLON.serializeAsVector3()
  49816. ], ShadowLight.prototype, "position", null);
  49817. __decorate([
  49818. BABYLON.serializeAsVector3()
  49819. ], ShadowLight.prototype, "direction", null);
  49820. __decorate([
  49821. BABYLON.serialize()
  49822. ], ShadowLight.prototype, "shadowMinZ", null);
  49823. __decorate([
  49824. BABYLON.serialize()
  49825. ], ShadowLight.prototype, "shadowMaxZ", null);
  49826. return ShadowLight;
  49827. }(BABYLON.Light));
  49828. BABYLON.ShadowLight = ShadowLight;
  49829. })(BABYLON || (BABYLON = {}));
  49830. //# sourceMappingURL=babylon.shadowLight.js.map
  49831. var BABYLON;
  49832. (function (BABYLON) {
  49833. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  49834. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  49835. });
  49836. /**
  49837. * A point light is a light defined by an unique point in world space.
  49838. * The light is emitted in every direction from this point.
  49839. * A good example of a point light is a standard light bulb.
  49840. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49841. */
  49842. var PointLight = /** @class */ (function (_super) {
  49843. __extends(PointLight, _super);
  49844. /**
  49845. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49846. * A PointLight emits the light in every direction.
  49847. * It can cast shadows.
  49848. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49849. * ```javascript
  49850. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49851. * ```
  49852. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49853. * @param name The light friendly name
  49854. * @param position The position of the point light in the scene
  49855. * @param scene The scene the lights belongs to
  49856. */
  49857. function PointLight(name, position, scene) {
  49858. var _this = _super.call(this, name, scene) || this;
  49859. _this._shadowAngle = Math.PI / 2;
  49860. _this.position = position;
  49861. return _this;
  49862. }
  49863. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49864. /**
  49865. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49866. * This specifies what angle the shadow will use to be created.
  49867. *
  49868. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49869. */
  49870. get: function () {
  49871. return this._shadowAngle;
  49872. },
  49873. /**
  49874. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49875. * This specifies what angle the shadow will use to be created.
  49876. *
  49877. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49878. */
  49879. set: function (value) {
  49880. this._shadowAngle = value;
  49881. this.forceProjectionMatrixCompute();
  49882. },
  49883. enumerable: true,
  49884. configurable: true
  49885. });
  49886. Object.defineProperty(PointLight.prototype, "direction", {
  49887. /**
  49888. * Gets the direction if it has been set.
  49889. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49890. */
  49891. get: function () {
  49892. return this._direction;
  49893. },
  49894. /**
  49895. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49896. */
  49897. set: function (value) {
  49898. var previousNeedCube = this.needCube();
  49899. this._direction = value;
  49900. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49901. this._shadowGenerator.recreateShadowMap();
  49902. }
  49903. },
  49904. enumerable: true,
  49905. configurable: true
  49906. });
  49907. /**
  49908. * Returns the string "PointLight"
  49909. * @returns the class name
  49910. */
  49911. PointLight.prototype.getClassName = function () {
  49912. return "PointLight";
  49913. };
  49914. /**
  49915. * Returns the integer 0.
  49916. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49917. */
  49918. PointLight.prototype.getTypeID = function () {
  49919. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49920. };
  49921. /**
  49922. * Specifies wether or not the shadowmap should be a cube texture.
  49923. * @returns true if the shadowmap needs to be a cube texture.
  49924. */
  49925. PointLight.prototype.needCube = function () {
  49926. return !this.direction;
  49927. };
  49928. /**
  49929. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49930. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49931. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49932. */
  49933. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49934. if (this.direction) {
  49935. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49936. }
  49937. else {
  49938. switch (faceIndex) {
  49939. case 0:
  49940. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49941. case 1:
  49942. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49943. case 2:
  49944. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49945. case 3:
  49946. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49947. case 4:
  49948. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49949. case 5:
  49950. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49951. }
  49952. }
  49953. return BABYLON.Vector3.Zero();
  49954. };
  49955. /**
  49956. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49957. * - fov = PI / 2
  49958. * - aspect ratio : 1.0
  49959. * - z-near and far equal to the active camera minZ and maxZ.
  49960. * Returns the PointLight.
  49961. */
  49962. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49963. var activeCamera = this.getScene().activeCamera;
  49964. if (!activeCamera) {
  49965. return;
  49966. }
  49967. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49968. };
  49969. PointLight.prototype._buildUniformLayout = function () {
  49970. this._uniformBuffer.addUniform("vLightData", 4);
  49971. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49972. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49973. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49974. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49975. this._uniformBuffer.addUniform("depthValues", 2);
  49976. this._uniformBuffer.create();
  49977. };
  49978. /**
  49979. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49980. * @param effect The effect to update
  49981. * @param lightIndex The index of the light in the effect to update
  49982. * @returns The point light
  49983. */
  49984. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49985. if (this.computeTransformedInformation()) {
  49986. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49987. }
  49988. else {
  49989. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49990. }
  49991. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  49992. return this;
  49993. };
  49994. /**
  49995. * Prepares the list of defines specific to the light type.
  49996. * @param defines the list of defines
  49997. * @param lightIndex defines the index of the light for the effect
  49998. */
  49999. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50000. defines["POINTLIGHT" + lightIndex] = true;
  50001. };
  50002. __decorate([
  50003. BABYLON.serialize()
  50004. ], PointLight.prototype, "shadowAngle", null);
  50005. return PointLight;
  50006. }(BABYLON.ShadowLight));
  50007. BABYLON.PointLight = PointLight;
  50008. })(BABYLON || (BABYLON = {}));
  50009. //# sourceMappingURL=babylon.pointLight.js.map
  50010. var BABYLON;
  50011. (function (BABYLON) {
  50012. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  50013. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  50014. });
  50015. /**
  50016. * A directional light is defined by a direction (what a surprise!).
  50017. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  50018. * 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.
  50019. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50020. */
  50021. var DirectionalLight = /** @class */ (function (_super) {
  50022. __extends(DirectionalLight, _super);
  50023. /**
  50024. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  50025. * The directional light is emitted from everywhere in the given direction.
  50026. * It can cast shadows.
  50027. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50028. * @param name The friendly name of the light
  50029. * @param direction The direction of the light
  50030. * @param scene The scene the light belongs to
  50031. */
  50032. function DirectionalLight(name, direction, scene) {
  50033. var _this = _super.call(this, name, scene) || this;
  50034. _this._shadowFrustumSize = 0;
  50035. _this._shadowOrthoScale = 0.1;
  50036. /**
  50037. * Automatically compute the projection matrix to best fit (including all the casters)
  50038. * on each frame.
  50039. */
  50040. _this.autoUpdateExtends = true;
  50041. // Cache
  50042. _this._orthoLeft = Number.MAX_VALUE;
  50043. _this._orthoRight = Number.MIN_VALUE;
  50044. _this._orthoTop = Number.MIN_VALUE;
  50045. _this._orthoBottom = Number.MAX_VALUE;
  50046. _this.position = direction.scale(-1.0);
  50047. _this.direction = direction;
  50048. return _this;
  50049. }
  50050. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  50051. /**
  50052. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  50053. */
  50054. get: function () {
  50055. return this._shadowFrustumSize;
  50056. },
  50057. /**
  50058. * Specifies a fix frustum size for the shadow generation.
  50059. */
  50060. set: function (value) {
  50061. this._shadowFrustumSize = value;
  50062. this.forceProjectionMatrixCompute();
  50063. },
  50064. enumerable: true,
  50065. configurable: true
  50066. });
  50067. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  50068. /**
  50069. * Gets the shadow projection scale against the optimal computed one.
  50070. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50071. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50072. */
  50073. get: function () {
  50074. return this._shadowOrthoScale;
  50075. },
  50076. /**
  50077. * Sets the shadow projection scale against the optimal computed one.
  50078. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50079. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50080. */
  50081. set: function (value) {
  50082. this._shadowOrthoScale = value;
  50083. this.forceProjectionMatrixCompute();
  50084. },
  50085. enumerable: true,
  50086. configurable: true
  50087. });
  50088. /**
  50089. * Returns the string "DirectionalLight".
  50090. * @return The class name
  50091. */
  50092. DirectionalLight.prototype.getClassName = function () {
  50093. return "DirectionalLight";
  50094. };
  50095. /**
  50096. * Returns the integer 1.
  50097. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50098. */
  50099. DirectionalLight.prototype.getTypeID = function () {
  50100. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  50101. };
  50102. /**
  50103. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  50104. * Returns the DirectionalLight Shadow projection matrix.
  50105. */
  50106. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50107. if (this.shadowFrustumSize > 0) {
  50108. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  50109. }
  50110. else {
  50111. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50112. }
  50113. };
  50114. /**
  50115. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  50116. * Returns the DirectionalLight Shadow projection matrix.
  50117. */
  50118. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  50119. var activeCamera = this.getScene().activeCamera;
  50120. if (!activeCamera) {
  50121. return;
  50122. }
  50123. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  50124. };
  50125. /**
  50126. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  50127. * Returns the DirectionalLight Shadow projection matrix.
  50128. */
  50129. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50130. var activeCamera = this.getScene().activeCamera;
  50131. if (!activeCamera) {
  50132. return;
  50133. }
  50134. // Check extends
  50135. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  50136. var tempVector3 = BABYLON.Vector3.Zero();
  50137. this._orthoLeft = Number.MAX_VALUE;
  50138. this._orthoRight = Number.MIN_VALUE;
  50139. this._orthoTop = Number.MIN_VALUE;
  50140. this._orthoBottom = Number.MAX_VALUE;
  50141. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  50142. var mesh = renderList[meshIndex];
  50143. if (!mesh) {
  50144. continue;
  50145. }
  50146. var boundingInfo = mesh.getBoundingInfo();
  50147. var boundingBox = boundingInfo.boundingBox;
  50148. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  50149. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  50150. if (tempVector3.x < this._orthoLeft)
  50151. this._orthoLeft = tempVector3.x;
  50152. if (tempVector3.y < this._orthoBottom)
  50153. this._orthoBottom = tempVector3.y;
  50154. if (tempVector3.x > this._orthoRight)
  50155. this._orthoRight = tempVector3.x;
  50156. if (tempVector3.y > this._orthoTop)
  50157. this._orthoTop = tempVector3.y;
  50158. }
  50159. }
  50160. }
  50161. var xOffset = this._orthoRight - this._orthoLeft;
  50162. var yOffset = this._orthoTop - this._orthoBottom;
  50163. 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);
  50164. };
  50165. DirectionalLight.prototype._buildUniformLayout = function () {
  50166. this._uniformBuffer.addUniform("vLightData", 4);
  50167. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50168. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50169. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50170. this._uniformBuffer.addUniform("depthValues", 2);
  50171. this._uniformBuffer.create();
  50172. };
  50173. /**
  50174. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  50175. * @param effect The effect to update
  50176. * @param lightIndex The index of the light in the effect to update
  50177. * @returns The directional light
  50178. */
  50179. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  50180. if (this.computeTransformedInformation()) {
  50181. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  50182. return this;
  50183. }
  50184. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  50185. return this;
  50186. };
  50187. /**
  50188. * Gets the minZ used for shadow according to both the scene and the light.
  50189. *
  50190. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50191. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50192. * @param activeCamera The camera we are returning the min for
  50193. * @returns the depth min z
  50194. */
  50195. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  50196. return 1;
  50197. };
  50198. /**
  50199. * Gets the maxZ used for shadow according to both the scene and the light.
  50200. *
  50201. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50202. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50203. * @param activeCamera The camera we are returning the max for
  50204. * @returns the depth max z
  50205. */
  50206. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  50207. return 1;
  50208. };
  50209. /**
  50210. * Prepares the list of defines specific to the light type.
  50211. * @param defines the list of defines
  50212. * @param lightIndex defines the index of the light for the effect
  50213. */
  50214. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50215. defines["DIRLIGHT" + lightIndex] = true;
  50216. };
  50217. __decorate([
  50218. BABYLON.serialize()
  50219. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  50220. __decorate([
  50221. BABYLON.serialize()
  50222. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  50223. __decorate([
  50224. BABYLON.serialize()
  50225. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  50226. return DirectionalLight;
  50227. }(BABYLON.ShadowLight));
  50228. BABYLON.DirectionalLight = DirectionalLight;
  50229. })(BABYLON || (BABYLON = {}));
  50230. //# sourceMappingURL=babylon.directionalLight.js.map
  50231. var BABYLON;
  50232. (function (BABYLON) {
  50233. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  50234. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  50235. });
  50236. /**
  50237. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50238. * These values define a cone of light starting from the position, emitting toward the direction.
  50239. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50240. * and the exponent defines the speed of the decay of the light with distance (reach).
  50241. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50242. */
  50243. var SpotLight = /** @class */ (function (_super) {
  50244. __extends(SpotLight, _super);
  50245. /**
  50246. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50247. * It can cast shadows.
  50248. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50249. * @param name The light friendly name
  50250. * @param position The position of the spot light in the scene
  50251. * @param direction The direction of the light in the scene
  50252. * @param angle The cone angle of the light in Radians
  50253. * @param exponent The light decay speed with the distance from the emission spot
  50254. * @param scene The scene the lights belongs to
  50255. */
  50256. function SpotLight(name, position, direction, angle, exponent, scene) {
  50257. var _this = _super.call(this, name, scene) || this;
  50258. _this._innerAngle = 0;
  50259. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50260. _this._projectionTextureLightNear = 1e-6;
  50261. _this._projectionTextureLightFar = 1000.0;
  50262. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50263. _this._projectionTextureViewLightDirty = true;
  50264. _this._projectionTextureProjectionLightDirty = true;
  50265. _this._projectionTextureDirty = true;
  50266. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50267. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50268. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50269. _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);
  50270. _this.position = position;
  50271. _this.direction = direction;
  50272. _this.angle = angle;
  50273. _this.exponent = exponent;
  50274. return _this;
  50275. }
  50276. Object.defineProperty(SpotLight.prototype, "angle", {
  50277. /**
  50278. * Gets the cone angle of the spot light in Radians.
  50279. */
  50280. get: function () {
  50281. return this._angle;
  50282. },
  50283. /**
  50284. * Sets the cone angle of the spot light in Radians.
  50285. */
  50286. set: function (value) {
  50287. this._angle = value;
  50288. this._cosHalfAngle = Math.cos(value * 0.5);
  50289. this._projectionTextureProjectionLightDirty = true;
  50290. this.forceProjectionMatrixCompute();
  50291. this._computeAngleValues();
  50292. },
  50293. enumerable: true,
  50294. configurable: true
  50295. });
  50296. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  50297. /**
  50298. * Only used in gltf falloff mode, this defines the angle where
  50299. * the directional falloff will start before cutting at angle which could be seen
  50300. * as outer angle.
  50301. */
  50302. get: function () {
  50303. return this._innerAngle;
  50304. },
  50305. /**
  50306. * Only used in gltf falloff mode, this defines the angle where
  50307. * the directional falloff will start before cutting at angle which could be seen
  50308. * as outer angle.
  50309. */
  50310. set: function (value) {
  50311. this._innerAngle = value;
  50312. this._computeAngleValues();
  50313. },
  50314. enumerable: true,
  50315. configurable: true
  50316. });
  50317. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50318. /**
  50319. * Allows scaling the angle of the light for shadow generation only.
  50320. */
  50321. get: function () {
  50322. return this._shadowAngleScale;
  50323. },
  50324. /**
  50325. * Allows scaling the angle of the light for shadow generation only.
  50326. */
  50327. set: function (value) {
  50328. this._shadowAngleScale = value;
  50329. this.forceProjectionMatrixCompute();
  50330. },
  50331. enumerable: true,
  50332. configurable: true
  50333. });
  50334. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50335. /**
  50336. * Allows reading the projecton texture
  50337. */
  50338. get: function () {
  50339. return this._projectionTextureMatrix;
  50340. },
  50341. enumerable: true,
  50342. configurable: true
  50343. });
  50344. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50345. /**
  50346. * Gets the near clip of the Spotlight for texture projection.
  50347. */
  50348. get: function () {
  50349. return this._projectionTextureLightNear;
  50350. },
  50351. /**
  50352. * Sets the near clip of the Spotlight for texture projection.
  50353. */
  50354. set: function (value) {
  50355. this._projectionTextureLightNear = value;
  50356. this._projectionTextureProjectionLightDirty = true;
  50357. },
  50358. enumerable: true,
  50359. configurable: true
  50360. });
  50361. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50362. /**
  50363. * Gets the far clip of the Spotlight for texture projection.
  50364. */
  50365. get: function () {
  50366. return this._projectionTextureLightFar;
  50367. },
  50368. /**
  50369. * Sets the far clip of the Spotlight for texture projection.
  50370. */
  50371. set: function (value) {
  50372. this._projectionTextureLightFar = value;
  50373. this._projectionTextureProjectionLightDirty = true;
  50374. },
  50375. enumerable: true,
  50376. configurable: true
  50377. });
  50378. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50379. /**
  50380. * Gets the Up vector of the Spotlight for texture projection.
  50381. */
  50382. get: function () {
  50383. return this._projectionTextureUpDirection;
  50384. },
  50385. /**
  50386. * Sets the Up vector of the Spotlight for texture projection.
  50387. */
  50388. set: function (value) {
  50389. this._projectionTextureUpDirection = value;
  50390. this._projectionTextureProjectionLightDirty = true;
  50391. },
  50392. enumerable: true,
  50393. configurable: true
  50394. });
  50395. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50396. /**
  50397. * Gets the projection texture of the light.
  50398. */
  50399. get: function () {
  50400. return this._projectionTexture;
  50401. },
  50402. /**
  50403. * Sets the projection texture of the light.
  50404. */
  50405. set: function (value) {
  50406. this._projectionTexture = value;
  50407. this._projectionTextureDirty = true;
  50408. },
  50409. enumerable: true,
  50410. configurable: true
  50411. });
  50412. /**
  50413. * Returns the string "SpotLight".
  50414. * @returns the class name
  50415. */
  50416. SpotLight.prototype.getClassName = function () {
  50417. return "SpotLight";
  50418. };
  50419. /**
  50420. * Returns the integer 2.
  50421. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50422. */
  50423. SpotLight.prototype.getTypeID = function () {
  50424. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50425. };
  50426. /**
  50427. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50428. */
  50429. SpotLight.prototype._setDirection = function (value) {
  50430. _super.prototype._setDirection.call(this, value);
  50431. this._projectionTextureViewLightDirty = true;
  50432. };
  50433. /**
  50434. * Overrides the position setter to recompute the projection texture view light Matrix.
  50435. */
  50436. SpotLight.prototype._setPosition = function (value) {
  50437. _super.prototype._setPosition.call(this, value);
  50438. this._projectionTextureViewLightDirty = true;
  50439. };
  50440. /**
  50441. * 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.
  50442. * Returns the SpotLight.
  50443. */
  50444. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50445. var activeCamera = this.getScene().activeCamera;
  50446. if (!activeCamera) {
  50447. return;
  50448. }
  50449. this._shadowAngleScale = this._shadowAngleScale || 1;
  50450. var angle = this._shadowAngleScale * this._angle;
  50451. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50452. };
  50453. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50454. this._projectionTextureViewLightDirty = false;
  50455. this._projectionTextureDirty = true;
  50456. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50457. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50458. };
  50459. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50460. this._projectionTextureProjectionLightDirty = false;
  50461. this._projectionTextureDirty = true;
  50462. var light_far = this.projectionTextureLightFar;
  50463. var light_near = this.projectionTextureLightNear;
  50464. var P = light_far / (light_far - light_near);
  50465. var Q = -P * light_near;
  50466. var S = 1.0 / Math.tan(this._angle / 2.0);
  50467. var A = 1.0;
  50468. 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);
  50469. };
  50470. /**
  50471. * Main function for light texture projection matrix computing.
  50472. */
  50473. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50474. this._projectionTextureDirty = false;
  50475. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50476. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50477. };
  50478. SpotLight.prototype._buildUniformLayout = function () {
  50479. this._uniformBuffer.addUniform("vLightData", 4);
  50480. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50481. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50482. this._uniformBuffer.addUniform("vLightDirection", 3);
  50483. this._uniformBuffer.addUniform("vLightFalloff", 4);
  50484. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50485. this._uniformBuffer.addUniform("depthValues", 2);
  50486. this._uniformBuffer.create();
  50487. };
  50488. SpotLight.prototype._computeAngleValues = function () {
  50489. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  50490. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  50491. };
  50492. /**
  50493. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50494. * @param effect The effect to update
  50495. * @param lightIndex The index of the light in the effect to update
  50496. * @returns The spot light
  50497. */
  50498. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50499. var normalizeDirection;
  50500. if (this.computeTransformedInformation()) {
  50501. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50502. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50503. }
  50504. else {
  50505. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50506. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50507. }
  50508. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  50509. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  50510. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50511. if (this._projectionTextureViewLightDirty) {
  50512. this._computeProjectionTextureViewLightMatrix();
  50513. }
  50514. if (this._projectionTextureProjectionLightDirty) {
  50515. this._computeProjectionTextureProjectionLightMatrix();
  50516. }
  50517. if (this._projectionTextureDirty) {
  50518. this._computeProjectionTextureMatrix();
  50519. }
  50520. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50521. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50522. }
  50523. return this;
  50524. };
  50525. /**
  50526. * Disposes the light and the associated resources.
  50527. */
  50528. SpotLight.prototype.dispose = function () {
  50529. _super.prototype.dispose.call(this);
  50530. if (this._projectionTexture) {
  50531. this._projectionTexture.dispose();
  50532. }
  50533. };
  50534. /**
  50535. * Prepares the list of defines specific to the light type.
  50536. * @param defines the list of defines
  50537. * @param lightIndex defines the index of the light for the effect
  50538. */
  50539. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50540. defines["SPOTLIGHT" + lightIndex] = true;
  50541. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  50542. };
  50543. __decorate([
  50544. BABYLON.serialize()
  50545. ], SpotLight.prototype, "angle", null);
  50546. __decorate([
  50547. BABYLON.serialize()
  50548. ], SpotLight.prototype, "innerAngle", null);
  50549. __decorate([
  50550. BABYLON.serialize()
  50551. ], SpotLight.prototype, "shadowAngleScale", null);
  50552. __decorate([
  50553. BABYLON.serialize()
  50554. ], SpotLight.prototype, "exponent", void 0);
  50555. __decorate([
  50556. BABYLON.serialize()
  50557. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50558. __decorate([
  50559. BABYLON.serialize()
  50560. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50561. __decorate([
  50562. BABYLON.serialize()
  50563. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50564. __decorate([
  50565. BABYLON.serializeAsTexture("projectedLightTexture")
  50566. ], SpotLight.prototype, "_projectionTexture", void 0);
  50567. return SpotLight;
  50568. }(BABYLON.ShadowLight));
  50569. BABYLON.SpotLight = SpotLight;
  50570. })(BABYLON || (BABYLON = {}));
  50571. //# sourceMappingURL=babylon.spotLight.js.map
  50572. var BABYLON;
  50573. (function (BABYLON) {
  50574. /**
  50575. * Class used to override all child animations of a given target
  50576. */
  50577. var AnimationPropertiesOverride = /** @class */ (function () {
  50578. function AnimationPropertiesOverride() {
  50579. /**
  50580. * Gets or sets a value indicating if animation blending must be used
  50581. */
  50582. this.enableBlending = false;
  50583. /**
  50584. * Gets or sets the blending speed to use when enableBlending is true
  50585. */
  50586. this.blendingSpeed = 0.01;
  50587. /**
  50588. * Gets or sets the default loop mode to use
  50589. */
  50590. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50591. }
  50592. return AnimationPropertiesOverride;
  50593. }());
  50594. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50595. })(BABYLON || (BABYLON = {}));
  50596. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50597. var BABYLON;
  50598. (function (BABYLON) {
  50599. /**
  50600. * Represents the range of an animation
  50601. */
  50602. var AnimationRange = /** @class */ (function () {
  50603. /**
  50604. * Initializes the range of an animation
  50605. * @param name The name of the animation range
  50606. * @param from The starting frame of the animation
  50607. * @param to The ending frame of the animation
  50608. */
  50609. function AnimationRange(
  50610. /**The name of the animation range**/
  50611. name,
  50612. /**The starting frame of the animation */
  50613. from,
  50614. /**The ending frame of the animation*/
  50615. to) {
  50616. this.name = name;
  50617. this.from = from;
  50618. this.to = to;
  50619. }
  50620. /**
  50621. * Makes a copy of the animation range
  50622. * @returns A copy of the animation range
  50623. */
  50624. AnimationRange.prototype.clone = function () {
  50625. return new AnimationRange(this.name, this.from, this.to);
  50626. };
  50627. return AnimationRange;
  50628. }());
  50629. BABYLON.AnimationRange = AnimationRange;
  50630. /**
  50631. * Composed of a frame, and an action function
  50632. */
  50633. var AnimationEvent = /** @class */ (function () {
  50634. /**
  50635. * Initializes the animation event
  50636. * @param frame The frame for which the event is triggered
  50637. * @param action The event to perform when triggered
  50638. * @param onlyOnce Specifies if the event should be triggered only once
  50639. */
  50640. function AnimationEvent(
  50641. /** The frame for which the event is triggered **/
  50642. frame,
  50643. /** The event to perform when triggered **/
  50644. action,
  50645. /** Specifies if the event should be triggered only once**/
  50646. onlyOnce) {
  50647. this.frame = frame;
  50648. this.action = action;
  50649. this.onlyOnce = onlyOnce;
  50650. /**
  50651. * Specifies if the animation event is done
  50652. */
  50653. this.isDone = false;
  50654. }
  50655. /** @hidden */
  50656. AnimationEvent.prototype._clone = function () {
  50657. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50658. };
  50659. return AnimationEvent;
  50660. }());
  50661. BABYLON.AnimationEvent = AnimationEvent;
  50662. /**
  50663. * A cursor which tracks a point on a path
  50664. */
  50665. var PathCursor = /** @class */ (function () {
  50666. /**
  50667. * Initializes the path cursor
  50668. * @param path The path to track
  50669. */
  50670. function PathCursor(path) {
  50671. this.path = path;
  50672. /**
  50673. * Stores path cursor callbacks for when an onchange event is triggered
  50674. */
  50675. this._onchange = new Array();
  50676. /**
  50677. * The value of the path cursor
  50678. */
  50679. this.value = 0;
  50680. /**
  50681. * The animation array of the path cursor
  50682. */
  50683. this.animations = new Array();
  50684. }
  50685. /**
  50686. * Gets the cursor point on the path
  50687. * @returns A point on the path cursor at the cursor location
  50688. */
  50689. PathCursor.prototype.getPoint = function () {
  50690. var point = this.path.getPointAtLengthPosition(this.value);
  50691. return new BABYLON.Vector3(point.x, 0, point.y);
  50692. };
  50693. /**
  50694. * Moves the cursor ahead by the step amount
  50695. * @param step The amount to move the cursor forward
  50696. * @returns This path cursor
  50697. */
  50698. PathCursor.prototype.moveAhead = function (step) {
  50699. if (step === void 0) { step = 0.002; }
  50700. this.move(step);
  50701. return this;
  50702. };
  50703. /**
  50704. * Moves the cursor behind by the step amount
  50705. * @param step The amount to move the cursor back
  50706. * @returns This path cursor
  50707. */
  50708. PathCursor.prototype.moveBack = function (step) {
  50709. if (step === void 0) { step = 0.002; }
  50710. this.move(-step);
  50711. return this;
  50712. };
  50713. /**
  50714. * Moves the cursor by the step amount
  50715. * If the step amount is greater than one, an exception is thrown
  50716. * @param step The amount to move the cursor
  50717. * @returns This path cursor
  50718. */
  50719. PathCursor.prototype.move = function (step) {
  50720. if (Math.abs(step) > 1) {
  50721. throw "step size should be less than 1.";
  50722. }
  50723. this.value += step;
  50724. this.ensureLimits();
  50725. this.raiseOnChange();
  50726. return this;
  50727. };
  50728. /**
  50729. * Ensures that the value is limited between zero and one
  50730. * @returns This path cursor
  50731. */
  50732. PathCursor.prototype.ensureLimits = function () {
  50733. while (this.value > 1) {
  50734. this.value -= 1;
  50735. }
  50736. while (this.value < 0) {
  50737. this.value += 1;
  50738. }
  50739. return this;
  50740. };
  50741. /**
  50742. * Runs onchange callbacks on change (used by the animation engine)
  50743. * @returns This path cursor
  50744. */
  50745. PathCursor.prototype.raiseOnChange = function () {
  50746. var _this = this;
  50747. this._onchange.forEach(function (f) { return f(_this); });
  50748. return this;
  50749. };
  50750. /**
  50751. * Executes a function on change
  50752. * @param f A path cursor onchange callback
  50753. * @returns This path cursor
  50754. */
  50755. PathCursor.prototype.onchange = function (f) {
  50756. this._onchange.push(f);
  50757. return this;
  50758. };
  50759. return PathCursor;
  50760. }());
  50761. BABYLON.PathCursor = PathCursor;
  50762. /**
  50763. * Enum for the animation key frame interpolation type
  50764. */
  50765. var AnimationKeyInterpolation;
  50766. (function (AnimationKeyInterpolation) {
  50767. /**
  50768. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50769. */
  50770. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50771. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50772. /**
  50773. * Class used to store any kind of animation
  50774. */
  50775. var Animation = /** @class */ (function () {
  50776. /**
  50777. * Initializes the animation
  50778. * @param name Name of the animation
  50779. * @param targetProperty Property to animate
  50780. * @param framePerSecond The frames per second of the animation
  50781. * @param dataType The data type of the animation
  50782. * @param loopMode The loop mode of the animation
  50783. * @param enableBlendings Specifies if blending should be enabled
  50784. */
  50785. function Animation(
  50786. /**Name of the animation */
  50787. name,
  50788. /**Property to animate */
  50789. targetProperty,
  50790. /**The frames per second of the animation */
  50791. framePerSecond,
  50792. /**The data type of the animation */
  50793. dataType,
  50794. /**The loop mode of the animation */
  50795. loopMode,
  50796. /**Specifies if blending should be enabled */
  50797. enableBlending) {
  50798. this.name = name;
  50799. this.targetProperty = targetProperty;
  50800. this.framePerSecond = framePerSecond;
  50801. this.dataType = dataType;
  50802. this.loopMode = loopMode;
  50803. this.enableBlending = enableBlending;
  50804. /**
  50805. * @hidden Internal use only
  50806. */
  50807. this._runtimeAnimations = new Array();
  50808. /**
  50809. * The set of event that will be linked to this animation
  50810. */
  50811. this._events = new Array();
  50812. /**
  50813. * Stores the blending speed of the animation
  50814. */
  50815. this.blendingSpeed = 0.01;
  50816. /**
  50817. * Stores the animation ranges for the animation
  50818. */
  50819. this._ranges = {};
  50820. this.targetPropertyPath = targetProperty.split(".");
  50821. this.dataType = dataType;
  50822. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50823. }
  50824. /**
  50825. * @hidden Internal use
  50826. */
  50827. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50828. var dataType = undefined;
  50829. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50830. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50831. }
  50832. else if (from instanceof BABYLON.Quaternion) {
  50833. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50834. }
  50835. else if (from instanceof BABYLON.Vector3) {
  50836. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50837. }
  50838. else if (from instanceof BABYLON.Vector2) {
  50839. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50840. }
  50841. else if (from instanceof BABYLON.Color3) {
  50842. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50843. }
  50844. else if (from instanceof BABYLON.Size) {
  50845. dataType = Animation.ANIMATIONTYPE_SIZE;
  50846. }
  50847. if (dataType == undefined) {
  50848. return null;
  50849. }
  50850. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50851. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50852. animation.setKeys(keys);
  50853. if (easingFunction !== undefined) {
  50854. animation.setEasingFunction(easingFunction);
  50855. }
  50856. return animation;
  50857. };
  50858. /**
  50859. * Sets up an animation
  50860. * @param property The property to animate
  50861. * @param animationType The animation type to apply
  50862. * @param framePerSecond The frames per second of the animation
  50863. * @param easingFunction The easing function used in the animation
  50864. * @returns The created animation
  50865. */
  50866. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50867. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50868. animation.setEasingFunction(easingFunction);
  50869. return animation;
  50870. };
  50871. /**
  50872. * Create and start an animation on a node
  50873. * @param name defines the name of the global animation that will be run on all nodes
  50874. * @param node defines the root node where the animation will take place
  50875. * @param targetProperty defines property to animate
  50876. * @param framePerSecond defines the number of frame per second yo use
  50877. * @param totalFrame defines the number of frames in total
  50878. * @param from defines the initial value
  50879. * @param to defines the final value
  50880. * @param loopMode defines which loop mode you want to use (off by default)
  50881. * @param easingFunction defines the easing function to use (linear by default)
  50882. * @param onAnimationEnd defines the callback to call when animation end
  50883. * @returns the animatable created for this animation
  50884. */
  50885. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50886. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50887. if (!animation) {
  50888. return null;
  50889. }
  50890. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50891. };
  50892. /**
  50893. * Create and start an animation on a node and its descendants
  50894. * @param name defines the name of the global animation that will be run on all nodes
  50895. * @param node defines the root node where the animation will take place
  50896. * @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
  50897. * @param targetProperty defines property to animate
  50898. * @param framePerSecond defines the number of frame per second to use
  50899. * @param totalFrame defines the number of frames in total
  50900. * @param from defines the initial value
  50901. * @param to defines the final value
  50902. * @param loopMode defines which loop mode you want to use (off by default)
  50903. * @param easingFunction defines the easing function to use (linear by default)
  50904. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50905. * @returns the list of animatables created for all nodes
  50906. * @example https://www.babylonjs-playground.com/#MH0VLI
  50907. */
  50908. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50909. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50910. if (!animation) {
  50911. return null;
  50912. }
  50913. var scene = node.getScene();
  50914. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50915. };
  50916. /**
  50917. * Creates a new animation, merges it with the existing animations and starts it
  50918. * @param name Name of the animation
  50919. * @param node Node which contains the scene that begins the animations
  50920. * @param targetProperty Specifies which property to animate
  50921. * @param framePerSecond The frames per second of the animation
  50922. * @param totalFrame The total number of frames
  50923. * @param from The frame at the beginning of the animation
  50924. * @param to The frame at the end of the animation
  50925. * @param loopMode Specifies the loop mode of the animation
  50926. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50927. * @param onAnimationEnd Callback to run once the animation is complete
  50928. * @returns Nullable animation
  50929. */
  50930. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50931. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50932. if (!animation) {
  50933. return null;
  50934. }
  50935. node.animations.push(animation);
  50936. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50937. };
  50938. /**
  50939. * Transition property of an host to the target Value
  50940. * @param property The property to transition
  50941. * @param targetValue The target Value of the property
  50942. * @param host The object where the property to animate belongs
  50943. * @param scene Scene used to run the animation
  50944. * @param frameRate Framerate (in frame/s) to use
  50945. * @param transition The transition type we want to use
  50946. * @param duration The duration of the animation, in milliseconds
  50947. * @param onAnimationEnd Callback trigger at the end of the animation
  50948. * @returns Nullable animation
  50949. */
  50950. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50951. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50952. if (duration <= 0) {
  50953. host[property] = targetValue;
  50954. if (onAnimationEnd) {
  50955. onAnimationEnd();
  50956. }
  50957. return null;
  50958. }
  50959. var endFrame = frameRate * (duration / 1000);
  50960. transition.setKeys([{
  50961. frame: 0,
  50962. value: host[property].clone ? host[property].clone() : host[property]
  50963. },
  50964. {
  50965. frame: endFrame,
  50966. value: targetValue
  50967. }]);
  50968. if (!host.animations) {
  50969. host.animations = [];
  50970. }
  50971. host.animations.push(transition);
  50972. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50973. animation.onAnimationEnd = onAnimationEnd;
  50974. return animation;
  50975. };
  50976. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50977. /**
  50978. * Return the array of runtime animations currently using this animation
  50979. */
  50980. get: function () {
  50981. return this._runtimeAnimations;
  50982. },
  50983. enumerable: true,
  50984. configurable: true
  50985. });
  50986. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50987. /**
  50988. * Specifies if any of the runtime animations are currently running
  50989. */
  50990. get: function () {
  50991. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50992. var runtimeAnimation = _a[_i];
  50993. if (!runtimeAnimation.isStopped) {
  50994. return true;
  50995. }
  50996. }
  50997. return false;
  50998. },
  50999. enumerable: true,
  51000. configurable: true
  51001. });
  51002. // Methods
  51003. /**
  51004. * Converts the animation to a string
  51005. * @param fullDetails support for multiple levels of logging within scene loading
  51006. * @returns String form of the animation
  51007. */
  51008. Animation.prototype.toString = function (fullDetails) {
  51009. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  51010. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  51011. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  51012. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  51013. if (fullDetails) {
  51014. ret += ", Ranges: {";
  51015. var first = true;
  51016. for (var name in this._ranges) {
  51017. if (first) {
  51018. ret += ", ";
  51019. first = false;
  51020. }
  51021. ret += name;
  51022. }
  51023. ret += "}";
  51024. }
  51025. return ret;
  51026. };
  51027. /**
  51028. * Add an event to this animation
  51029. * @param event Event to add
  51030. */
  51031. Animation.prototype.addEvent = function (event) {
  51032. this._events.push(event);
  51033. };
  51034. /**
  51035. * Remove all events found at the given frame
  51036. * @param frame The frame to remove events from
  51037. */
  51038. Animation.prototype.removeEvents = function (frame) {
  51039. for (var index = 0; index < this._events.length; index++) {
  51040. if (this._events[index].frame === frame) {
  51041. this._events.splice(index, 1);
  51042. index--;
  51043. }
  51044. }
  51045. };
  51046. /**
  51047. * Retrieves all the events from the animation
  51048. * @returns Events from the animation
  51049. */
  51050. Animation.prototype.getEvents = function () {
  51051. return this._events;
  51052. };
  51053. /**
  51054. * Creates an animation range
  51055. * @param name Name of the animation range
  51056. * @param from Starting frame of the animation range
  51057. * @param to Ending frame of the animation
  51058. */
  51059. Animation.prototype.createRange = function (name, from, to) {
  51060. // check name not already in use; could happen for bones after serialized
  51061. if (!this._ranges[name]) {
  51062. this._ranges[name] = new AnimationRange(name, from, to);
  51063. }
  51064. };
  51065. /**
  51066. * Deletes an animation range by name
  51067. * @param name Name of the animation range to delete
  51068. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  51069. */
  51070. Animation.prototype.deleteRange = function (name, deleteFrames) {
  51071. if (deleteFrames === void 0) { deleteFrames = true; }
  51072. var range = this._ranges[name];
  51073. if (!range) {
  51074. return;
  51075. }
  51076. if (deleteFrames) {
  51077. var from = range.from;
  51078. var to = range.to;
  51079. // this loop MUST go high to low for multiple splices to work
  51080. for (var key = this._keys.length - 1; key >= 0; key--) {
  51081. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  51082. this._keys.splice(key, 1);
  51083. }
  51084. }
  51085. }
  51086. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  51087. };
  51088. /**
  51089. * Gets the animation range by name, or null if not defined
  51090. * @param name Name of the animation range
  51091. * @returns Nullable animation range
  51092. */
  51093. Animation.prototype.getRange = function (name) {
  51094. return this._ranges[name];
  51095. };
  51096. /**
  51097. * Gets the key frames from the animation
  51098. * @returns The key frames of the animation
  51099. */
  51100. Animation.prototype.getKeys = function () {
  51101. return this._keys;
  51102. };
  51103. /**
  51104. * Gets the highest frame rate of the animation
  51105. * @returns Highest frame rate of the animation
  51106. */
  51107. Animation.prototype.getHighestFrame = function () {
  51108. var ret = 0;
  51109. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  51110. if (ret < this._keys[key].frame) {
  51111. ret = this._keys[key].frame;
  51112. }
  51113. }
  51114. return ret;
  51115. };
  51116. /**
  51117. * Gets the easing function of the animation
  51118. * @returns Easing function of the animation
  51119. */
  51120. Animation.prototype.getEasingFunction = function () {
  51121. return this._easingFunction;
  51122. };
  51123. /**
  51124. * Sets the easing function of the animation
  51125. * @param easingFunction A custom mathematical formula for animation
  51126. */
  51127. Animation.prototype.setEasingFunction = function (easingFunction) {
  51128. this._easingFunction = easingFunction;
  51129. };
  51130. /**
  51131. * Interpolates a scalar linearly
  51132. * @param startValue Start value of the animation curve
  51133. * @param endValue End value of the animation curve
  51134. * @param gradient Scalar amount to interpolate
  51135. * @returns Interpolated scalar value
  51136. */
  51137. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  51138. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  51139. };
  51140. /**
  51141. * Interpolates a scalar cubically
  51142. * @param startValue Start value of the animation curve
  51143. * @param outTangent End tangent of the animation
  51144. * @param endValue End value of the animation curve
  51145. * @param inTangent Start tangent of the animation curve
  51146. * @param gradient Scalar amount to interpolate
  51147. * @returns Interpolated scalar value
  51148. */
  51149. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51150. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51151. };
  51152. /**
  51153. * Interpolates a quaternion using a spherical linear interpolation
  51154. * @param startValue Start value of the animation curve
  51155. * @param endValue End value of the animation curve
  51156. * @param gradient Scalar amount to interpolate
  51157. * @returns Interpolated quaternion value
  51158. */
  51159. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  51160. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  51161. };
  51162. /**
  51163. * Interpolates a quaternion cubically
  51164. * @param startValue Start value of the animation curve
  51165. * @param outTangent End tangent of the animation curve
  51166. * @param endValue End value of the animation curve
  51167. * @param inTangent Start tangent of the animation curve
  51168. * @param gradient Scalar amount to interpolate
  51169. * @returns Interpolated quaternion value
  51170. */
  51171. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51172. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  51173. };
  51174. /**
  51175. * Interpolates a Vector3 linearl
  51176. * @param startValue Start value of the animation curve
  51177. * @param endValue End value of the animation curve
  51178. * @param gradient Scalar amount to interpolate
  51179. * @returns Interpolated scalar value
  51180. */
  51181. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  51182. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  51183. };
  51184. /**
  51185. * Interpolates a Vector3 cubically
  51186. * @param startValue Start value of the animation curve
  51187. * @param outTangent End tangent of the animation
  51188. * @param endValue End value of the animation curve
  51189. * @param inTangent Start tangent of the animation curve
  51190. * @param gradient Scalar amount to interpolate
  51191. * @returns InterpolatedVector3 value
  51192. */
  51193. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51194. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51195. };
  51196. /**
  51197. * Interpolates a Vector2 linearly
  51198. * @param startValue Start value of the animation curve
  51199. * @param endValue End value of the animation curve
  51200. * @param gradient Scalar amount to interpolate
  51201. * @returns Interpolated Vector2 value
  51202. */
  51203. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  51204. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  51205. };
  51206. /**
  51207. * Interpolates a Vector2 cubically
  51208. * @param startValue Start value of the animation curve
  51209. * @param outTangent End tangent of the animation
  51210. * @param endValue End value of the animation curve
  51211. * @param inTangent Start tangent of the animation curve
  51212. * @param gradient Scalar amount to interpolate
  51213. * @returns Interpolated Vector2 value
  51214. */
  51215. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51216. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51217. };
  51218. /**
  51219. * Interpolates a size linearly
  51220. * @param startValue Start value of the animation curve
  51221. * @param endValue End value of the animation curve
  51222. * @param gradient Scalar amount to interpolate
  51223. * @returns Interpolated Size value
  51224. */
  51225. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  51226. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  51227. };
  51228. /**
  51229. * Interpolates a Color3 linearly
  51230. * @param startValue Start value of the animation curve
  51231. * @param endValue End value of the animation curve
  51232. * @param gradient Scalar amount to interpolate
  51233. * @returns Interpolated Color3 value
  51234. */
  51235. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  51236. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  51237. };
  51238. /**
  51239. * @hidden Internal use only
  51240. */
  51241. Animation.prototype._getKeyValue = function (value) {
  51242. if (typeof value === "function") {
  51243. return value();
  51244. }
  51245. return value;
  51246. };
  51247. /**
  51248. * @hidden Internal use only
  51249. */
  51250. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  51251. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  51252. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  51253. }
  51254. var keys = this.getKeys();
  51255. // Try to get a hash to find the right key
  51256. 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));
  51257. if (keys[startKeyIndex].frame >= currentFrame) {
  51258. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  51259. startKeyIndex--;
  51260. }
  51261. }
  51262. for (var key = startKeyIndex; key < keys.length; key++) {
  51263. var endKey = keys[key + 1];
  51264. if (endKey.frame >= currentFrame) {
  51265. var startKey = keys[key];
  51266. var startValue = this._getKeyValue(startKey.value);
  51267. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51268. return startValue;
  51269. }
  51270. var endValue = this._getKeyValue(endKey.value);
  51271. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51272. var frameDelta = endKey.frame - startKey.frame;
  51273. // gradient : percent of currentFrame between the frame inf and the frame sup
  51274. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51275. // check for easingFunction and correction of gradient
  51276. var easingFunction = this.getEasingFunction();
  51277. if (easingFunction != null) {
  51278. gradient = easingFunction.ease(gradient);
  51279. }
  51280. switch (this.dataType) {
  51281. // Float
  51282. case Animation.ANIMATIONTYPE_FLOAT:
  51283. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51284. switch (loopMode) {
  51285. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51286. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51287. return floatValue;
  51288. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51289. return offsetValue * repeatCount + floatValue;
  51290. }
  51291. break;
  51292. // Quaternion
  51293. case Animation.ANIMATIONTYPE_QUATERNION:
  51294. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51295. switch (loopMode) {
  51296. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51297. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51298. return quatValue;
  51299. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51300. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51301. }
  51302. return quatValue;
  51303. // Vector3
  51304. case Animation.ANIMATIONTYPE_VECTOR3:
  51305. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51306. switch (loopMode) {
  51307. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51308. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51309. return vec3Value;
  51310. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51311. return vec3Value.add(offsetValue.scale(repeatCount));
  51312. }
  51313. // Vector2
  51314. case Animation.ANIMATIONTYPE_VECTOR2:
  51315. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51316. switch (loopMode) {
  51317. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51318. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51319. return vec2Value;
  51320. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51321. return vec2Value.add(offsetValue.scale(repeatCount));
  51322. }
  51323. // Size
  51324. case Animation.ANIMATIONTYPE_SIZE:
  51325. switch (loopMode) {
  51326. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51327. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51328. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51329. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51330. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51331. }
  51332. // Color3
  51333. case Animation.ANIMATIONTYPE_COLOR3:
  51334. switch (loopMode) {
  51335. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51336. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51337. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51338. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51339. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51340. }
  51341. // Matrix
  51342. case Animation.ANIMATIONTYPE_MATRIX:
  51343. switch (loopMode) {
  51344. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51345. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51346. if (Animation.AllowMatricesInterpolation) {
  51347. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51348. }
  51349. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51350. return startValue;
  51351. }
  51352. default:
  51353. break;
  51354. }
  51355. break;
  51356. }
  51357. }
  51358. return this._getKeyValue(keys[keys.length - 1].value);
  51359. };
  51360. /**
  51361. * Defines the function to use to interpolate matrices
  51362. * @param startValue defines the start matrix
  51363. * @param endValue defines the end matrix
  51364. * @param gradient defines the gradient between both matrices
  51365. * @param result defines an optional target matrix where to store the interpolation
  51366. * @returns the interpolated matrix
  51367. */
  51368. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51369. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51370. if (result) {
  51371. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51372. return result;
  51373. }
  51374. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51375. }
  51376. if (result) {
  51377. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51378. return result;
  51379. }
  51380. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51381. };
  51382. /**
  51383. * Makes a copy of the animation
  51384. * @returns Cloned animation
  51385. */
  51386. Animation.prototype.clone = function () {
  51387. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51388. clone.enableBlending = this.enableBlending;
  51389. clone.blendingSpeed = this.blendingSpeed;
  51390. if (this._keys) {
  51391. clone.setKeys(this._keys);
  51392. }
  51393. if (this._ranges) {
  51394. clone._ranges = {};
  51395. for (var name in this._ranges) {
  51396. var range = this._ranges[name];
  51397. if (!range) {
  51398. continue;
  51399. }
  51400. clone._ranges[name] = range.clone();
  51401. }
  51402. }
  51403. return clone;
  51404. };
  51405. /**
  51406. * Sets the key frames of the animation
  51407. * @param values The animation key frames to set
  51408. */
  51409. Animation.prototype.setKeys = function (values) {
  51410. this._keys = values.slice(0);
  51411. };
  51412. /**
  51413. * Serializes the animation to an object
  51414. * @returns Serialized object
  51415. */
  51416. Animation.prototype.serialize = function () {
  51417. var serializationObject = {};
  51418. serializationObject.name = this.name;
  51419. serializationObject.property = this.targetProperty;
  51420. serializationObject.framePerSecond = this.framePerSecond;
  51421. serializationObject.dataType = this.dataType;
  51422. serializationObject.loopBehavior = this.loopMode;
  51423. serializationObject.enableBlending = this.enableBlending;
  51424. serializationObject.blendingSpeed = this.blendingSpeed;
  51425. var dataType = this.dataType;
  51426. serializationObject.keys = [];
  51427. var keys = this.getKeys();
  51428. for (var index = 0; index < keys.length; index++) {
  51429. var animationKey = keys[index];
  51430. var key = {};
  51431. key.frame = animationKey.frame;
  51432. switch (dataType) {
  51433. case Animation.ANIMATIONTYPE_FLOAT:
  51434. key.values = [animationKey.value];
  51435. break;
  51436. case Animation.ANIMATIONTYPE_QUATERNION:
  51437. case Animation.ANIMATIONTYPE_MATRIX:
  51438. case Animation.ANIMATIONTYPE_VECTOR3:
  51439. case Animation.ANIMATIONTYPE_COLOR3:
  51440. key.values = animationKey.value.asArray();
  51441. break;
  51442. }
  51443. serializationObject.keys.push(key);
  51444. }
  51445. serializationObject.ranges = [];
  51446. for (var name in this._ranges) {
  51447. var source = this._ranges[name];
  51448. if (!source) {
  51449. continue;
  51450. }
  51451. var range = {};
  51452. range.name = name;
  51453. range.from = source.from;
  51454. range.to = source.to;
  51455. serializationObject.ranges.push(range);
  51456. }
  51457. return serializationObject;
  51458. };
  51459. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51460. /**
  51461. * Get the float animation type
  51462. */
  51463. get: function () {
  51464. return Animation._ANIMATIONTYPE_FLOAT;
  51465. },
  51466. enumerable: true,
  51467. configurable: true
  51468. });
  51469. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51470. /**
  51471. * Get the Vector3 animation type
  51472. */
  51473. get: function () {
  51474. return Animation._ANIMATIONTYPE_VECTOR3;
  51475. },
  51476. enumerable: true,
  51477. configurable: true
  51478. });
  51479. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51480. /**
  51481. * Get the Vector2 animation type
  51482. */
  51483. get: function () {
  51484. return Animation._ANIMATIONTYPE_VECTOR2;
  51485. },
  51486. enumerable: true,
  51487. configurable: true
  51488. });
  51489. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51490. /**
  51491. * Get the Size animation type
  51492. */
  51493. get: function () {
  51494. return Animation._ANIMATIONTYPE_SIZE;
  51495. },
  51496. enumerable: true,
  51497. configurable: true
  51498. });
  51499. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51500. /**
  51501. * Get the Quaternion animation type
  51502. */
  51503. get: function () {
  51504. return Animation._ANIMATIONTYPE_QUATERNION;
  51505. },
  51506. enumerable: true,
  51507. configurable: true
  51508. });
  51509. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51510. /**
  51511. * Get the Matrix animation type
  51512. */
  51513. get: function () {
  51514. return Animation._ANIMATIONTYPE_MATRIX;
  51515. },
  51516. enumerable: true,
  51517. configurable: true
  51518. });
  51519. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51520. /**
  51521. * Get the Color3 animation type
  51522. */
  51523. get: function () {
  51524. return Animation._ANIMATIONTYPE_COLOR3;
  51525. },
  51526. enumerable: true,
  51527. configurable: true
  51528. });
  51529. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51530. /**
  51531. * Get the Relative Loop Mode
  51532. */
  51533. get: function () {
  51534. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51535. },
  51536. enumerable: true,
  51537. configurable: true
  51538. });
  51539. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51540. /**
  51541. * Get the Cycle Loop Mode
  51542. */
  51543. get: function () {
  51544. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51545. },
  51546. enumerable: true,
  51547. configurable: true
  51548. });
  51549. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51550. /**
  51551. * Get the Constant Loop Mode
  51552. */
  51553. get: function () {
  51554. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51555. },
  51556. enumerable: true,
  51557. configurable: true
  51558. });
  51559. /** @hidden */
  51560. Animation._UniversalLerp = function (left, right, amount) {
  51561. var constructor = left.constructor;
  51562. if (constructor.Lerp) { // Lerp supported
  51563. return constructor.Lerp(left, right, amount);
  51564. }
  51565. else if (constructor.Slerp) { // Slerp supported
  51566. return constructor.Slerp(left, right, amount);
  51567. }
  51568. else if (left.toFixed) { // Number
  51569. return left * (1.0 - amount) + amount * right;
  51570. }
  51571. else { // Blending not supported
  51572. return right;
  51573. }
  51574. };
  51575. /**
  51576. * Parses an animation object and creates an animation
  51577. * @param parsedAnimation Parsed animation object
  51578. * @returns Animation object
  51579. */
  51580. Animation.Parse = function (parsedAnimation) {
  51581. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51582. var dataType = parsedAnimation.dataType;
  51583. var keys = [];
  51584. var data;
  51585. var index;
  51586. if (parsedAnimation.enableBlending) {
  51587. animation.enableBlending = parsedAnimation.enableBlending;
  51588. }
  51589. if (parsedAnimation.blendingSpeed) {
  51590. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51591. }
  51592. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51593. var key = parsedAnimation.keys[index];
  51594. var inTangent;
  51595. var outTangent;
  51596. switch (dataType) {
  51597. case Animation.ANIMATIONTYPE_FLOAT:
  51598. data = key.values[0];
  51599. if (key.values.length >= 1) {
  51600. inTangent = key.values[1];
  51601. }
  51602. if (key.values.length >= 2) {
  51603. outTangent = key.values[2];
  51604. }
  51605. break;
  51606. case Animation.ANIMATIONTYPE_QUATERNION:
  51607. data = BABYLON.Quaternion.FromArray(key.values);
  51608. if (key.values.length >= 8) {
  51609. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51610. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51611. inTangent = _inTangent;
  51612. }
  51613. }
  51614. if (key.values.length >= 12) {
  51615. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51616. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51617. outTangent = _outTangent;
  51618. }
  51619. }
  51620. break;
  51621. case Animation.ANIMATIONTYPE_MATRIX:
  51622. data = BABYLON.Matrix.FromArray(key.values);
  51623. break;
  51624. case Animation.ANIMATIONTYPE_COLOR3:
  51625. data = BABYLON.Color3.FromArray(key.values);
  51626. break;
  51627. case Animation.ANIMATIONTYPE_VECTOR3:
  51628. default:
  51629. data = BABYLON.Vector3.FromArray(key.values);
  51630. break;
  51631. }
  51632. var keyData = {};
  51633. keyData.frame = key.frame;
  51634. keyData.value = data;
  51635. if (inTangent != undefined) {
  51636. keyData.inTangent = inTangent;
  51637. }
  51638. if (outTangent != undefined) {
  51639. keyData.outTangent = outTangent;
  51640. }
  51641. keys.push(keyData);
  51642. }
  51643. animation.setKeys(keys);
  51644. if (parsedAnimation.ranges) {
  51645. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51646. data = parsedAnimation.ranges[index];
  51647. animation.createRange(data.name, data.from, data.to);
  51648. }
  51649. }
  51650. return animation;
  51651. };
  51652. /**
  51653. * Appends the serialized animations from the source animations
  51654. * @param source Source containing the animations
  51655. * @param destination Target to store the animations
  51656. */
  51657. Animation.AppendSerializedAnimations = function (source, destination) {
  51658. if (source.animations) {
  51659. destination.animations = [];
  51660. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51661. var animation = source.animations[animationIndex];
  51662. destination.animations.push(animation.serialize());
  51663. }
  51664. }
  51665. };
  51666. /**
  51667. * Use matrix interpolation instead of using direct key value when animating matrices
  51668. */
  51669. Animation.AllowMatricesInterpolation = false;
  51670. /**
  51671. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51672. */
  51673. Animation.AllowMatrixDecomposeForInterpolation = true;
  51674. // Statics
  51675. /**
  51676. * Float animation type
  51677. */
  51678. Animation._ANIMATIONTYPE_FLOAT = 0;
  51679. /**
  51680. * Vector3 animation type
  51681. */
  51682. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51683. /**
  51684. * Quaternion animation type
  51685. */
  51686. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51687. /**
  51688. * Matrix animation type
  51689. */
  51690. Animation._ANIMATIONTYPE_MATRIX = 3;
  51691. /**
  51692. * Color3 animation type
  51693. */
  51694. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51695. /**
  51696. * Vector2 animation type
  51697. */
  51698. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51699. /**
  51700. * Size animation type
  51701. */
  51702. Animation._ANIMATIONTYPE_SIZE = 6;
  51703. /**
  51704. * Relative Loop Mode
  51705. */
  51706. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51707. /**
  51708. * Cycle Loop Mode
  51709. */
  51710. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51711. /**
  51712. * Constant Loop Mode
  51713. */
  51714. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51715. return Animation;
  51716. }());
  51717. BABYLON.Animation = Animation;
  51718. })(BABYLON || (BABYLON = {}));
  51719. //# sourceMappingURL=babylon.animation.js.map
  51720. var BABYLON;
  51721. (function (BABYLON) {
  51722. /**
  51723. * This class defines the direct association between an animation and a target
  51724. */
  51725. var TargetedAnimation = /** @class */ (function () {
  51726. function TargetedAnimation() {
  51727. }
  51728. return TargetedAnimation;
  51729. }());
  51730. BABYLON.TargetedAnimation = TargetedAnimation;
  51731. /**
  51732. * Use this class to create coordinated animations on multiple targets
  51733. */
  51734. var AnimationGroup = /** @class */ (function () {
  51735. /**
  51736. * Instantiates a new Animation Group.
  51737. * This helps managing several animations at once.
  51738. * @see http://doc.babylonjs.com/how_to/group
  51739. * @param name Defines the name of the group
  51740. * @param scene Defines the scene the group belongs to
  51741. */
  51742. function AnimationGroup(
  51743. /** The name of the animation group */
  51744. name, scene) {
  51745. if (scene === void 0) { scene = null; }
  51746. this.name = name;
  51747. this._targetedAnimations = new Array();
  51748. this._animatables = new Array();
  51749. this._from = Number.MAX_VALUE;
  51750. this._to = -Number.MAX_VALUE;
  51751. this._speedRatio = 1;
  51752. /**
  51753. * This observable will notify when one animation have ended.
  51754. */
  51755. this.onAnimationEndObservable = new BABYLON.Observable();
  51756. /**
  51757. * This observable will notify when all animations have ended.
  51758. */
  51759. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  51760. /**
  51761. * This observable will notify when all animations have paused.
  51762. */
  51763. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  51764. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51765. this._scene.animationGroups.push(this);
  51766. }
  51767. Object.defineProperty(AnimationGroup.prototype, "from", {
  51768. /**
  51769. * Gets the first frame
  51770. */
  51771. get: function () {
  51772. return this._from;
  51773. },
  51774. enumerable: true,
  51775. configurable: true
  51776. });
  51777. Object.defineProperty(AnimationGroup.prototype, "to", {
  51778. /**
  51779. * Gets the last frame
  51780. */
  51781. get: function () {
  51782. return this._to;
  51783. },
  51784. enumerable: true,
  51785. configurable: true
  51786. });
  51787. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51788. /**
  51789. * Define if the animations are started
  51790. */
  51791. get: function () {
  51792. return this._isStarted;
  51793. },
  51794. enumerable: true,
  51795. configurable: true
  51796. });
  51797. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51798. /**
  51799. * Gets or sets the speed ratio to use for all animations
  51800. */
  51801. get: function () {
  51802. return this._speedRatio;
  51803. },
  51804. /**
  51805. * Gets or sets the speed ratio to use for all animations
  51806. */
  51807. set: function (value) {
  51808. if (this._speedRatio === value) {
  51809. return;
  51810. }
  51811. this._speedRatio = value;
  51812. for (var index = 0; index < this._animatables.length; index++) {
  51813. var animatable = this._animatables[index];
  51814. animatable.speedRatio = this._speedRatio;
  51815. }
  51816. },
  51817. enumerable: true,
  51818. configurable: true
  51819. });
  51820. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51821. /**
  51822. * Gets the targeted animations for this animation group
  51823. */
  51824. get: function () {
  51825. return this._targetedAnimations;
  51826. },
  51827. enumerable: true,
  51828. configurable: true
  51829. });
  51830. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51831. /**
  51832. * returning the list of animatables controlled by this animation group.
  51833. */
  51834. get: function () {
  51835. return this._animatables;
  51836. },
  51837. enumerable: true,
  51838. configurable: true
  51839. });
  51840. /**
  51841. * Add an animation (with its target) in the group
  51842. * @param animation defines the animation we want to add
  51843. * @param target defines the target of the animation
  51844. * @returns the {BABYLON.TargetedAnimation} object
  51845. */
  51846. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51847. var targetedAnimation = {
  51848. animation: animation,
  51849. target: target
  51850. };
  51851. var keys = animation.getKeys();
  51852. if (this._from > keys[0].frame) {
  51853. this._from = keys[0].frame;
  51854. }
  51855. if (this._to < keys[keys.length - 1].frame) {
  51856. this._to = keys[keys.length - 1].frame;
  51857. }
  51858. this._targetedAnimations.push(targetedAnimation);
  51859. return targetedAnimation;
  51860. };
  51861. /**
  51862. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51863. * It can add constant keys at begin or end
  51864. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51865. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51866. * @returns the animation group
  51867. */
  51868. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51869. if (beginFrame === void 0) { beginFrame = null; }
  51870. if (endFrame === void 0) { endFrame = null; }
  51871. if (beginFrame == null)
  51872. beginFrame = this._from;
  51873. if (endFrame == null)
  51874. endFrame = this._to;
  51875. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51876. var targetedAnimation = this._targetedAnimations[index];
  51877. var keys = targetedAnimation.animation.getKeys();
  51878. var startKey = keys[0];
  51879. var endKey = keys[keys.length - 1];
  51880. if (startKey.frame > beginFrame) {
  51881. var newKey = {
  51882. frame: beginFrame,
  51883. value: startKey.value,
  51884. inTangent: startKey.inTangent,
  51885. outTangent: startKey.outTangent,
  51886. interpolation: startKey.interpolation
  51887. };
  51888. keys.splice(0, 0, newKey);
  51889. }
  51890. if (endKey.frame < endFrame) {
  51891. var newKey = {
  51892. frame: endFrame,
  51893. value: endKey.value,
  51894. inTangent: endKey.outTangent,
  51895. outTangent: endKey.outTangent,
  51896. interpolation: endKey.interpolation
  51897. };
  51898. keys.push(newKey);
  51899. }
  51900. }
  51901. this._from = beginFrame;
  51902. this._to = endFrame;
  51903. return this;
  51904. };
  51905. /**
  51906. * Start all animations on given targets
  51907. * @param loop defines if animations must loop
  51908. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51909. * @param from defines the from key (optional)
  51910. * @param to defines the to key (optional)
  51911. * @returns the current animation group
  51912. */
  51913. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51914. var _this = this;
  51915. if (loop === void 0) { loop = false; }
  51916. if (speedRatio === void 0) { speedRatio = 1; }
  51917. if (this._isStarted || this._targetedAnimations.length === 0) {
  51918. return this;
  51919. }
  51920. var _loop_1 = function (targetedAnimation) {
  51921. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51922. animatable.onAnimationEnd = function () {
  51923. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51924. _this._checkAnimationGroupEnded(animatable);
  51925. };
  51926. this_1._animatables.push(animatable);
  51927. };
  51928. var this_1 = this;
  51929. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51930. var targetedAnimation = _a[_i];
  51931. _loop_1(targetedAnimation);
  51932. }
  51933. this._speedRatio = speedRatio;
  51934. this._isStarted = true;
  51935. return this;
  51936. };
  51937. /**
  51938. * Pause all animations
  51939. * @returns the animation group
  51940. */
  51941. AnimationGroup.prototype.pause = function () {
  51942. if (!this._isStarted) {
  51943. return this;
  51944. }
  51945. for (var index = 0; index < this._animatables.length; index++) {
  51946. var animatable = this._animatables[index];
  51947. animatable.pause();
  51948. }
  51949. this.onAnimationGroupPauseObservable.notifyObservers(this);
  51950. return this;
  51951. };
  51952. /**
  51953. * Play all animations to initial state
  51954. * This function will start() the animations if they were not started or will restart() them if they were paused
  51955. * @param loop defines if animations must loop
  51956. * @returns the animation group
  51957. */
  51958. AnimationGroup.prototype.play = function (loop) {
  51959. // only if all animatables are ready and exist
  51960. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51961. if (loop !== undefined) {
  51962. for (var index = 0; index < this._animatables.length; index++) {
  51963. var animatable = this._animatables[index];
  51964. animatable.loopAnimation = loop;
  51965. }
  51966. }
  51967. this.restart();
  51968. }
  51969. else {
  51970. this.stop();
  51971. this.start(loop, this._speedRatio);
  51972. }
  51973. return this;
  51974. };
  51975. /**
  51976. * Reset all animations to initial state
  51977. * @returns the animation group
  51978. */
  51979. AnimationGroup.prototype.reset = function () {
  51980. if (!this._isStarted) {
  51981. return this;
  51982. }
  51983. for (var index = 0; index < this._animatables.length; index++) {
  51984. var animatable = this._animatables[index];
  51985. animatable.reset();
  51986. }
  51987. return this;
  51988. };
  51989. /**
  51990. * Restart animations from key 0
  51991. * @returns the animation group
  51992. */
  51993. AnimationGroup.prototype.restart = function () {
  51994. if (!this._isStarted) {
  51995. return this;
  51996. }
  51997. for (var index = 0; index < this._animatables.length; index++) {
  51998. var animatable = this._animatables[index];
  51999. animatable.restart();
  52000. }
  52001. return this;
  52002. };
  52003. /**
  52004. * Stop all animations
  52005. * @returns the animation group
  52006. */
  52007. AnimationGroup.prototype.stop = function () {
  52008. if (!this._isStarted) {
  52009. return this;
  52010. }
  52011. var list = this._animatables.slice();
  52012. for (var index = 0; index < list.length; index++) {
  52013. list[index].stop();
  52014. }
  52015. this._isStarted = false;
  52016. return this;
  52017. };
  52018. /**
  52019. * Set animation weight for all animatables
  52020. * @param weight defines the weight to use
  52021. * @return the animationGroup
  52022. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52023. */
  52024. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  52025. for (var index = 0; index < this._animatables.length; index++) {
  52026. var animatable = this._animatables[index];
  52027. animatable.weight = weight;
  52028. }
  52029. return this;
  52030. };
  52031. /**
  52032. * Synchronize and normalize all animatables with a source animatable
  52033. * @param root defines the root animatable to synchronize with
  52034. * @return the animationGroup
  52035. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52036. */
  52037. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  52038. for (var index = 0; index < this._animatables.length; index++) {
  52039. var animatable = this._animatables[index];
  52040. animatable.syncWith(root);
  52041. }
  52042. return this;
  52043. };
  52044. /**
  52045. * Goes to a specific frame in this animation group
  52046. * @param frame the frame number to go to
  52047. * @return the animationGroup
  52048. */
  52049. AnimationGroup.prototype.goToFrame = function (frame) {
  52050. if (!this._isStarted) {
  52051. return this;
  52052. }
  52053. for (var index = 0; index < this._animatables.length; index++) {
  52054. var animatable = this._animatables[index];
  52055. animatable.goToFrame(frame);
  52056. }
  52057. return this;
  52058. };
  52059. /**
  52060. * Dispose all associated resources
  52061. */
  52062. AnimationGroup.prototype.dispose = function () {
  52063. this._targetedAnimations = [];
  52064. this._animatables = [];
  52065. var index = this._scene.animationGroups.indexOf(this);
  52066. if (index > -1) {
  52067. this._scene.animationGroups.splice(index, 1);
  52068. }
  52069. };
  52070. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  52071. // animatable should be taken out of the array
  52072. var idx = this._animatables.indexOf(animatable);
  52073. if (idx > -1) {
  52074. this._animatables.splice(idx, 1);
  52075. }
  52076. // all animatables were removed? animation group ended!
  52077. if (this._animatables.length === 0) {
  52078. this._isStarted = false;
  52079. this.onAnimationGroupEndObservable.notifyObservers(this);
  52080. }
  52081. };
  52082. // Statics
  52083. /**
  52084. * Returns a new AnimationGroup object parsed from the source provided.
  52085. * @param parsedAnimationGroup defines the source
  52086. * @param scene defines the scene that will receive the animationGroup
  52087. * @returns a new AnimationGroup
  52088. */
  52089. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  52090. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  52091. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  52092. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  52093. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  52094. var id = targetedAnimation.targetId;
  52095. var targetNode = scene.getNodeByID(id);
  52096. if (targetNode != null)
  52097. animationGroup.addTargetedAnimation(animation, targetNode);
  52098. }
  52099. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  52100. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  52101. return animationGroup;
  52102. };
  52103. /**
  52104. * Returns the string "AnimationGroup"
  52105. * @returns "AnimationGroup"
  52106. */
  52107. AnimationGroup.prototype.getClassName = function () {
  52108. return "AnimationGroup";
  52109. };
  52110. /**
  52111. * Creates a detailled string about the object
  52112. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  52113. * @returns a string representing the object
  52114. */
  52115. AnimationGroup.prototype.toString = function (fullDetails) {
  52116. var ret = "Name: " + this.name;
  52117. ret += ", type: " + this.getClassName();
  52118. if (fullDetails) {
  52119. ret += ", from: " + this._from;
  52120. ret += ", to: " + this._to;
  52121. ret += ", isStarted: " + this._isStarted;
  52122. ret += ", speedRatio: " + this._speedRatio;
  52123. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  52124. ret += ", animatables length: " + this._animatables;
  52125. }
  52126. return ret;
  52127. };
  52128. return AnimationGroup;
  52129. }());
  52130. BABYLON.AnimationGroup = AnimationGroup;
  52131. })(BABYLON || (BABYLON = {}));
  52132. //# sourceMappingURL=babylon.animationGroup.js.map
  52133. var BABYLON;
  52134. (function (BABYLON) {
  52135. // Static values to help the garbage collector
  52136. // Quaternion
  52137. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  52138. // Vector3
  52139. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  52140. // Vector2
  52141. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  52142. // Size
  52143. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  52144. // Color3
  52145. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  52146. /**
  52147. * Defines a runtime animation
  52148. */
  52149. var RuntimeAnimation = /** @class */ (function () {
  52150. /**
  52151. * Create a new RuntimeAnimation object
  52152. * @param target defines the target of the animation
  52153. * @param animation defines the source animation object
  52154. * @param scene defines the hosting scene
  52155. * @param host defines the initiating Animatable
  52156. */
  52157. function RuntimeAnimation(target, animation, scene, host) {
  52158. var _this = this;
  52159. this._events = new Array();
  52160. /**
  52161. * The current frame of the runtime animation
  52162. */
  52163. this._currentFrame = 0;
  52164. /**
  52165. * The original value of the runtime animation
  52166. */
  52167. this._originalValue = new Array();
  52168. /**
  52169. * The offsets cache of the runtime animation
  52170. */
  52171. this._offsetsCache = {};
  52172. /**
  52173. * The high limits cache of the runtime animation
  52174. */
  52175. this._highLimitsCache = {};
  52176. /**
  52177. * Specifies if the runtime animation has been stopped
  52178. */
  52179. this._stopped = false;
  52180. /**
  52181. * The blending factor of the runtime animation
  52182. */
  52183. this._blendingFactor = 0;
  52184. /**
  52185. * The target path of the runtime animation
  52186. */
  52187. this._targetPath = "";
  52188. /**
  52189. * The weight of the runtime animation
  52190. */
  52191. this._weight = 1.0;
  52192. /**
  52193. * The ratio offset of the runtime animation
  52194. */
  52195. this._ratioOffset = 0;
  52196. /**
  52197. * The previous delay of the runtime animation
  52198. */
  52199. this._previousDelay = 0;
  52200. /**
  52201. * The previous ratio of the runtime animation
  52202. */
  52203. this._previousRatio = 0;
  52204. this._animation = animation;
  52205. this._target = target;
  52206. this._scene = scene;
  52207. this._host = host;
  52208. animation._runtimeAnimations.push(this);
  52209. // Cloning events locally
  52210. var events = animation.getEvents();
  52211. if (events && events.length > 0) {
  52212. events.forEach(function (e) {
  52213. _this._events.push(e._clone());
  52214. });
  52215. }
  52216. }
  52217. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  52218. /**
  52219. * Gets the current frame of the runtime animation
  52220. */
  52221. get: function () {
  52222. return this._currentFrame;
  52223. },
  52224. enumerable: true,
  52225. configurable: true
  52226. });
  52227. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  52228. /**
  52229. * Gets the weight of the runtime animation
  52230. */
  52231. get: function () {
  52232. return this._weight;
  52233. },
  52234. enumerable: true,
  52235. configurable: true
  52236. });
  52237. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  52238. /**
  52239. * Gets the current value of the runtime animation
  52240. */
  52241. get: function () {
  52242. return this._currentValue;
  52243. },
  52244. enumerable: true,
  52245. configurable: true
  52246. });
  52247. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  52248. /**
  52249. * Gets the target path of the runtime animation
  52250. */
  52251. get: function () {
  52252. return this._targetPath;
  52253. },
  52254. enumerable: true,
  52255. configurable: true
  52256. });
  52257. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  52258. /**
  52259. * Gets the actual target of the runtime animation
  52260. */
  52261. get: function () {
  52262. return this._activeTarget;
  52263. },
  52264. enumerable: true,
  52265. configurable: true
  52266. });
  52267. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  52268. /**
  52269. * Gets the animation from the runtime animation
  52270. */
  52271. get: function () {
  52272. return this._animation;
  52273. },
  52274. enumerable: true,
  52275. configurable: true
  52276. });
  52277. /**
  52278. * Resets the runtime animation to the beginning
  52279. * @param restoreOriginal defines whether to restore the target property to the original value
  52280. */
  52281. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  52282. if (restoreOriginal === void 0) { restoreOriginal = false; }
  52283. if (restoreOriginal) {
  52284. if (this._target instanceof Array) {
  52285. var index = 0;
  52286. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52287. var target = _a[_i];
  52288. if (this._originalValue[index] !== undefined) {
  52289. this._setValue(target, this._originalValue[index], -1);
  52290. }
  52291. index++;
  52292. }
  52293. }
  52294. else {
  52295. if (this._originalValue[0] !== undefined) {
  52296. this._setValue(this._target, this._originalValue[0], -1);
  52297. }
  52298. }
  52299. }
  52300. this._offsetsCache = {};
  52301. this._highLimitsCache = {};
  52302. this._currentFrame = 0;
  52303. this._blendingFactor = 0;
  52304. this._originalValue = new Array();
  52305. // Events
  52306. for (var index = 0; index < this._events.length; index++) {
  52307. this._events[index].isDone = false;
  52308. }
  52309. };
  52310. /**
  52311. * Specifies if the runtime animation is stopped
  52312. * @returns Boolean specifying if the runtime animation is stopped
  52313. */
  52314. RuntimeAnimation.prototype.isStopped = function () {
  52315. return this._stopped;
  52316. };
  52317. /**
  52318. * Disposes of the runtime animation
  52319. */
  52320. RuntimeAnimation.prototype.dispose = function () {
  52321. var index = this._animation.runtimeAnimations.indexOf(this);
  52322. if (index > -1) {
  52323. this._animation.runtimeAnimations.splice(index, 1);
  52324. }
  52325. };
  52326. /**
  52327. * Interpolates the animation from the current frame
  52328. * @param currentFrame The frame to interpolate the animation to
  52329. * @param repeatCount The number of times that the animation should loop
  52330. * @param loopMode The type of looping mode to use
  52331. * @param offsetValue Animation offset value
  52332. * @param highLimitValue The high limit value
  52333. * @returns The interpolated value
  52334. */
  52335. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  52336. this._currentFrame = currentFrame;
  52337. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  52338. this._workValue = BABYLON.Matrix.Zero();
  52339. }
  52340. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  52341. };
  52342. /**
  52343. * Apply the interpolated value to the target
  52344. * @param currentValue defines the value computed by the animation
  52345. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  52346. */
  52347. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  52348. if (weight === void 0) { weight = 1.0; }
  52349. if (this._target instanceof Array) {
  52350. var index = 0;
  52351. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52352. var target = _a[_i];
  52353. this._setValue(target, currentValue, weight, index);
  52354. index++;
  52355. }
  52356. }
  52357. else {
  52358. this._setValue(this._target, currentValue, weight);
  52359. }
  52360. };
  52361. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  52362. if (targetIndex === void 0) { targetIndex = 0; }
  52363. // Set value
  52364. var path;
  52365. var destination;
  52366. var targetPropertyPath = this._animation.targetPropertyPath;
  52367. if (targetPropertyPath.length > 1) {
  52368. var property = target[targetPropertyPath[0]];
  52369. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  52370. property = property[targetPropertyPath[index]];
  52371. }
  52372. path = targetPropertyPath[targetPropertyPath.length - 1];
  52373. destination = property;
  52374. }
  52375. else {
  52376. path = targetPropertyPath[0];
  52377. destination = target;
  52378. }
  52379. this._targetPath = path;
  52380. this._activeTarget = destination;
  52381. this._weight = weight;
  52382. if (this._originalValue[targetIndex] === undefined) {
  52383. var originalValue = void 0;
  52384. if (destination.getRestPose && path === "_matrix") { // For bones
  52385. originalValue = destination.getRestPose();
  52386. }
  52387. else {
  52388. originalValue = destination[path];
  52389. }
  52390. if (originalValue && originalValue.clone) {
  52391. this._originalValue[targetIndex] = originalValue.clone();
  52392. }
  52393. else {
  52394. this._originalValue[targetIndex] = originalValue;
  52395. }
  52396. }
  52397. // Blending
  52398. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52399. if (enableBlending && this._blendingFactor <= 1.0) {
  52400. if (!this._originalBlendValue) {
  52401. var originalValue = destination[path];
  52402. if (originalValue.clone) {
  52403. this._originalBlendValue = originalValue.clone();
  52404. }
  52405. else {
  52406. this._originalBlendValue = originalValue;
  52407. }
  52408. }
  52409. if (this._originalBlendValue.m) { // Matrix
  52410. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52411. if (this._currentValue) {
  52412. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52413. }
  52414. else {
  52415. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52416. }
  52417. }
  52418. else {
  52419. if (this._currentValue) {
  52420. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52421. }
  52422. else {
  52423. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52424. }
  52425. }
  52426. }
  52427. else {
  52428. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52429. }
  52430. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52431. this._blendingFactor += blendingSpeed;
  52432. }
  52433. else {
  52434. this._currentValue = currentValue;
  52435. }
  52436. if (weight !== -1.0) {
  52437. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52438. }
  52439. else {
  52440. destination[path] = this._currentValue;
  52441. }
  52442. if (target.markAsDirty) {
  52443. target.markAsDirty(this._animation.targetProperty);
  52444. }
  52445. };
  52446. /**
  52447. * Gets the loop pmode of the runtime animation
  52448. * @returns Loop Mode
  52449. */
  52450. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52451. if (this._target && this._target.animationPropertiesOverride) {
  52452. return this._target.animationPropertiesOverride.loopMode;
  52453. }
  52454. return this._animation.loopMode;
  52455. };
  52456. /**
  52457. * Move the current animation to a given frame
  52458. * @param frame defines the frame to move to
  52459. */
  52460. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52461. var keys = this._animation.getKeys();
  52462. if (frame < keys[0].frame) {
  52463. frame = keys[0].frame;
  52464. }
  52465. else if (frame > keys[keys.length - 1].frame) {
  52466. frame = keys[keys.length - 1].frame;
  52467. }
  52468. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52469. this.setValue(currentValue, -1);
  52470. };
  52471. /**
  52472. * @hidden Internal use only
  52473. */
  52474. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52475. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52476. this._ratioOffset = this._previousRatio - newRatio;
  52477. };
  52478. /**
  52479. * Execute the current animation
  52480. * @param delay defines the delay to add to the current frame
  52481. * @param from defines the lower bound of the animation range
  52482. * @param to defines the upper bound of the animation range
  52483. * @param loop defines if the current animation must loop
  52484. * @param speedRatio defines the current speed ratio
  52485. * @param weight defines the weight of the animation (default is -1 so no weight)
  52486. * @returns a boolean indicating if the animation is running
  52487. */
  52488. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52489. if (weight === void 0) { weight = -1.0; }
  52490. var targetPropertyPath = this._animation.targetPropertyPath;
  52491. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52492. this._stopped = true;
  52493. return false;
  52494. }
  52495. var returnValue = true;
  52496. var keys = this._animation.getKeys();
  52497. // Adding a start key at frame 0 if missing
  52498. if (keys[0].frame !== 0) {
  52499. var newKey = { frame: 0, value: keys[0].value };
  52500. keys.splice(0, 0, newKey);
  52501. }
  52502. // Adding a duplicate key when there is only one key at frame zero
  52503. else if (keys.length === 1) {
  52504. var newKey = { frame: 0.001, value: keys[0].value };
  52505. keys.push(newKey);
  52506. }
  52507. // Check limits
  52508. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52509. from = keys[0].frame;
  52510. }
  52511. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52512. to = keys[keys.length - 1].frame;
  52513. }
  52514. //to and from cannot be the same key
  52515. if (from === to) {
  52516. if (from > keys[0].frame) {
  52517. from--;
  52518. }
  52519. else if (to < keys[keys.length - 1].frame) {
  52520. to++;
  52521. }
  52522. }
  52523. // Compute ratio
  52524. var range = to - from;
  52525. var offsetValue;
  52526. // ratio represents the frame delta between from and to
  52527. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52528. var highLimitValue = 0;
  52529. this._previousDelay = delay;
  52530. this._previousRatio = ratio;
  52531. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  52532. returnValue = false;
  52533. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52534. }
  52535. else {
  52536. // Get max value if required
  52537. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52538. var keyOffset = to.toString() + from.toString();
  52539. if (!this._offsetsCache[keyOffset]) {
  52540. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52541. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52542. switch (this._animation.dataType) {
  52543. // Float
  52544. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52545. this._offsetsCache[keyOffset] = toValue - fromValue;
  52546. break;
  52547. // Quaternion
  52548. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52549. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52550. break;
  52551. // Vector3
  52552. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52553. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52554. // Vector2
  52555. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52556. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52557. // Size
  52558. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52559. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52560. // Color3
  52561. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52562. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52563. default:
  52564. break;
  52565. }
  52566. this._highLimitsCache[keyOffset] = toValue;
  52567. }
  52568. highLimitValue = this._highLimitsCache[keyOffset];
  52569. offsetValue = this._offsetsCache[keyOffset];
  52570. }
  52571. }
  52572. if (offsetValue === undefined) {
  52573. switch (this._animation.dataType) {
  52574. // Float
  52575. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52576. offsetValue = 0;
  52577. break;
  52578. // Quaternion
  52579. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52580. offsetValue = _staticOffsetValueQuaternion;
  52581. break;
  52582. // Vector3
  52583. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52584. offsetValue = _staticOffsetValueVector3;
  52585. break;
  52586. // Vector2
  52587. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52588. offsetValue = _staticOffsetValueVector2;
  52589. break;
  52590. // Size
  52591. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52592. offsetValue = _staticOffsetValueSize;
  52593. break;
  52594. // Color3
  52595. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52596. offsetValue = _staticOffsetValueColor3;
  52597. }
  52598. }
  52599. // Compute value
  52600. var repeatCount = (ratio / range) >> 0;
  52601. var currentFrame = returnValue ? from + ratio % range : to;
  52602. // Need to normalize?
  52603. if (this._host && this._host.syncRoot) {
  52604. var syncRoot = this._host.syncRoot;
  52605. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52606. currentFrame = from + (to - from) * hostNormalizedFrame;
  52607. }
  52608. // Reset events if looping
  52609. var events = this._events;
  52610. if (range > 0 && this.currentFrame > currentFrame ||
  52611. range < 0 && this.currentFrame < currentFrame) {
  52612. // Need to reset animation events
  52613. for (var index = 0; index < events.length; index++) {
  52614. if (!events[index].onlyOnce) {
  52615. // reset event, the animation is looping
  52616. events[index].isDone = false;
  52617. }
  52618. }
  52619. }
  52620. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52621. // Set value
  52622. this.setValue(currentValue, weight);
  52623. // Check events
  52624. for (var index = 0; index < events.length; index++) {
  52625. // Make sure current frame has passed event frame and that event frame is within the current range
  52626. // Also, handle both forward and reverse animations
  52627. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52628. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52629. var event = events[index];
  52630. if (!event.isDone) {
  52631. // If event should be done only once, remove it.
  52632. if (event.onlyOnce) {
  52633. events.splice(index, 1);
  52634. index--;
  52635. }
  52636. event.isDone = true;
  52637. event.action(currentFrame);
  52638. } // Don't do anything if the event has already be done.
  52639. }
  52640. }
  52641. if (!returnValue) {
  52642. this._stopped = true;
  52643. }
  52644. return returnValue;
  52645. };
  52646. return RuntimeAnimation;
  52647. }());
  52648. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52649. })(BABYLON || (BABYLON = {}));
  52650. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52651. var BABYLON;
  52652. (function (BABYLON) {
  52653. /**
  52654. * Class used to store an actual running animation
  52655. */
  52656. var Animatable = /** @class */ (function () {
  52657. /**
  52658. * Creates a new Animatable
  52659. * @param scene defines the hosting scene
  52660. * @param target defines the target object
  52661. * @param fromFrame defines the starting frame number (default is 0)
  52662. * @param toFrame defines the ending frame number (default is 100)
  52663. * @param loopAnimation defines if the animation must loop (default is false)
  52664. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  52665. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  52666. * @param animations defines a group of animation to add to the new Animatable
  52667. */
  52668. function Animatable(scene,
  52669. /** defines the target object */
  52670. target,
  52671. /** defines the starting frame number (default is 0) */
  52672. fromFrame,
  52673. /** defines the ending frame number (default is 100) */
  52674. toFrame,
  52675. /** defines if the animation must loop (default is false) */
  52676. loopAnimation, speedRatio,
  52677. /** defines a callback to call when animation ends if it is not looping */
  52678. onAnimationEnd, animations) {
  52679. if (fromFrame === void 0) { fromFrame = 0; }
  52680. if (toFrame === void 0) { toFrame = 100; }
  52681. if (loopAnimation === void 0) { loopAnimation = false; }
  52682. if (speedRatio === void 0) { speedRatio = 1.0; }
  52683. this.target = target;
  52684. this.fromFrame = fromFrame;
  52685. this.toFrame = toFrame;
  52686. this.loopAnimation = loopAnimation;
  52687. this.onAnimationEnd = onAnimationEnd;
  52688. this._localDelayOffset = null;
  52689. this._pausedDelay = null;
  52690. this._runtimeAnimations = new Array();
  52691. this._paused = false;
  52692. this._speedRatio = 1;
  52693. this._weight = -1.0;
  52694. /**
  52695. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  52696. * This will only apply for non looping animation (default is true)
  52697. */
  52698. this.disposeOnEnd = true;
  52699. /**
  52700. * Gets a boolean indicating if the animation has started
  52701. */
  52702. this.animationStarted = false;
  52703. /**
  52704. * Observer raised when the animation ends
  52705. */
  52706. this.onAnimationEndObservable = new BABYLON.Observable();
  52707. this._scene = scene;
  52708. if (animations) {
  52709. this.appendAnimations(target, animations);
  52710. }
  52711. this._speedRatio = speedRatio;
  52712. scene._activeAnimatables.push(this);
  52713. }
  52714. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52715. /**
  52716. * Gets the root Animatable used to synchronize and normalize animations
  52717. */
  52718. get: function () {
  52719. return this._syncRoot;
  52720. },
  52721. enumerable: true,
  52722. configurable: true
  52723. });
  52724. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52725. /**
  52726. * Gets the current frame of the first RuntimeAnimation
  52727. * Used to synchronize Animatables
  52728. */
  52729. get: function () {
  52730. if (this._runtimeAnimations.length === 0) {
  52731. return 0;
  52732. }
  52733. return this._runtimeAnimations[0].currentFrame;
  52734. },
  52735. enumerable: true,
  52736. configurable: true
  52737. });
  52738. Object.defineProperty(Animatable.prototype, "weight", {
  52739. /**
  52740. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52741. */
  52742. get: function () {
  52743. return this._weight;
  52744. },
  52745. set: function (value) {
  52746. if (value === -1) { // -1 is ok and means no weight
  52747. this._weight = -1;
  52748. return;
  52749. }
  52750. // Else weight must be in [0, 1] range
  52751. this._weight = Math.min(Math.max(value, 0), 1.0);
  52752. },
  52753. enumerable: true,
  52754. configurable: true
  52755. });
  52756. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52757. /**
  52758. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52759. */
  52760. get: function () {
  52761. return this._speedRatio;
  52762. },
  52763. set: function (value) {
  52764. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52765. var animation = this._runtimeAnimations[index];
  52766. animation._prepareForSpeedRatioChange(value);
  52767. }
  52768. this._speedRatio = value;
  52769. },
  52770. enumerable: true,
  52771. configurable: true
  52772. });
  52773. // Methods
  52774. /**
  52775. * Synchronize and normalize current Animatable with a source Animatable
  52776. * This is useful when using animation weights and when animations are not of the same length
  52777. * @param root defines the root Animatable to synchronize with
  52778. * @returns the current Animatable
  52779. */
  52780. Animatable.prototype.syncWith = function (root) {
  52781. this._syncRoot = root;
  52782. if (root) {
  52783. // Make sure this animatable will animate after the root
  52784. var index = this._scene._activeAnimatables.indexOf(this);
  52785. if (index > -1) {
  52786. this._scene._activeAnimatables.splice(index, 1);
  52787. this._scene._activeAnimatables.push(this);
  52788. }
  52789. }
  52790. return this;
  52791. };
  52792. /**
  52793. * Gets the list of runtime animations
  52794. * @returns an array of RuntimeAnimation
  52795. */
  52796. Animatable.prototype.getAnimations = function () {
  52797. return this._runtimeAnimations;
  52798. };
  52799. /**
  52800. * Adds more animations to the current animatable
  52801. * @param target defines the target of the animations
  52802. * @param animations defines the new animations to add
  52803. */
  52804. Animatable.prototype.appendAnimations = function (target, animations) {
  52805. for (var index = 0; index < animations.length; index++) {
  52806. var animation = animations[index];
  52807. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52808. }
  52809. };
  52810. /**
  52811. * Gets the source animation for a specific property
  52812. * @param property defines the propertyu to look for
  52813. * @returns null or the source animation for the given property
  52814. */
  52815. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52816. var runtimeAnimations = this._runtimeAnimations;
  52817. for (var index = 0; index < runtimeAnimations.length; index++) {
  52818. if (runtimeAnimations[index].animation.targetProperty === property) {
  52819. return runtimeAnimations[index].animation;
  52820. }
  52821. }
  52822. return null;
  52823. };
  52824. /**
  52825. * Gets the runtime animation for a specific property
  52826. * @param property defines the propertyu to look for
  52827. * @returns null or the runtime animation for the given property
  52828. */
  52829. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52830. var runtimeAnimations = this._runtimeAnimations;
  52831. for (var index = 0; index < runtimeAnimations.length; index++) {
  52832. if (runtimeAnimations[index].animation.targetProperty === property) {
  52833. return runtimeAnimations[index];
  52834. }
  52835. }
  52836. return null;
  52837. };
  52838. /**
  52839. * Resets the animatable to its original state
  52840. */
  52841. Animatable.prototype.reset = function () {
  52842. var runtimeAnimations = this._runtimeAnimations;
  52843. for (var index = 0; index < runtimeAnimations.length; index++) {
  52844. runtimeAnimations[index].reset(true);
  52845. }
  52846. this._localDelayOffset = null;
  52847. this._pausedDelay = null;
  52848. };
  52849. /**
  52850. * Allows the animatable to blend with current running animations
  52851. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  52852. * @param blendingSpeed defines the blending speed to use
  52853. */
  52854. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52855. var runtimeAnimations = this._runtimeAnimations;
  52856. for (var index = 0; index < runtimeAnimations.length; index++) {
  52857. runtimeAnimations[index].animation.enableBlending = true;
  52858. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52859. }
  52860. };
  52861. /**
  52862. * Disable animation blending
  52863. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  52864. */
  52865. Animatable.prototype.disableBlending = function () {
  52866. var runtimeAnimations = this._runtimeAnimations;
  52867. for (var index = 0; index < runtimeAnimations.length; index++) {
  52868. runtimeAnimations[index].animation.enableBlending = false;
  52869. }
  52870. };
  52871. /**
  52872. * Jump directly to a given frame
  52873. * @param frame defines the frame to jump to
  52874. */
  52875. Animatable.prototype.goToFrame = function (frame) {
  52876. var runtimeAnimations = this._runtimeAnimations;
  52877. if (runtimeAnimations[0]) {
  52878. var fps = runtimeAnimations[0].animation.framePerSecond;
  52879. var currentFrame = runtimeAnimations[0].currentFrame;
  52880. var adjustTime = frame - currentFrame;
  52881. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52882. if (this._localDelayOffset === null) {
  52883. this._localDelayOffset = 0;
  52884. }
  52885. this._localDelayOffset -= delay;
  52886. }
  52887. for (var index = 0; index < runtimeAnimations.length; index++) {
  52888. runtimeAnimations[index].goToFrame(frame);
  52889. }
  52890. };
  52891. /**
  52892. * Pause the animation
  52893. */
  52894. Animatable.prototype.pause = function () {
  52895. if (this._paused) {
  52896. return;
  52897. }
  52898. this._paused = true;
  52899. };
  52900. /**
  52901. * Restart the animation
  52902. */
  52903. Animatable.prototype.restart = function () {
  52904. this._paused = false;
  52905. };
  52906. Animatable.prototype._raiseOnAnimationEnd = function () {
  52907. if (this.onAnimationEnd) {
  52908. this.onAnimationEnd();
  52909. }
  52910. this.onAnimationEndObservable.notifyObservers(this);
  52911. };
  52912. /**
  52913. * Stop and delete the current animation
  52914. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  52915. * @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)
  52916. */
  52917. Animatable.prototype.stop = function (animationName, targetMask) {
  52918. if (animationName || targetMask) {
  52919. var idx = this._scene._activeAnimatables.indexOf(this);
  52920. if (idx > -1) {
  52921. var runtimeAnimations = this._runtimeAnimations;
  52922. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52923. var runtimeAnimation = runtimeAnimations[index];
  52924. if (animationName && runtimeAnimation.animation.name != animationName) {
  52925. continue;
  52926. }
  52927. if (targetMask && !targetMask(runtimeAnimation.target)) {
  52928. continue;
  52929. }
  52930. runtimeAnimation.dispose();
  52931. runtimeAnimations.splice(index, 1);
  52932. }
  52933. if (runtimeAnimations.length == 0) {
  52934. this._scene._activeAnimatables.splice(idx, 1);
  52935. this._raiseOnAnimationEnd();
  52936. }
  52937. }
  52938. }
  52939. else {
  52940. var index = this._scene._activeAnimatables.indexOf(this);
  52941. if (index > -1) {
  52942. this._scene._activeAnimatables.splice(index, 1);
  52943. var runtimeAnimations = this._runtimeAnimations;
  52944. for (var index = 0; index < runtimeAnimations.length; index++) {
  52945. runtimeAnimations[index].dispose();
  52946. }
  52947. this._raiseOnAnimationEnd();
  52948. }
  52949. }
  52950. };
  52951. /**
  52952. * Wait asynchronously for the animation to end
  52953. * @returns a promise which will be fullfilled when the animation ends
  52954. */
  52955. Animatable.prototype.waitAsync = function () {
  52956. var _this = this;
  52957. return new Promise(function (resolve, reject) {
  52958. _this.onAnimationEndObservable.add(function () {
  52959. resolve(_this);
  52960. }, undefined, undefined, _this, true);
  52961. });
  52962. };
  52963. /** @hidden */
  52964. Animatable.prototype._animate = function (delay) {
  52965. if (this._paused) {
  52966. this.animationStarted = false;
  52967. if (this._pausedDelay === null) {
  52968. this._pausedDelay = delay;
  52969. }
  52970. return true;
  52971. }
  52972. if (this._localDelayOffset === null) {
  52973. this._localDelayOffset = delay;
  52974. this._pausedDelay = null;
  52975. }
  52976. else if (this._pausedDelay !== null) {
  52977. this._localDelayOffset += delay - this._pausedDelay;
  52978. this._pausedDelay = null;
  52979. }
  52980. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52981. return true;
  52982. }
  52983. // Animating
  52984. var running = false;
  52985. var runtimeAnimations = this._runtimeAnimations;
  52986. var index;
  52987. for (index = 0; index < runtimeAnimations.length; index++) {
  52988. var animation = runtimeAnimations[index];
  52989. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52990. running = running || isRunning;
  52991. }
  52992. this.animationStarted = running;
  52993. if (!running) {
  52994. if (this.disposeOnEnd) {
  52995. // Remove from active animatables
  52996. index = this._scene._activeAnimatables.indexOf(this);
  52997. this._scene._activeAnimatables.splice(index, 1);
  52998. // Dispose all runtime animations
  52999. for (index = 0; index < runtimeAnimations.length; index++) {
  53000. runtimeAnimations[index].dispose();
  53001. }
  53002. }
  53003. this._raiseOnAnimationEnd();
  53004. if (this.disposeOnEnd) {
  53005. this.onAnimationEnd = null;
  53006. this.onAnimationEndObservable.clear();
  53007. }
  53008. }
  53009. return running;
  53010. };
  53011. return Animatable;
  53012. }());
  53013. BABYLON.Animatable = Animatable;
  53014. })(BABYLON || (BABYLON = {}));
  53015. //# sourceMappingURL=babylon.animatable.js.map
  53016. var BABYLON;
  53017. (function (BABYLON) {
  53018. /**
  53019. * Base class used for every default easing function.
  53020. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53021. */
  53022. var EasingFunction = /** @class */ (function () {
  53023. function EasingFunction() {
  53024. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  53025. }
  53026. /**
  53027. * Sets the easing mode of the current function.
  53028. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  53029. */
  53030. EasingFunction.prototype.setEasingMode = function (easingMode) {
  53031. var n = Math.min(Math.max(easingMode, 0), 2);
  53032. this._easingMode = n;
  53033. };
  53034. /**
  53035. * Gets the current easing mode.
  53036. * @returns the easing mode
  53037. */
  53038. EasingFunction.prototype.getEasingMode = function () {
  53039. return this._easingMode;
  53040. };
  53041. /**
  53042. * @hidden
  53043. */
  53044. EasingFunction.prototype.easeInCore = function (gradient) {
  53045. throw new Error('You must implement this method');
  53046. };
  53047. /**
  53048. * Given an input gradient between 0 and 1, this returns the corrseponding value
  53049. * of the easing function.
  53050. * @param gradient Defines the value between 0 and 1 we want the easing value for
  53051. * @returns the corresponding value on the curve defined by the easing function
  53052. */
  53053. EasingFunction.prototype.ease = function (gradient) {
  53054. switch (this._easingMode) {
  53055. case EasingFunction.EASINGMODE_EASEIN:
  53056. return this.easeInCore(gradient);
  53057. case EasingFunction.EASINGMODE_EASEOUT:
  53058. return (1 - this.easeInCore(1 - gradient));
  53059. }
  53060. if (gradient >= 0.5) {
  53061. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  53062. }
  53063. return (this.easeInCore(gradient * 2) * 0.5);
  53064. };
  53065. /**
  53066. * Interpolation follows the mathematical formula associated with the easing function.
  53067. */
  53068. EasingFunction.EASINGMODE_EASEIN = 0;
  53069. /**
  53070. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  53071. */
  53072. EasingFunction.EASINGMODE_EASEOUT = 1;
  53073. /**
  53074. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  53075. */
  53076. EasingFunction.EASINGMODE_EASEINOUT = 2;
  53077. return EasingFunction;
  53078. }());
  53079. BABYLON.EasingFunction = EasingFunction;
  53080. /**
  53081. * Easing function with a circle shape (see link below).
  53082. * @see https://easings.net/#easeInCirc
  53083. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53084. */
  53085. var CircleEase = /** @class */ (function (_super) {
  53086. __extends(CircleEase, _super);
  53087. function CircleEase() {
  53088. return _super !== null && _super.apply(this, arguments) || this;
  53089. }
  53090. /** @hidden */
  53091. CircleEase.prototype.easeInCore = function (gradient) {
  53092. gradient = Math.max(0, Math.min(1, gradient));
  53093. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  53094. };
  53095. return CircleEase;
  53096. }(EasingFunction));
  53097. BABYLON.CircleEase = CircleEase;
  53098. /**
  53099. * Easing function with a ease back shape (see link below).
  53100. * @see https://easings.net/#easeInBack
  53101. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53102. */
  53103. var BackEase = /** @class */ (function (_super) {
  53104. __extends(BackEase, _super);
  53105. /**
  53106. * Instantiates a back ease easing
  53107. * @see https://easings.net/#easeInBack
  53108. * @param amplitude Defines the amplitude of the function
  53109. */
  53110. function BackEase(
  53111. /** Defines the amplitude of the function */
  53112. amplitude) {
  53113. if (amplitude === void 0) { amplitude = 1; }
  53114. var _this = _super.call(this) || this;
  53115. _this.amplitude = amplitude;
  53116. return _this;
  53117. }
  53118. /** @hidden */
  53119. BackEase.prototype.easeInCore = function (gradient) {
  53120. var num = Math.max(0, this.amplitude);
  53121. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  53122. };
  53123. return BackEase;
  53124. }(EasingFunction));
  53125. BABYLON.BackEase = BackEase;
  53126. /**
  53127. * Easing function with a bouncing shape (see link below).
  53128. * @see https://easings.net/#easeInBounce
  53129. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53130. */
  53131. var BounceEase = /** @class */ (function (_super) {
  53132. __extends(BounceEase, _super);
  53133. /**
  53134. * Instantiates a bounce easing
  53135. * @see https://easings.net/#easeInBounce
  53136. * @param bounces Defines the number of bounces
  53137. * @param bounciness Defines the amplitude of the bounce
  53138. */
  53139. function BounceEase(
  53140. /** Defines the number of bounces */
  53141. bounces,
  53142. /** Defines the amplitude of the bounce */
  53143. bounciness) {
  53144. if (bounces === void 0) { bounces = 3; }
  53145. if (bounciness === void 0) { bounciness = 2; }
  53146. var _this = _super.call(this) || this;
  53147. _this.bounces = bounces;
  53148. _this.bounciness = bounciness;
  53149. return _this;
  53150. }
  53151. /** @hidden */
  53152. BounceEase.prototype.easeInCore = function (gradient) {
  53153. var y = Math.max(0.0, this.bounces);
  53154. var bounciness = this.bounciness;
  53155. if (bounciness <= 1.0) {
  53156. bounciness = 1.001;
  53157. }
  53158. var num9 = Math.pow(bounciness, y);
  53159. var num5 = 1.0 - bounciness;
  53160. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  53161. var num15 = gradient * num4;
  53162. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  53163. var num3 = Math.floor(num65);
  53164. var num13 = num3 + 1.0;
  53165. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  53166. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  53167. var num7 = (num8 + num12) * 0.5;
  53168. var num6 = gradient - num7;
  53169. var num2 = num7 - num8;
  53170. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  53171. };
  53172. return BounceEase;
  53173. }(EasingFunction));
  53174. BABYLON.BounceEase = BounceEase;
  53175. /**
  53176. * Easing function with a power of 3 shape (see link below).
  53177. * @see https://easings.net/#easeInCubic
  53178. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53179. */
  53180. var CubicEase = /** @class */ (function (_super) {
  53181. __extends(CubicEase, _super);
  53182. function CubicEase() {
  53183. return _super !== null && _super.apply(this, arguments) || this;
  53184. }
  53185. /** @hidden */
  53186. CubicEase.prototype.easeInCore = function (gradient) {
  53187. return (gradient * gradient * gradient);
  53188. };
  53189. return CubicEase;
  53190. }(EasingFunction));
  53191. BABYLON.CubicEase = CubicEase;
  53192. /**
  53193. * Easing function with an elastic shape (see link below).
  53194. * @see https://easings.net/#easeInElastic
  53195. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53196. */
  53197. var ElasticEase = /** @class */ (function (_super) {
  53198. __extends(ElasticEase, _super);
  53199. /**
  53200. * Instantiates an elastic easing function
  53201. * @see https://easings.net/#easeInElastic
  53202. * @param oscillations Defines the number of oscillations
  53203. * @param springiness Defines the amplitude of the oscillations
  53204. */
  53205. function ElasticEase(
  53206. /** Defines the number of oscillations*/
  53207. oscillations,
  53208. /** Defines the amplitude of the oscillations*/
  53209. springiness) {
  53210. if (oscillations === void 0) { oscillations = 3; }
  53211. if (springiness === void 0) { springiness = 3; }
  53212. var _this = _super.call(this) || this;
  53213. _this.oscillations = oscillations;
  53214. _this.springiness = springiness;
  53215. return _this;
  53216. }
  53217. /** @hidden */
  53218. ElasticEase.prototype.easeInCore = function (gradient) {
  53219. var num2;
  53220. var num3 = Math.max(0.0, this.oscillations);
  53221. var num = Math.max(0.0, this.springiness);
  53222. if (num == 0) {
  53223. num2 = gradient;
  53224. }
  53225. else {
  53226. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  53227. }
  53228. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  53229. };
  53230. return ElasticEase;
  53231. }(EasingFunction));
  53232. BABYLON.ElasticEase = ElasticEase;
  53233. /**
  53234. * Easing function with an exponential shape (see link below).
  53235. * @see https://easings.net/#easeInExpo
  53236. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53237. */
  53238. var ExponentialEase = /** @class */ (function (_super) {
  53239. __extends(ExponentialEase, _super);
  53240. /**
  53241. * Instantiates an exponential easing function
  53242. * @see https://easings.net/#easeInExpo
  53243. * @param exponent Defines the exponent of the function
  53244. */
  53245. function ExponentialEase(
  53246. /** Defines the exponent of the function */
  53247. exponent) {
  53248. if (exponent === void 0) { exponent = 2; }
  53249. var _this = _super.call(this) || this;
  53250. _this.exponent = exponent;
  53251. return _this;
  53252. }
  53253. /** @hidden */
  53254. ExponentialEase.prototype.easeInCore = function (gradient) {
  53255. if (this.exponent <= 0) {
  53256. return gradient;
  53257. }
  53258. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  53259. };
  53260. return ExponentialEase;
  53261. }(EasingFunction));
  53262. BABYLON.ExponentialEase = ExponentialEase;
  53263. /**
  53264. * Easing function with a power shape (see link below).
  53265. * @see https://easings.net/#easeInQuad
  53266. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53267. */
  53268. var PowerEase = /** @class */ (function (_super) {
  53269. __extends(PowerEase, _super);
  53270. /**
  53271. * Instantiates an power base easing function
  53272. * @see https://easings.net/#easeInQuad
  53273. * @param power Defines the power of the function
  53274. */
  53275. function PowerEase(
  53276. /** Defines the power of the function */
  53277. power) {
  53278. if (power === void 0) { power = 2; }
  53279. var _this = _super.call(this) || this;
  53280. _this.power = power;
  53281. return _this;
  53282. }
  53283. /** @hidden */
  53284. PowerEase.prototype.easeInCore = function (gradient) {
  53285. var y = Math.max(0.0, this.power);
  53286. return Math.pow(gradient, y);
  53287. };
  53288. return PowerEase;
  53289. }(EasingFunction));
  53290. BABYLON.PowerEase = PowerEase;
  53291. /**
  53292. * Easing function with a power of 2 shape (see link below).
  53293. * @see https://easings.net/#easeInQuad
  53294. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53295. */
  53296. var QuadraticEase = /** @class */ (function (_super) {
  53297. __extends(QuadraticEase, _super);
  53298. function QuadraticEase() {
  53299. return _super !== null && _super.apply(this, arguments) || this;
  53300. }
  53301. /** @hidden */
  53302. QuadraticEase.prototype.easeInCore = function (gradient) {
  53303. return (gradient * gradient);
  53304. };
  53305. return QuadraticEase;
  53306. }(EasingFunction));
  53307. BABYLON.QuadraticEase = QuadraticEase;
  53308. /**
  53309. * Easing function with a power of 4 shape (see link below).
  53310. * @see https://easings.net/#easeInQuart
  53311. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53312. */
  53313. var QuarticEase = /** @class */ (function (_super) {
  53314. __extends(QuarticEase, _super);
  53315. function QuarticEase() {
  53316. return _super !== null && _super.apply(this, arguments) || this;
  53317. }
  53318. /** @hidden */
  53319. QuarticEase.prototype.easeInCore = function (gradient) {
  53320. return (gradient * gradient * gradient * gradient);
  53321. };
  53322. return QuarticEase;
  53323. }(EasingFunction));
  53324. BABYLON.QuarticEase = QuarticEase;
  53325. /**
  53326. * Easing function with a power of 5 shape (see link below).
  53327. * @see https://easings.net/#easeInQuint
  53328. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53329. */
  53330. var QuinticEase = /** @class */ (function (_super) {
  53331. __extends(QuinticEase, _super);
  53332. function QuinticEase() {
  53333. return _super !== null && _super.apply(this, arguments) || this;
  53334. }
  53335. /** @hidden */
  53336. QuinticEase.prototype.easeInCore = function (gradient) {
  53337. return (gradient * gradient * gradient * gradient * gradient);
  53338. };
  53339. return QuinticEase;
  53340. }(EasingFunction));
  53341. BABYLON.QuinticEase = QuinticEase;
  53342. /**
  53343. * Easing function with a sin shape (see link below).
  53344. * @see https://easings.net/#easeInSine
  53345. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53346. */
  53347. var SineEase = /** @class */ (function (_super) {
  53348. __extends(SineEase, _super);
  53349. function SineEase() {
  53350. return _super !== null && _super.apply(this, arguments) || this;
  53351. }
  53352. /** @hidden */
  53353. SineEase.prototype.easeInCore = function (gradient) {
  53354. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  53355. };
  53356. return SineEase;
  53357. }(EasingFunction));
  53358. BABYLON.SineEase = SineEase;
  53359. /**
  53360. * Easing function with a bezier shape (see link below).
  53361. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  53362. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53363. */
  53364. var BezierCurveEase = /** @class */ (function (_super) {
  53365. __extends(BezierCurveEase, _super);
  53366. /**
  53367. * Instantiates a bezier function
  53368. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  53369. * @param x1 Defines the x component of the start tangent in the bezier curve
  53370. * @param y1 Defines the y component of the start tangent in the bezier curve
  53371. * @param x2 Defines the x component of the end tangent in the bezier curve
  53372. * @param y2 Defines the y component of the end tangent in the bezier curve
  53373. */
  53374. function BezierCurveEase(
  53375. /** Defines the x component of the start tangent in the bezier curve */
  53376. x1,
  53377. /** Defines the y component of the start tangent in the bezier curve */
  53378. y1,
  53379. /** Defines the x component of the end tangent in the bezier curve */
  53380. x2,
  53381. /** Defines the y component of the end tangent in the bezier curve */
  53382. y2) {
  53383. if (x1 === void 0) { x1 = 0; }
  53384. if (y1 === void 0) { y1 = 0; }
  53385. if (x2 === void 0) { x2 = 1; }
  53386. if (y2 === void 0) { y2 = 1; }
  53387. var _this = _super.call(this) || this;
  53388. _this.x1 = x1;
  53389. _this.y1 = y1;
  53390. _this.x2 = x2;
  53391. _this.y2 = y2;
  53392. return _this;
  53393. }
  53394. /** @hidden */
  53395. BezierCurveEase.prototype.easeInCore = function (gradient) {
  53396. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  53397. };
  53398. return BezierCurveEase;
  53399. }(EasingFunction));
  53400. BABYLON.BezierCurveEase = BezierCurveEase;
  53401. })(BABYLON || (BABYLON = {}));
  53402. //# sourceMappingURL=babylon.easing.js.map
  53403. var BABYLON;
  53404. (function (BABYLON) {
  53405. /**
  53406. * A Condition applied to an Action
  53407. */
  53408. var Condition = /** @class */ (function () {
  53409. /**
  53410. * Creates a new Condition
  53411. * @param actionManager the manager of the action the condition is applied to
  53412. */
  53413. function Condition(actionManager) {
  53414. this._actionManager = actionManager;
  53415. }
  53416. /**
  53417. * Check if the current condition is valid
  53418. * @returns a boolean
  53419. */
  53420. Condition.prototype.isValid = function () {
  53421. return true;
  53422. };
  53423. /**
  53424. * Internal only
  53425. * @hidden
  53426. */
  53427. Condition.prototype._getProperty = function (propertyPath) {
  53428. return this._actionManager._getProperty(propertyPath);
  53429. };
  53430. /**
  53431. * Internal only
  53432. * @hidden
  53433. */
  53434. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  53435. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53436. };
  53437. /**
  53438. * Serialize placeholder for child classes
  53439. * @returns the serialized object
  53440. */
  53441. Condition.prototype.serialize = function () {
  53442. };
  53443. /**
  53444. * Internal only
  53445. * @hidden
  53446. */
  53447. Condition.prototype._serialize = function (serializedCondition) {
  53448. return {
  53449. type: 2,
  53450. children: [],
  53451. name: serializedCondition.name,
  53452. properties: serializedCondition.properties
  53453. };
  53454. };
  53455. return Condition;
  53456. }());
  53457. BABYLON.Condition = Condition;
  53458. /**
  53459. * Defines specific conditional operators as extensions of Condition
  53460. */
  53461. var ValueCondition = /** @class */ (function (_super) {
  53462. __extends(ValueCondition, _super);
  53463. /**
  53464. * Creates a new ValueCondition
  53465. * @param actionManager manager for the action the condition applies to
  53466. * @param target for the action
  53467. * @param propertyPath path to specify the property of the target the conditional operator uses
  53468. * @param value the value compared by the conditional operator against the current value of the property
  53469. * @param operator the conditional operator, default ValueCondition.IsEqual
  53470. */
  53471. function ValueCondition(actionManager, target,
  53472. /** path to specify the property of the target the conditional operator uses */
  53473. propertyPath,
  53474. /** the value compared by the conditional operator against the current value of the property */
  53475. value,
  53476. /** the conditional operator, default ValueCondition.IsEqual */
  53477. operator) {
  53478. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  53479. var _this = _super.call(this, actionManager) || this;
  53480. _this.propertyPath = propertyPath;
  53481. _this.value = value;
  53482. _this.operator = operator;
  53483. _this._target = target;
  53484. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  53485. _this._property = _this._getProperty(_this.propertyPath);
  53486. return _this;
  53487. }
  53488. Object.defineProperty(ValueCondition, "IsEqual", {
  53489. /**
  53490. * returns the number for IsEqual
  53491. */
  53492. get: function () {
  53493. return ValueCondition._IsEqual;
  53494. },
  53495. enumerable: true,
  53496. configurable: true
  53497. });
  53498. Object.defineProperty(ValueCondition, "IsDifferent", {
  53499. /**
  53500. * Returns the number for IsDifferent
  53501. */
  53502. get: function () {
  53503. return ValueCondition._IsDifferent;
  53504. },
  53505. enumerable: true,
  53506. configurable: true
  53507. });
  53508. Object.defineProperty(ValueCondition, "IsGreater", {
  53509. /**
  53510. * Returns the number for IsGreater
  53511. */
  53512. get: function () {
  53513. return ValueCondition._IsGreater;
  53514. },
  53515. enumerable: true,
  53516. configurable: true
  53517. });
  53518. Object.defineProperty(ValueCondition, "IsLesser", {
  53519. /**
  53520. * Returns the number for IsLesser
  53521. */
  53522. get: function () {
  53523. return ValueCondition._IsLesser;
  53524. },
  53525. enumerable: true,
  53526. configurable: true
  53527. });
  53528. /**
  53529. * Compares the given value with the property value for the specified conditional operator
  53530. * @returns the result of the comparison
  53531. */
  53532. ValueCondition.prototype.isValid = function () {
  53533. switch (this.operator) {
  53534. case ValueCondition.IsGreater:
  53535. return this._effectiveTarget[this._property] > this.value;
  53536. case ValueCondition.IsLesser:
  53537. return this._effectiveTarget[this._property] < this.value;
  53538. case ValueCondition.IsEqual:
  53539. case ValueCondition.IsDifferent:
  53540. var check;
  53541. if (this.value.equals) {
  53542. check = this.value.equals(this._effectiveTarget[this._property]);
  53543. }
  53544. else {
  53545. check = this.value === this._effectiveTarget[this._property];
  53546. }
  53547. return this.operator === ValueCondition.IsEqual ? check : !check;
  53548. }
  53549. return false;
  53550. };
  53551. /**
  53552. * Serialize the ValueCondition into a JSON compatible object
  53553. * @returns serialization object
  53554. */
  53555. ValueCondition.prototype.serialize = function () {
  53556. return this._serialize({
  53557. name: "ValueCondition",
  53558. properties: [
  53559. BABYLON.Action._GetTargetProperty(this._target),
  53560. { name: "propertyPath", value: this.propertyPath },
  53561. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53562. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53563. ]
  53564. });
  53565. };
  53566. /**
  53567. * Gets the name of the conditional operator for the ValueCondition
  53568. * @param operator the conditional operator
  53569. * @returns the name
  53570. */
  53571. ValueCondition.GetOperatorName = function (operator) {
  53572. switch (operator) {
  53573. case ValueCondition._IsEqual: return "IsEqual";
  53574. case ValueCondition._IsDifferent: return "IsDifferent";
  53575. case ValueCondition._IsGreater: return "IsGreater";
  53576. case ValueCondition._IsLesser: return "IsLesser";
  53577. default: return "";
  53578. }
  53579. };
  53580. /**
  53581. * Internal only
  53582. * @hidden
  53583. */
  53584. ValueCondition._IsEqual = 0;
  53585. /**
  53586. * Internal only
  53587. * @hidden
  53588. */
  53589. ValueCondition._IsDifferent = 1;
  53590. /**
  53591. * Internal only
  53592. * @hidden
  53593. */
  53594. ValueCondition._IsGreater = 2;
  53595. /**
  53596. * Internal only
  53597. * @hidden
  53598. */
  53599. ValueCondition._IsLesser = 3;
  53600. return ValueCondition;
  53601. }(Condition));
  53602. BABYLON.ValueCondition = ValueCondition;
  53603. /**
  53604. * Defines a predicate condition as an extension of Condition
  53605. */
  53606. var PredicateCondition = /** @class */ (function (_super) {
  53607. __extends(PredicateCondition, _super);
  53608. /**
  53609. * Creates a new PredicateCondition
  53610. * @param actionManager manager for the action the condition applies to
  53611. * @param predicate defines the predicate function used to validate the condition
  53612. */
  53613. function PredicateCondition(actionManager,
  53614. /** defines the predicate function used to validate the condition */
  53615. predicate) {
  53616. var _this = _super.call(this, actionManager) || this;
  53617. _this.predicate = predicate;
  53618. return _this;
  53619. }
  53620. /**
  53621. * @returns the validity of the predicate condition
  53622. */
  53623. PredicateCondition.prototype.isValid = function () {
  53624. return this.predicate();
  53625. };
  53626. return PredicateCondition;
  53627. }(Condition));
  53628. BABYLON.PredicateCondition = PredicateCondition;
  53629. /**
  53630. * Defines a state condition as an extension of Condition
  53631. */
  53632. var StateCondition = /** @class */ (function (_super) {
  53633. __extends(StateCondition, _super);
  53634. /**
  53635. * Creates a new StateCondition
  53636. * @param actionManager manager for the action the condition applies to
  53637. * @param target of the condition
  53638. * @param value to compare with target state
  53639. */
  53640. function StateCondition(actionManager, target, value) {
  53641. var _this = _super.call(this, actionManager) || this;
  53642. _this.value = value;
  53643. _this._target = target;
  53644. return _this;
  53645. }
  53646. /**
  53647. * @returns the validity of the state
  53648. */
  53649. StateCondition.prototype.isValid = function () {
  53650. return this._target.state === this.value;
  53651. };
  53652. /**
  53653. * Serialize the StateCondition into a JSON compatible object
  53654. * @returns serialization object
  53655. */
  53656. StateCondition.prototype.serialize = function () {
  53657. return this._serialize({
  53658. name: "StateCondition",
  53659. properties: [
  53660. BABYLON.Action._GetTargetProperty(this._target),
  53661. { name: "value", value: this.value }
  53662. ]
  53663. });
  53664. };
  53665. return StateCondition;
  53666. }(Condition));
  53667. BABYLON.StateCondition = StateCondition;
  53668. })(BABYLON || (BABYLON = {}));
  53669. //# sourceMappingURL=babylon.condition.js.map
  53670. var BABYLON;
  53671. (function (BABYLON) {
  53672. /**
  53673. * The action to be carried out following a trigger
  53674. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53675. */
  53676. var Action = /** @class */ (function () {
  53677. /**
  53678. * Creates a new Action
  53679. * @param triggerOptions the trigger, with or without parameters, for the action
  53680. * @param condition an optional determinant of action
  53681. */
  53682. function Action(
  53683. /** the trigger, with or without parameters, for the action */
  53684. triggerOptions, condition) {
  53685. this.triggerOptions = triggerOptions;
  53686. /**
  53687. * An event triggered prior to action being executed.
  53688. */
  53689. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53690. if (triggerOptions.parameter) {
  53691. this.trigger = triggerOptions.trigger;
  53692. this._triggerParameter = triggerOptions.parameter;
  53693. }
  53694. else if (triggerOptions.trigger) {
  53695. this.trigger = triggerOptions.trigger;
  53696. }
  53697. else {
  53698. this.trigger = triggerOptions;
  53699. }
  53700. this._nextActiveAction = this;
  53701. this._condition = condition;
  53702. }
  53703. /**
  53704. * Internal only
  53705. * @hidden
  53706. */
  53707. Action.prototype._prepare = function () {
  53708. };
  53709. /**
  53710. * Gets the trigger parameters
  53711. * @returns the trigger parameters
  53712. */
  53713. Action.prototype.getTriggerParameter = function () {
  53714. return this._triggerParameter;
  53715. };
  53716. /**
  53717. * Internal only - executes current action event
  53718. * @hidden
  53719. */
  53720. Action.prototype._executeCurrent = function (evt) {
  53721. if (this._nextActiveAction._condition) {
  53722. var condition = this._nextActiveAction._condition;
  53723. var currentRenderId = this._actionManager.getScene().getRenderId();
  53724. // We cache the current evaluation for the current frame
  53725. if (condition._evaluationId === currentRenderId) {
  53726. if (!condition._currentResult) {
  53727. return;
  53728. }
  53729. }
  53730. else {
  53731. condition._evaluationId = currentRenderId;
  53732. if (!condition.isValid()) {
  53733. condition._currentResult = false;
  53734. return;
  53735. }
  53736. condition._currentResult = true;
  53737. }
  53738. }
  53739. this.onBeforeExecuteObservable.notifyObservers(this);
  53740. this._nextActiveAction.execute(evt);
  53741. this.skipToNextActiveAction();
  53742. };
  53743. /**
  53744. * Execute placeholder for child classes
  53745. * @param evt optional action event
  53746. */
  53747. Action.prototype.execute = function (evt) {
  53748. };
  53749. /**
  53750. * Skips to next active action
  53751. */
  53752. Action.prototype.skipToNextActiveAction = function () {
  53753. if (this._nextActiveAction._child) {
  53754. if (!this._nextActiveAction._child._actionManager) {
  53755. this._nextActiveAction._child._actionManager = this._actionManager;
  53756. }
  53757. this._nextActiveAction = this._nextActiveAction._child;
  53758. }
  53759. else {
  53760. this._nextActiveAction = this;
  53761. }
  53762. };
  53763. /**
  53764. * Adds action to chain of actions, may be a DoNothingAction
  53765. * @param action defines the next action to execute
  53766. * @returns The action passed in
  53767. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53768. */
  53769. Action.prototype.then = function (action) {
  53770. this._child = action;
  53771. action._actionManager = this._actionManager;
  53772. action._prepare();
  53773. return action;
  53774. };
  53775. /**
  53776. * Internal only
  53777. * @hidden
  53778. */
  53779. Action.prototype._getProperty = function (propertyPath) {
  53780. return this._actionManager._getProperty(propertyPath);
  53781. };
  53782. /**
  53783. * Internal only
  53784. * @hidden
  53785. */
  53786. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53787. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53788. };
  53789. /**
  53790. * Serialize placeholder for child classes
  53791. * @param parent of child
  53792. * @returns the serialized object
  53793. */
  53794. Action.prototype.serialize = function (parent) {
  53795. };
  53796. /**
  53797. * Internal only called by serialize
  53798. * @hidden
  53799. */
  53800. Action.prototype._serialize = function (serializedAction, parent) {
  53801. var serializationObject = {
  53802. type: 1,
  53803. children: [],
  53804. name: serializedAction.name,
  53805. properties: serializedAction.properties || []
  53806. };
  53807. // Serialize child
  53808. if (this._child) {
  53809. this._child.serialize(serializationObject);
  53810. }
  53811. // Check if "this" has a condition
  53812. if (this._condition) {
  53813. var serializedCondition = this._condition.serialize();
  53814. serializedCondition.children.push(serializationObject);
  53815. if (parent) {
  53816. parent.children.push(serializedCondition);
  53817. }
  53818. return serializedCondition;
  53819. }
  53820. if (parent) {
  53821. parent.children.push(serializationObject);
  53822. }
  53823. return serializationObject;
  53824. };
  53825. /**
  53826. * Internal only
  53827. * @hidden
  53828. */
  53829. Action._SerializeValueAsString = function (value) {
  53830. if (typeof value === "number") {
  53831. return value.toString();
  53832. }
  53833. if (typeof value === "boolean") {
  53834. return value ? "true" : "false";
  53835. }
  53836. if (value instanceof BABYLON.Vector2) {
  53837. return value.x + ", " + value.y;
  53838. }
  53839. if (value instanceof BABYLON.Vector3) {
  53840. return value.x + ", " + value.y + ", " + value.z;
  53841. }
  53842. if (value instanceof BABYLON.Color3) {
  53843. return value.r + ", " + value.g + ", " + value.b;
  53844. }
  53845. if (value instanceof BABYLON.Color4) {
  53846. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53847. }
  53848. return value; // string
  53849. };
  53850. /**
  53851. * Internal only
  53852. * @hidden
  53853. */
  53854. Action._GetTargetProperty = function (target) {
  53855. return {
  53856. name: "target",
  53857. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53858. : target instanceof BABYLON.Light ? "LightProperties"
  53859. : target instanceof BABYLON.Camera ? "CameraProperties"
  53860. : "SceneProperties",
  53861. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53862. };
  53863. };
  53864. return Action;
  53865. }());
  53866. BABYLON.Action = Action;
  53867. })(BABYLON || (BABYLON = {}));
  53868. //# sourceMappingURL=babylon.action.js.map
  53869. var BABYLON;
  53870. (function (BABYLON) {
  53871. /**
  53872. * ActionEvent is the event being sent when an action is triggered.
  53873. */
  53874. var ActionEvent = /** @class */ (function () {
  53875. /**
  53876. * Creates a new ActionEvent
  53877. * @param source The mesh or sprite that triggered the action
  53878. * @param pointerX The X mouse cursor position at the time of the event
  53879. * @param pointerY The Y mouse cursor position at the time of the event
  53880. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53881. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53882. * @param additionalData additional data for the event
  53883. */
  53884. function ActionEvent(
  53885. /** The mesh or sprite that triggered the action */
  53886. source,
  53887. /** The X mouse cursor position at the time of the event */
  53888. pointerX,
  53889. /** The Y mouse cursor position at the time of the event */
  53890. pointerY,
  53891. /** The mesh that is currently pointed at (can be null) */
  53892. meshUnderPointer,
  53893. /** the original (browser) event that triggered the ActionEvent */
  53894. sourceEvent,
  53895. /** additional data for the event */
  53896. additionalData) {
  53897. this.source = source;
  53898. this.pointerX = pointerX;
  53899. this.pointerY = pointerY;
  53900. this.meshUnderPointer = meshUnderPointer;
  53901. this.sourceEvent = sourceEvent;
  53902. this.additionalData = additionalData;
  53903. }
  53904. /**
  53905. * Helper function to auto-create an ActionEvent from a source mesh.
  53906. * @param source The source mesh that triggered the event
  53907. * @param evt The original (browser) event
  53908. * @param additionalData additional data for the event
  53909. * @returns the new ActionEvent
  53910. */
  53911. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53912. var scene = source.getScene();
  53913. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53914. };
  53915. /**
  53916. * Helper function to auto-create an ActionEvent from a source sprite
  53917. * @param source The source sprite that triggered the event
  53918. * @param scene Scene associated with the sprite
  53919. * @param evt The original (browser) event
  53920. * @param additionalData additional data for the event
  53921. * @returns the new ActionEvent
  53922. */
  53923. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53924. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53925. };
  53926. /**
  53927. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53928. * @param scene the scene where the event occurred
  53929. * @param evt The original (browser) event
  53930. * @returns the new ActionEvent
  53931. */
  53932. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53933. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53934. };
  53935. /**
  53936. * Helper function to auto-create an ActionEvent from a primitive
  53937. * @param prim defines the target primitive
  53938. * @param pointerPos defines the pointer position
  53939. * @param evt The original (browser) event
  53940. * @param additionalData additional data for the event
  53941. * @returns the new ActionEvent
  53942. */
  53943. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53944. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53945. };
  53946. return ActionEvent;
  53947. }());
  53948. BABYLON.ActionEvent = ActionEvent;
  53949. /**
  53950. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53951. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53952. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53953. */
  53954. var ActionManager = /** @class */ (function () {
  53955. /**
  53956. * Creates a new action manager
  53957. * @param scene defines the hosting scene
  53958. */
  53959. function ActionManager(scene) {
  53960. // Members
  53961. /** Gets the list of actions */
  53962. this.actions = new Array();
  53963. /** Gets the cursor to use when hovering items */
  53964. this.hoverCursor = '';
  53965. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53966. scene.actionManagers.push(this);
  53967. }
  53968. // Methods
  53969. /**
  53970. * Releases all associated resources
  53971. */
  53972. ActionManager.prototype.dispose = function () {
  53973. var index = this._scene.actionManagers.indexOf(this);
  53974. for (var i = 0; i < this.actions.length; i++) {
  53975. var action = this.actions[i];
  53976. ActionManager.Triggers[action.trigger]--;
  53977. if (ActionManager.Triggers[action.trigger] === 0) {
  53978. delete ActionManager.Triggers[action.trigger];
  53979. }
  53980. }
  53981. if (index > -1) {
  53982. this._scene.actionManagers.splice(index, 1);
  53983. }
  53984. };
  53985. /**
  53986. * Gets hosting scene
  53987. * @returns the hosting scene
  53988. */
  53989. ActionManager.prototype.getScene = function () {
  53990. return this._scene;
  53991. };
  53992. /**
  53993. * Does this action manager handles actions of any of the given triggers
  53994. * @param triggers defines the triggers to be tested
  53995. * @return a boolean indicating whether one (or more) of the triggers is handled
  53996. */
  53997. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53998. for (var index = 0; index < this.actions.length; index++) {
  53999. var action = this.actions[index];
  54000. if (triggers.indexOf(action.trigger) > -1) {
  54001. return true;
  54002. }
  54003. }
  54004. return false;
  54005. };
  54006. /**
  54007. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  54008. * speed.
  54009. * @param triggerA defines the trigger to be tested
  54010. * @param triggerB defines the trigger to be tested
  54011. * @return a boolean indicating whether one (or more) of the triggers is handled
  54012. */
  54013. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  54014. for (var index = 0; index < this.actions.length; index++) {
  54015. var action = this.actions[index];
  54016. if (triggerA == action.trigger || triggerB == action.trigger) {
  54017. return true;
  54018. }
  54019. }
  54020. return false;
  54021. };
  54022. /**
  54023. * Does this action manager handles actions of a given trigger
  54024. * @param trigger defines the trigger to be tested
  54025. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  54026. * @return whether the trigger is handled
  54027. */
  54028. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  54029. for (var index = 0; index < this.actions.length; index++) {
  54030. var action = this.actions[index];
  54031. if (action.trigger === trigger) {
  54032. if (parameterPredicate) {
  54033. if (parameterPredicate(action.getTriggerParameter())) {
  54034. return true;
  54035. }
  54036. }
  54037. else {
  54038. return true;
  54039. }
  54040. }
  54041. }
  54042. return false;
  54043. };
  54044. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  54045. /**
  54046. * Does this action manager has pointer triggers
  54047. */
  54048. get: function () {
  54049. for (var index = 0; index < this.actions.length; index++) {
  54050. var action = this.actions[index];
  54051. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  54052. return true;
  54053. }
  54054. }
  54055. return false;
  54056. },
  54057. enumerable: true,
  54058. configurable: true
  54059. });
  54060. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  54061. /**
  54062. * Does this action manager has pick triggers
  54063. */
  54064. get: function () {
  54065. for (var index = 0; index < this.actions.length; index++) {
  54066. var action = this.actions[index];
  54067. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  54068. return true;
  54069. }
  54070. }
  54071. return false;
  54072. },
  54073. enumerable: true,
  54074. configurable: true
  54075. });
  54076. Object.defineProperty(ActionManager, "HasTriggers", {
  54077. /**
  54078. * Does exist one action manager with at least one trigger
  54079. **/
  54080. get: function () {
  54081. for (var t in ActionManager.Triggers) {
  54082. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54083. return true;
  54084. }
  54085. }
  54086. return false;
  54087. },
  54088. enumerable: true,
  54089. configurable: true
  54090. });
  54091. Object.defineProperty(ActionManager, "HasPickTriggers", {
  54092. /**
  54093. * Does exist one action manager with at least one pick trigger
  54094. **/
  54095. get: function () {
  54096. for (var t in ActionManager.Triggers) {
  54097. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54098. var t_int = parseInt(t);
  54099. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  54100. return true;
  54101. }
  54102. }
  54103. }
  54104. return false;
  54105. },
  54106. enumerable: true,
  54107. configurable: true
  54108. });
  54109. /**
  54110. * Does exist one action manager that handles actions of a given trigger
  54111. * @param trigger defines the trigger to be tested
  54112. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  54113. **/
  54114. ActionManager.HasSpecificTrigger = function (trigger) {
  54115. for (var t in ActionManager.Triggers) {
  54116. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54117. var t_int = parseInt(t);
  54118. if (t_int === trigger) {
  54119. return true;
  54120. }
  54121. }
  54122. }
  54123. return false;
  54124. };
  54125. /**
  54126. * Registers an action to this action manager
  54127. * @param action defines the action to be registered
  54128. * @return the action amended (prepared) after registration
  54129. */
  54130. ActionManager.prototype.registerAction = function (action) {
  54131. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  54132. if (this.getScene().actionManager !== this) {
  54133. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  54134. return null;
  54135. }
  54136. }
  54137. this.actions.push(action);
  54138. if (ActionManager.Triggers[action.trigger]) {
  54139. ActionManager.Triggers[action.trigger]++;
  54140. }
  54141. else {
  54142. ActionManager.Triggers[action.trigger] = 1;
  54143. }
  54144. action._actionManager = this;
  54145. action._prepare();
  54146. return action;
  54147. };
  54148. /**
  54149. * Unregisters an action to this action manager
  54150. * @param action defines the action to be unregistered
  54151. * @return a boolean indicating whether the action has been unregistered
  54152. */
  54153. ActionManager.prototype.unregisterAction = function (action) {
  54154. var index = this.actions.indexOf(action);
  54155. if (index !== -1) {
  54156. this.actions.splice(index, 1);
  54157. ActionManager.Triggers[action.trigger] -= 1;
  54158. if (ActionManager.Triggers[action.trigger] === 0) {
  54159. delete ActionManager.Triggers[action.trigger];
  54160. }
  54161. delete action._actionManager;
  54162. return true;
  54163. }
  54164. return false;
  54165. };
  54166. /**
  54167. * Process a specific trigger
  54168. * @param trigger defines the trigger to process
  54169. * @param evt defines the event details to be processed
  54170. */
  54171. ActionManager.prototype.processTrigger = function (trigger, evt) {
  54172. for (var index = 0; index < this.actions.length; index++) {
  54173. var action = this.actions[index];
  54174. if (action.trigger === trigger) {
  54175. if (evt) {
  54176. if (trigger === ActionManager.OnKeyUpTrigger
  54177. || trigger === ActionManager.OnKeyDownTrigger) {
  54178. var parameter = action.getTriggerParameter();
  54179. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  54180. if (!parameter.toLowerCase) {
  54181. continue;
  54182. }
  54183. var lowerCase = parameter.toLowerCase();
  54184. if (lowerCase !== evt.sourceEvent.key) {
  54185. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  54186. var actualkey = String.fromCharCode(unicode).toLowerCase();
  54187. if (actualkey !== lowerCase) {
  54188. continue;
  54189. }
  54190. }
  54191. }
  54192. }
  54193. }
  54194. action._executeCurrent(evt);
  54195. }
  54196. }
  54197. };
  54198. /** @hidden */
  54199. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  54200. var properties = propertyPath.split(".");
  54201. for (var index = 0; index < properties.length - 1; index++) {
  54202. target = target[properties[index]];
  54203. }
  54204. return target;
  54205. };
  54206. /** @hidden */
  54207. ActionManager.prototype._getProperty = function (propertyPath) {
  54208. var properties = propertyPath.split(".");
  54209. return properties[properties.length - 1];
  54210. };
  54211. /**
  54212. * Serialize this manager to a JSON object
  54213. * @param name defines the property name to store this manager
  54214. * @returns a JSON representation of this manager
  54215. */
  54216. ActionManager.prototype.serialize = function (name) {
  54217. var root = {
  54218. children: new Array(),
  54219. name: name,
  54220. type: 3,
  54221. properties: new Array() // Empty for root but required
  54222. };
  54223. for (var i = 0; i < this.actions.length; i++) {
  54224. var triggerObject = {
  54225. type: 0,
  54226. children: new Array(),
  54227. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  54228. properties: new Array()
  54229. };
  54230. var triggerOptions = this.actions[i].triggerOptions;
  54231. if (triggerOptions && typeof triggerOptions !== "number") {
  54232. if (triggerOptions.parameter instanceof BABYLON.Node) {
  54233. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  54234. }
  54235. else {
  54236. var parameter = {};
  54237. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  54238. if (triggerOptions.parameter.mesh) {
  54239. parameter._meshId = triggerOptions.parameter.mesh.id;
  54240. }
  54241. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  54242. }
  54243. }
  54244. // Serialize child action, recursively
  54245. this.actions[i].serialize(triggerObject);
  54246. // Add serialized trigger
  54247. root.children.push(triggerObject);
  54248. }
  54249. return root;
  54250. };
  54251. /**
  54252. * Creates a new ActionManager from a JSON data
  54253. * @param parsedActions defines the JSON data to read from
  54254. * @param object defines the hosting mesh
  54255. * @param scene defines the hosting scene
  54256. */
  54257. ActionManager.Parse = function (parsedActions, object, scene) {
  54258. var actionManager = new ActionManager(scene);
  54259. if (object === null)
  54260. scene.actionManager = actionManager;
  54261. else
  54262. object.actionManager = actionManager;
  54263. // instanciate a new object
  54264. var instanciate = function (name, params) {
  54265. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  54266. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  54267. newInstance.constructor.apply(newInstance, params);
  54268. return newInstance;
  54269. };
  54270. var parseParameter = function (name, value, target, propertyPath) {
  54271. if (propertyPath === null) {
  54272. // String, boolean or float
  54273. var floatValue = parseFloat(value);
  54274. if (value === "true" || value === "false")
  54275. return value === "true";
  54276. else
  54277. return isNaN(floatValue) ? value : floatValue;
  54278. }
  54279. var effectiveTarget = propertyPath.split(".");
  54280. var values = value.split(",");
  54281. // Get effective Target
  54282. for (var i = 0; i < effectiveTarget.length; i++) {
  54283. target = target[effectiveTarget[i]];
  54284. }
  54285. // Return appropriate value with its type
  54286. if (typeof (target) === "boolean")
  54287. return values[0] === "true";
  54288. if (typeof (target) === "string")
  54289. return values[0];
  54290. // Parameters with multiple values such as Vector3 etc.
  54291. var split = new Array();
  54292. for (var i = 0; i < values.length; i++)
  54293. split.push(parseFloat(values[i]));
  54294. if (target instanceof BABYLON.Vector3)
  54295. return BABYLON.Vector3.FromArray(split);
  54296. if (target instanceof BABYLON.Vector4)
  54297. return BABYLON.Vector4.FromArray(split);
  54298. if (target instanceof BABYLON.Color3)
  54299. return BABYLON.Color3.FromArray(split);
  54300. if (target instanceof BABYLON.Color4)
  54301. return BABYLON.Color4.FromArray(split);
  54302. return parseFloat(values[0]);
  54303. };
  54304. // traverse graph per trigger
  54305. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  54306. if (combineArray === void 0) { combineArray = null; }
  54307. if (parsedAction.detached)
  54308. return;
  54309. var parameters = new Array();
  54310. var target = null;
  54311. var propertyPath = null;
  54312. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  54313. // Parameters
  54314. if (parsedAction.type === 2)
  54315. parameters.push(actionManager);
  54316. else
  54317. parameters.push(trigger);
  54318. if (combine) {
  54319. var actions = new Array();
  54320. for (var j = 0; j < parsedAction.combine.length; j++) {
  54321. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  54322. }
  54323. parameters.push(actions);
  54324. }
  54325. else {
  54326. for (var i = 0; i < parsedAction.properties.length; i++) {
  54327. var value = parsedAction.properties[i].value;
  54328. var name = parsedAction.properties[i].name;
  54329. var targetType = parsedAction.properties[i].targetType;
  54330. if (name === "target")
  54331. if (targetType !== null && targetType === "SceneProperties")
  54332. value = target = scene;
  54333. else
  54334. value = target = scene.getNodeByName(value);
  54335. else if (name === "parent")
  54336. value = scene.getNodeByName(value);
  54337. else if (name === "sound") {
  54338. // Can not externalize to component, so only checks for the presence off the API.
  54339. if (scene.getSoundByName) {
  54340. value = scene.getSoundByName(value);
  54341. }
  54342. }
  54343. else if (name !== "propertyPath") {
  54344. if (parsedAction.type === 2 && name === "operator")
  54345. value = BABYLON.ValueCondition[value];
  54346. else
  54347. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  54348. }
  54349. else {
  54350. propertyPath = value;
  54351. }
  54352. parameters.push(value);
  54353. }
  54354. }
  54355. if (combineArray === null) {
  54356. parameters.push(condition);
  54357. }
  54358. else {
  54359. parameters.push(null);
  54360. }
  54361. // If interpolate value action
  54362. if (parsedAction.name === "InterpolateValueAction") {
  54363. var param = parameters[parameters.length - 2];
  54364. parameters[parameters.length - 1] = param;
  54365. parameters[parameters.length - 2] = condition;
  54366. }
  54367. // Action or condition(s) and not CombineAction
  54368. var newAction = instanciate(parsedAction.name, parameters);
  54369. if (newAction instanceof BABYLON.Condition && condition !== null) {
  54370. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  54371. if (action)
  54372. action.then(nothing);
  54373. else
  54374. actionManager.registerAction(nothing);
  54375. action = nothing;
  54376. }
  54377. if (combineArray === null) {
  54378. if (newAction instanceof BABYLON.Condition) {
  54379. condition = newAction;
  54380. newAction = action;
  54381. }
  54382. else {
  54383. condition = null;
  54384. if (action)
  54385. action.then(newAction);
  54386. else
  54387. actionManager.registerAction(newAction);
  54388. }
  54389. }
  54390. else {
  54391. combineArray.push(newAction);
  54392. }
  54393. for (var i = 0; i < parsedAction.children.length; i++)
  54394. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54395. };
  54396. // triggers
  54397. for (var i = 0; i < parsedActions.children.length; i++) {
  54398. var triggerParams;
  54399. var trigger = parsedActions.children[i];
  54400. if (trigger.properties.length > 0) {
  54401. var param = trigger.properties[0].value;
  54402. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54403. if (value._meshId) {
  54404. value.mesh = scene.getMeshByID(value._meshId);
  54405. }
  54406. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54407. }
  54408. else
  54409. triggerParams = ActionManager[trigger.name];
  54410. for (var j = 0; j < trigger.children.length; j++) {
  54411. if (!trigger.detached)
  54412. traverse(trigger.children[j], triggerParams, null, null);
  54413. }
  54414. }
  54415. };
  54416. /**
  54417. * Get a trigger name by index
  54418. * @param trigger defines the trigger index
  54419. * @returns a trigger name
  54420. */
  54421. ActionManager.GetTriggerName = function (trigger) {
  54422. switch (trigger) {
  54423. case 0: return "NothingTrigger";
  54424. case 1: return "OnPickTrigger";
  54425. case 2: return "OnLeftPickTrigger";
  54426. case 3: return "OnRightPickTrigger";
  54427. case 4: return "OnCenterPickTrigger";
  54428. case 5: return "OnPickDownTrigger";
  54429. case 6: return "OnPickUpTrigger";
  54430. case 7: return "OnLongPressTrigger";
  54431. case 8: return "OnPointerOverTrigger";
  54432. case 9: return "OnPointerOutTrigger";
  54433. case 10: return "OnEveryFrameTrigger";
  54434. case 11: return "OnIntersectionEnterTrigger";
  54435. case 12: return "OnIntersectionExitTrigger";
  54436. case 13: return "OnKeyDownTrigger";
  54437. case 14: return "OnKeyUpTrigger";
  54438. case 15: return "OnPickOutTrigger";
  54439. default: return "";
  54440. }
  54441. };
  54442. /**
  54443. * Nothing
  54444. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54445. */
  54446. ActionManager.NothingTrigger = 0;
  54447. /**
  54448. * On pick
  54449. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54450. */
  54451. ActionManager.OnPickTrigger = 1;
  54452. /**
  54453. * On left pick
  54454. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54455. */
  54456. ActionManager.OnLeftPickTrigger = 2;
  54457. /**
  54458. * On right pick
  54459. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54460. */
  54461. ActionManager.OnRightPickTrigger = 3;
  54462. /**
  54463. * On center pick
  54464. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54465. */
  54466. ActionManager.OnCenterPickTrigger = 4;
  54467. /**
  54468. * On pick down
  54469. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54470. */
  54471. ActionManager.OnPickDownTrigger = 5;
  54472. /**
  54473. * On double pick
  54474. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54475. */
  54476. ActionManager.OnDoublePickTrigger = 6;
  54477. /**
  54478. * On pick up
  54479. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54480. */
  54481. ActionManager.OnPickUpTrigger = 7;
  54482. /**
  54483. * On pick out.
  54484. * This trigger will only be raised if you also declared a OnPickDown
  54485. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54486. */
  54487. ActionManager.OnPickOutTrigger = 16;
  54488. /**
  54489. * On long press
  54490. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54491. */
  54492. ActionManager.OnLongPressTrigger = 8;
  54493. /**
  54494. * On pointer over
  54495. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54496. */
  54497. ActionManager.OnPointerOverTrigger = 9;
  54498. /**
  54499. * On pointer out
  54500. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54501. */
  54502. ActionManager.OnPointerOutTrigger = 10;
  54503. /**
  54504. * On every frame
  54505. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54506. */
  54507. ActionManager.OnEveryFrameTrigger = 11;
  54508. /**
  54509. * On intersection enter
  54510. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54511. */
  54512. ActionManager.OnIntersectionEnterTrigger = 12;
  54513. /**
  54514. * On intersection exit
  54515. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54516. */
  54517. ActionManager.OnIntersectionExitTrigger = 13;
  54518. /**
  54519. * On key down
  54520. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54521. */
  54522. ActionManager.OnKeyDownTrigger = 14;
  54523. /**
  54524. * On key up
  54525. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54526. */
  54527. ActionManager.OnKeyUpTrigger = 15;
  54528. /** Gets the list of active triggers */
  54529. ActionManager.Triggers = {};
  54530. return ActionManager;
  54531. }());
  54532. BABYLON.ActionManager = ActionManager;
  54533. })(BABYLON || (BABYLON = {}));
  54534. //# sourceMappingURL=babylon.actionManager.js.map
  54535. var BABYLON;
  54536. (function (BABYLON) {
  54537. /**
  54538. * This defines an action responsible to change the value of a property
  54539. * by interpolating between its current value and the newly set one once triggered.
  54540. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54541. */
  54542. var InterpolateValueAction = /** @class */ (function (_super) {
  54543. __extends(InterpolateValueAction, _super);
  54544. /**
  54545. * Instantiate the action
  54546. * @param triggerOptions defines the trigger options
  54547. * @param target defines the object containing the value to interpolate
  54548. * @param propertyPath defines the path to the property in the target object
  54549. * @param value defines the target value at the end of the interpolation
  54550. * @param duration deines the time it will take for the property to interpolate to the value.
  54551. * @param condition defines the trigger related conditions
  54552. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  54553. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  54554. */
  54555. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54556. if (duration === void 0) { duration = 1000; }
  54557. var _this = _super.call(this, triggerOptions, condition) || this;
  54558. /**
  54559. * Defines the time it will take for the property to interpolate to the value.
  54560. */
  54561. _this.duration = 1000;
  54562. /**
  54563. * Observable triggered once the interpolation animation has been done.
  54564. */
  54565. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54566. _this.propertyPath = propertyPath;
  54567. _this.value = value;
  54568. _this.duration = duration;
  54569. _this.stopOtherAnimations = stopOtherAnimations;
  54570. _this.onInterpolationDone = onInterpolationDone;
  54571. _this._target = _this._effectiveTarget = target;
  54572. return _this;
  54573. }
  54574. /** @hidden */
  54575. InterpolateValueAction.prototype._prepare = function () {
  54576. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54577. this._property = this._getProperty(this.propertyPath);
  54578. };
  54579. /**
  54580. * Execute the action starts the value interpolation.
  54581. */
  54582. InterpolateValueAction.prototype.execute = function () {
  54583. var _this = this;
  54584. var scene = this._actionManager.getScene();
  54585. var keys = [
  54586. {
  54587. frame: 0,
  54588. value: this._effectiveTarget[this._property]
  54589. }, {
  54590. frame: 100,
  54591. value: this.value
  54592. }
  54593. ];
  54594. var dataType;
  54595. if (typeof this.value === "number") {
  54596. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54597. }
  54598. else if (this.value instanceof BABYLON.Color3) {
  54599. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54600. }
  54601. else if (this.value instanceof BABYLON.Vector3) {
  54602. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54603. }
  54604. else if (this.value instanceof BABYLON.Matrix) {
  54605. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54606. }
  54607. else if (this.value instanceof BABYLON.Quaternion) {
  54608. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54609. }
  54610. else {
  54611. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54612. return;
  54613. }
  54614. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54615. animation.setKeys(keys);
  54616. if (this.stopOtherAnimations) {
  54617. scene.stopAnimation(this._effectiveTarget);
  54618. }
  54619. var wrapper = function () {
  54620. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54621. if (_this.onInterpolationDone) {
  54622. _this.onInterpolationDone();
  54623. }
  54624. };
  54625. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54626. };
  54627. /**
  54628. * Serializes the actions and its related information.
  54629. * @param parent defines the object to serialize in
  54630. * @returns the serialized object
  54631. */
  54632. InterpolateValueAction.prototype.serialize = function (parent) {
  54633. return _super.prototype._serialize.call(this, {
  54634. name: "InterpolateValueAction",
  54635. properties: [
  54636. BABYLON.Action._GetTargetProperty(this._target),
  54637. { name: "propertyPath", value: this.propertyPath },
  54638. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54639. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54640. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54641. ]
  54642. }, parent);
  54643. };
  54644. return InterpolateValueAction;
  54645. }(BABYLON.Action));
  54646. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54647. })(BABYLON || (BABYLON = {}));
  54648. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54649. var BABYLON;
  54650. (function (BABYLON) {
  54651. /**
  54652. * This defines an action responsible to toggle a boolean once triggered.
  54653. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54654. */
  54655. var SwitchBooleanAction = /** @class */ (function (_super) {
  54656. __extends(SwitchBooleanAction, _super);
  54657. /**
  54658. * Instantiate the action
  54659. * @param triggerOptions defines the trigger options
  54660. * @param target defines the object containing the boolean
  54661. * @param propertyPath defines the path to the boolean property in the target object
  54662. * @param condition defines the trigger related conditions
  54663. */
  54664. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54665. var _this = _super.call(this, triggerOptions, condition) || this;
  54666. _this.propertyPath = propertyPath;
  54667. _this._target = _this._effectiveTarget = target;
  54668. return _this;
  54669. }
  54670. /** @hidden */
  54671. SwitchBooleanAction.prototype._prepare = function () {
  54672. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54673. this._property = this._getProperty(this.propertyPath);
  54674. };
  54675. /**
  54676. * Execute the action toggle the boolean value.
  54677. */
  54678. SwitchBooleanAction.prototype.execute = function () {
  54679. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54680. };
  54681. /**
  54682. * Serializes the actions and its related information.
  54683. * @param parent defines the object to serialize in
  54684. * @returns the serialized object
  54685. */
  54686. SwitchBooleanAction.prototype.serialize = function (parent) {
  54687. return _super.prototype._serialize.call(this, {
  54688. name: "SwitchBooleanAction",
  54689. properties: [
  54690. BABYLON.Action._GetTargetProperty(this._target),
  54691. { name: "propertyPath", value: this.propertyPath }
  54692. ]
  54693. }, parent);
  54694. };
  54695. return SwitchBooleanAction;
  54696. }(BABYLON.Action));
  54697. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54698. /**
  54699. * This defines an action responsible to set a the state field of the target
  54700. * to a desired value once triggered.
  54701. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54702. */
  54703. var SetStateAction = /** @class */ (function (_super) {
  54704. __extends(SetStateAction, _super);
  54705. /**
  54706. * Instantiate the action
  54707. * @param triggerOptions defines the trigger options
  54708. * @param target defines the object containing the state property
  54709. * @param value defines the value to store in the state field
  54710. * @param condition defines the trigger related conditions
  54711. */
  54712. function SetStateAction(triggerOptions, target, value, condition) {
  54713. var _this = _super.call(this, triggerOptions, condition) || this;
  54714. _this.value = value;
  54715. _this._target = target;
  54716. return _this;
  54717. }
  54718. /**
  54719. * Execute the action and store the value on the target state property.
  54720. */
  54721. SetStateAction.prototype.execute = function () {
  54722. this._target.state = this.value;
  54723. };
  54724. /**
  54725. * Serializes the actions and its related information.
  54726. * @param parent defines the object to serialize in
  54727. * @returns the serialized object
  54728. */
  54729. SetStateAction.prototype.serialize = function (parent) {
  54730. return _super.prototype._serialize.call(this, {
  54731. name: "SetStateAction",
  54732. properties: [
  54733. BABYLON.Action._GetTargetProperty(this._target),
  54734. { name: "value", value: this.value }
  54735. ]
  54736. }, parent);
  54737. };
  54738. return SetStateAction;
  54739. }(BABYLON.Action));
  54740. BABYLON.SetStateAction = SetStateAction;
  54741. /**
  54742. * This defines an action responsible to set a property of the target
  54743. * to a desired value once triggered.
  54744. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54745. */
  54746. var SetValueAction = /** @class */ (function (_super) {
  54747. __extends(SetValueAction, _super);
  54748. /**
  54749. * Instantiate the action
  54750. * @param triggerOptions defines the trigger options
  54751. * @param target defines the object containing the property
  54752. * @param propertyPath defines the path of the property to set in the target
  54753. * @param value defines the value to set in the property
  54754. * @param condition defines the trigger related conditions
  54755. */
  54756. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54757. var _this = _super.call(this, triggerOptions, condition) || this;
  54758. _this.propertyPath = propertyPath;
  54759. _this.value = value;
  54760. _this._target = _this._effectiveTarget = target;
  54761. return _this;
  54762. }
  54763. /** @hidden */
  54764. SetValueAction.prototype._prepare = function () {
  54765. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54766. this._property = this._getProperty(this.propertyPath);
  54767. };
  54768. /**
  54769. * Execute the action and set the targetted property to the desired value.
  54770. */
  54771. SetValueAction.prototype.execute = function () {
  54772. this._effectiveTarget[this._property] = this.value;
  54773. if (this._target.markAsDirty) {
  54774. this._target.markAsDirty(this._property);
  54775. }
  54776. };
  54777. /**
  54778. * Serializes the actions and its related information.
  54779. * @param parent defines the object to serialize in
  54780. * @returns the serialized object
  54781. */
  54782. SetValueAction.prototype.serialize = function (parent) {
  54783. return _super.prototype._serialize.call(this, {
  54784. name: "SetValueAction",
  54785. properties: [
  54786. BABYLON.Action._GetTargetProperty(this._target),
  54787. { name: "propertyPath", value: this.propertyPath },
  54788. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54789. ]
  54790. }, parent);
  54791. };
  54792. return SetValueAction;
  54793. }(BABYLON.Action));
  54794. BABYLON.SetValueAction = SetValueAction;
  54795. /**
  54796. * This defines an action responsible to increment the target value
  54797. * to a desired value once triggered.
  54798. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54799. */
  54800. var IncrementValueAction = /** @class */ (function (_super) {
  54801. __extends(IncrementValueAction, _super);
  54802. /**
  54803. * Instantiate the action
  54804. * @param triggerOptions defines the trigger options
  54805. * @param target defines the object containing the property
  54806. * @param propertyPath defines the path of the property to increment in the target
  54807. * @param value defines the value value we should increment the property by
  54808. * @param condition defines the trigger related conditions
  54809. */
  54810. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54811. var _this = _super.call(this, triggerOptions, condition) || this;
  54812. _this.propertyPath = propertyPath;
  54813. _this.value = value;
  54814. _this._target = _this._effectiveTarget = target;
  54815. return _this;
  54816. }
  54817. /** @hidden */
  54818. IncrementValueAction.prototype._prepare = function () {
  54819. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54820. this._property = this._getProperty(this.propertyPath);
  54821. if (typeof this._effectiveTarget[this._property] !== "number") {
  54822. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54823. }
  54824. };
  54825. /**
  54826. * Execute the action and increment the target of the value amount.
  54827. */
  54828. IncrementValueAction.prototype.execute = function () {
  54829. this._effectiveTarget[this._property] += this.value;
  54830. if (this._target.markAsDirty) {
  54831. this._target.markAsDirty(this._property);
  54832. }
  54833. };
  54834. /**
  54835. * Serializes the actions and its related information.
  54836. * @param parent defines the object to serialize in
  54837. * @returns the serialized object
  54838. */
  54839. IncrementValueAction.prototype.serialize = function (parent) {
  54840. return _super.prototype._serialize.call(this, {
  54841. name: "IncrementValueAction",
  54842. properties: [
  54843. BABYLON.Action._GetTargetProperty(this._target),
  54844. { name: "propertyPath", value: this.propertyPath },
  54845. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54846. ]
  54847. }, parent);
  54848. };
  54849. return IncrementValueAction;
  54850. }(BABYLON.Action));
  54851. BABYLON.IncrementValueAction = IncrementValueAction;
  54852. /**
  54853. * This defines an action responsible to start an animation once triggered.
  54854. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54855. */
  54856. var PlayAnimationAction = /** @class */ (function (_super) {
  54857. __extends(PlayAnimationAction, _super);
  54858. /**
  54859. * Instantiate the action
  54860. * @param triggerOptions defines the trigger options
  54861. * @param target defines the target animation or animation name
  54862. * @param from defines from where the animation should start (animation frame)
  54863. * @param end defines where the animation should stop (animation frame)
  54864. * @param loop defines if the animation should loop or stop after the first play
  54865. * @param condition defines the trigger related conditions
  54866. */
  54867. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54868. var _this = _super.call(this, triggerOptions, condition) || this;
  54869. _this.from = from;
  54870. _this.to = to;
  54871. _this.loop = loop;
  54872. _this._target = target;
  54873. return _this;
  54874. }
  54875. /** @hidden */
  54876. PlayAnimationAction.prototype._prepare = function () {
  54877. };
  54878. /**
  54879. * Execute the action and play the animation.
  54880. */
  54881. PlayAnimationAction.prototype.execute = function () {
  54882. var scene = this._actionManager.getScene();
  54883. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54884. };
  54885. /**
  54886. * Serializes the actions and its related information.
  54887. * @param parent defines the object to serialize in
  54888. * @returns the serialized object
  54889. */
  54890. PlayAnimationAction.prototype.serialize = function (parent) {
  54891. return _super.prototype._serialize.call(this, {
  54892. name: "PlayAnimationAction",
  54893. properties: [
  54894. BABYLON.Action._GetTargetProperty(this._target),
  54895. { name: "from", value: String(this.from) },
  54896. { name: "to", value: String(this.to) },
  54897. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54898. ]
  54899. }, parent);
  54900. };
  54901. return PlayAnimationAction;
  54902. }(BABYLON.Action));
  54903. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54904. /**
  54905. * This defines an action responsible to stop an animation once triggered.
  54906. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54907. */
  54908. var StopAnimationAction = /** @class */ (function (_super) {
  54909. __extends(StopAnimationAction, _super);
  54910. /**
  54911. * Instantiate the action
  54912. * @param triggerOptions defines the trigger options
  54913. * @param target defines the target animation or animation name
  54914. * @param condition defines the trigger related conditions
  54915. */
  54916. function StopAnimationAction(triggerOptions, target, condition) {
  54917. var _this = _super.call(this, triggerOptions, condition) || this;
  54918. _this._target = target;
  54919. return _this;
  54920. }
  54921. /** @hidden */
  54922. StopAnimationAction.prototype._prepare = function () {
  54923. };
  54924. /**
  54925. * Execute the action and stop the animation.
  54926. */
  54927. StopAnimationAction.prototype.execute = function () {
  54928. var scene = this._actionManager.getScene();
  54929. scene.stopAnimation(this._target);
  54930. };
  54931. /**
  54932. * Serializes the actions and its related information.
  54933. * @param parent defines the object to serialize in
  54934. * @returns the serialized object
  54935. */
  54936. StopAnimationAction.prototype.serialize = function (parent) {
  54937. return _super.prototype._serialize.call(this, {
  54938. name: "StopAnimationAction",
  54939. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54940. }, parent);
  54941. };
  54942. return StopAnimationAction;
  54943. }(BABYLON.Action));
  54944. BABYLON.StopAnimationAction = StopAnimationAction;
  54945. /**
  54946. * This defines an action responsible that does nothing once triggered.
  54947. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54948. */
  54949. var DoNothingAction = /** @class */ (function (_super) {
  54950. __extends(DoNothingAction, _super);
  54951. /**
  54952. * Instantiate the action
  54953. * @param triggerOptions defines the trigger options
  54954. * @param condition defines the trigger related conditions
  54955. */
  54956. function DoNothingAction(triggerOptions, condition) {
  54957. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54958. return _super.call(this, triggerOptions, condition) || this;
  54959. }
  54960. /**
  54961. * Execute the action and do nothing.
  54962. */
  54963. DoNothingAction.prototype.execute = function () {
  54964. };
  54965. /**
  54966. * Serializes the actions and its related information.
  54967. * @param parent defines the object to serialize in
  54968. * @returns the serialized object
  54969. */
  54970. DoNothingAction.prototype.serialize = function (parent) {
  54971. return _super.prototype._serialize.call(this, {
  54972. name: "DoNothingAction",
  54973. properties: []
  54974. }, parent);
  54975. };
  54976. return DoNothingAction;
  54977. }(BABYLON.Action));
  54978. BABYLON.DoNothingAction = DoNothingAction;
  54979. /**
  54980. * This defines an action responsible to trigger several actions once triggered.
  54981. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54982. */
  54983. var CombineAction = /** @class */ (function (_super) {
  54984. __extends(CombineAction, _super);
  54985. /**
  54986. * Instantiate the action
  54987. * @param triggerOptions defines the trigger options
  54988. * @param children defines the list of aggregated animations to run
  54989. * @param condition defines the trigger related conditions
  54990. */
  54991. function CombineAction(triggerOptions, children, condition) {
  54992. var _this = _super.call(this, triggerOptions, condition) || this;
  54993. _this.children = children;
  54994. return _this;
  54995. }
  54996. /** @hidden */
  54997. CombineAction.prototype._prepare = function () {
  54998. for (var index = 0; index < this.children.length; index++) {
  54999. this.children[index]._actionManager = this._actionManager;
  55000. this.children[index]._prepare();
  55001. }
  55002. };
  55003. /**
  55004. * Execute the action and executes all the aggregated actions.
  55005. */
  55006. CombineAction.prototype.execute = function (evt) {
  55007. for (var index = 0; index < this.children.length; index++) {
  55008. this.children[index].execute(evt);
  55009. }
  55010. };
  55011. /**
  55012. * Serializes the actions and its related information.
  55013. * @param parent defines the object to serialize in
  55014. * @returns the serialized object
  55015. */
  55016. CombineAction.prototype.serialize = function (parent) {
  55017. var serializationObject = _super.prototype._serialize.call(this, {
  55018. name: "CombineAction",
  55019. properties: [],
  55020. combine: []
  55021. }, parent);
  55022. for (var i = 0; i < this.children.length; i++) {
  55023. serializationObject.combine.push(this.children[i].serialize(null));
  55024. }
  55025. return serializationObject;
  55026. };
  55027. return CombineAction;
  55028. }(BABYLON.Action));
  55029. BABYLON.CombineAction = CombineAction;
  55030. /**
  55031. * This defines an action responsible to run code (external event) once triggered.
  55032. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55033. */
  55034. var ExecuteCodeAction = /** @class */ (function (_super) {
  55035. __extends(ExecuteCodeAction, _super);
  55036. /**
  55037. * Instantiate the action
  55038. * @param triggerOptions defines the trigger options
  55039. * @param func defines the callback function to run
  55040. * @param condition defines the trigger related conditions
  55041. */
  55042. function ExecuteCodeAction(triggerOptions, func, condition) {
  55043. var _this = _super.call(this, triggerOptions, condition) || this;
  55044. _this.func = func;
  55045. return _this;
  55046. }
  55047. /**
  55048. * Execute the action and run the attached code.
  55049. */
  55050. ExecuteCodeAction.prototype.execute = function (evt) {
  55051. this.func(evt);
  55052. };
  55053. return ExecuteCodeAction;
  55054. }(BABYLON.Action));
  55055. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  55056. /**
  55057. * This defines an action responsible to set the parent property of the target once triggered.
  55058. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55059. */
  55060. var SetParentAction = /** @class */ (function (_super) {
  55061. __extends(SetParentAction, _super);
  55062. /**
  55063. * Instantiate the action
  55064. * @param triggerOptions defines the trigger options
  55065. * @param target defines the target containing the parent property
  55066. * @param parent defines from where the animation should start (animation frame)
  55067. * @param condition defines the trigger related conditions
  55068. */
  55069. function SetParentAction(triggerOptions, target, parent, condition) {
  55070. var _this = _super.call(this, triggerOptions, condition) || this;
  55071. _this._target = target;
  55072. _this._parent = parent;
  55073. return _this;
  55074. }
  55075. /** @hidden */
  55076. SetParentAction.prototype._prepare = function () {
  55077. };
  55078. /**
  55079. * Execute the action and set the parent property.
  55080. */
  55081. SetParentAction.prototype.execute = function () {
  55082. if (this._target.parent === this._parent) {
  55083. return;
  55084. }
  55085. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  55086. invertParentWorldMatrix.invert();
  55087. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  55088. this._target.parent = this._parent;
  55089. };
  55090. /**
  55091. * Serializes the actions and its related information.
  55092. * @param parent defines the object to serialize in
  55093. * @returns the serialized object
  55094. */
  55095. SetParentAction.prototype.serialize = function (parent) {
  55096. return _super.prototype._serialize.call(this, {
  55097. name: "SetParentAction",
  55098. properties: [
  55099. BABYLON.Action._GetTargetProperty(this._target),
  55100. BABYLON.Action._GetTargetProperty(this._parent),
  55101. ]
  55102. }, parent);
  55103. };
  55104. return SetParentAction;
  55105. }(BABYLON.Action));
  55106. BABYLON.SetParentAction = SetParentAction;
  55107. })(BABYLON || (BABYLON = {}));
  55108. //# sourceMappingURL=babylon.directActions.js.map
  55109. var BABYLON;
  55110. (function (BABYLON) {
  55111. var SpriteManager = /** @class */ (function () {
  55112. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  55113. if (epsilon === void 0) { epsilon = 0.01; }
  55114. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55115. this.name = name;
  55116. this.sprites = new Array();
  55117. this.renderingGroupId = 0;
  55118. this.layerMask = 0x0FFFFFFF;
  55119. this.fogEnabled = true;
  55120. this.isPickable = false;
  55121. /**
  55122. * An event triggered when the manager is disposed.
  55123. */
  55124. this.onDisposeObservable = new BABYLON.Observable();
  55125. this._vertexBuffers = {};
  55126. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  55127. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  55128. }
  55129. this._capacity = capacity;
  55130. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  55131. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55132. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55133. if (cellSize.width && cellSize.height) {
  55134. this.cellWidth = cellSize.width;
  55135. this.cellHeight = cellSize.height;
  55136. }
  55137. else if (cellSize !== undefined) {
  55138. this.cellWidth = cellSize;
  55139. this.cellHeight = cellSize;
  55140. }
  55141. else {
  55142. return;
  55143. }
  55144. this._epsilon = epsilon;
  55145. this._scene = scene;
  55146. this._scene.spriteManagers.push(this);
  55147. var indices = [];
  55148. var index = 0;
  55149. for (var count = 0; count < capacity; count++) {
  55150. indices.push(index);
  55151. indices.push(index + 1);
  55152. indices.push(index + 2);
  55153. indices.push(index);
  55154. indices.push(index + 2);
  55155. indices.push(index + 3);
  55156. index += 4;
  55157. }
  55158. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  55159. // VBO
  55160. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  55161. this._vertexData = new Float32Array(capacity * 16 * 4);
  55162. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  55163. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  55164. var options = this._buffer.createVertexBuffer("options", 4, 4);
  55165. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  55166. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  55167. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55168. this._vertexBuffers["options"] = options;
  55169. this._vertexBuffers["cellInfo"] = cellInfo;
  55170. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55171. // Effects
  55172. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  55173. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  55174. }
  55175. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  55176. set: function (callback) {
  55177. if (this._onDisposeObserver) {
  55178. this.onDisposeObservable.remove(this._onDisposeObserver);
  55179. }
  55180. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55181. },
  55182. enumerable: true,
  55183. configurable: true
  55184. });
  55185. Object.defineProperty(SpriteManager.prototype, "texture", {
  55186. get: function () {
  55187. return this._spriteTexture;
  55188. },
  55189. set: function (value) {
  55190. this._spriteTexture = value;
  55191. },
  55192. enumerable: true,
  55193. configurable: true
  55194. });
  55195. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  55196. var arrayOffset = index * 16;
  55197. if (offsetX === 0)
  55198. offsetX = this._epsilon;
  55199. else if (offsetX === 1)
  55200. offsetX = 1 - this._epsilon;
  55201. if (offsetY === 0)
  55202. offsetY = this._epsilon;
  55203. else if (offsetY === 1)
  55204. offsetY = 1 - this._epsilon;
  55205. this._vertexData[arrayOffset] = sprite.position.x;
  55206. this._vertexData[arrayOffset + 1] = sprite.position.y;
  55207. this._vertexData[arrayOffset + 2] = sprite.position.z;
  55208. this._vertexData[arrayOffset + 3] = sprite.angle;
  55209. this._vertexData[arrayOffset + 4] = sprite.width;
  55210. this._vertexData[arrayOffset + 5] = sprite.height;
  55211. this._vertexData[arrayOffset + 6] = offsetX;
  55212. this._vertexData[arrayOffset + 7] = offsetY;
  55213. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  55214. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  55215. var offset = (sprite.cellIndex / rowSize) >> 0;
  55216. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  55217. this._vertexData[arrayOffset + 11] = offset;
  55218. // Color
  55219. this._vertexData[arrayOffset + 12] = sprite.color.r;
  55220. this._vertexData[arrayOffset + 13] = sprite.color.g;
  55221. this._vertexData[arrayOffset + 14] = sprite.color.b;
  55222. this._vertexData[arrayOffset + 15] = sprite.color.a;
  55223. };
  55224. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  55225. var count = Math.min(this._capacity, this.sprites.length);
  55226. var min = BABYLON.Vector3.Zero();
  55227. var max = BABYLON.Vector3.Zero();
  55228. var distance = Number.MAX_VALUE;
  55229. var currentSprite = null;
  55230. var cameraSpacePosition = BABYLON.Vector3.Zero();
  55231. var cameraView = camera.getViewMatrix();
  55232. for (var index = 0; index < count; index++) {
  55233. var sprite = this.sprites[index];
  55234. if (!sprite) {
  55235. continue;
  55236. }
  55237. if (predicate) {
  55238. if (!predicate(sprite)) {
  55239. continue;
  55240. }
  55241. }
  55242. else if (!sprite.isPickable) {
  55243. continue;
  55244. }
  55245. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  55246. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  55247. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  55248. if (ray.intersectsBoxMinMax(min, max)) {
  55249. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  55250. if (distance > currentDistance) {
  55251. distance = currentDistance;
  55252. currentSprite = sprite;
  55253. if (fastCheck) {
  55254. break;
  55255. }
  55256. }
  55257. }
  55258. }
  55259. if (currentSprite) {
  55260. var result = new BABYLON.PickingInfo();
  55261. result.hit = true;
  55262. result.pickedSprite = currentSprite;
  55263. result.distance = distance;
  55264. return result;
  55265. }
  55266. return null;
  55267. };
  55268. SpriteManager.prototype.render = function () {
  55269. // Check
  55270. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  55271. return;
  55272. var engine = this._scene.getEngine();
  55273. var baseSize = this._spriteTexture.getBaseSize();
  55274. // Sprites
  55275. var deltaTime = engine.getDeltaTime();
  55276. var max = Math.min(this._capacity, this.sprites.length);
  55277. var rowSize = baseSize.width / this.cellWidth;
  55278. var offset = 0;
  55279. for (var index = 0; index < max; index++) {
  55280. var sprite = this.sprites[index];
  55281. if (!sprite || !sprite.isVisible) {
  55282. continue;
  55283. }
  55284. sprite._animate(deltaTime);
  55285. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  55286. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  55287. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  55288. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  55289. }
  55290. this._buffer.update(this._vertexData);
  55291. // Render
  55292. var effect = this._effectBase;
  55293. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  55294. effect = this._effectFog;
  55295. }
  55296. engine.enableEffect(effect);
  55297. var viewMatrix = this._scene.getViewMatrix();
  55298. effect.setTexture("diffuseSampler", this._spriteTexture);
  55299. effect.setMatrix("view", viewMatrix);
  55300. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55301. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  55302. // Fog
  55303. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  55304. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  55305. effect.setColor3("vFogColor", this._scene.fogColor);
  55306. }
  55307. // VBOs
  55308. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55309. // Draw order
  55310. engine.setDepthFunctionToLessOrEqual();
  55311. effect.setBool("alphaTest", true);
  55312. engine.setColorWrite(false);
  55313. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  55314. engine.setColorWrite(true);
  55315. effect.setBool("alphaTest", false);
  55316. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55317. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  55318. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55319. };
  55320. SpriteManager.prototype.dispose = function () {
  55321. if (this._buffer) {
  55322. this._buffer.dispose();
  55323. this._buffer = null;
  55324. }
  55325. if (this._indexBuffer) {
  55326. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55327. this._indexBuffer = null;
  55328. }
  55329. if (this._spriteTexture) {
  55330. this._spriteTexture.dispose();
  55331. this._spriteTexture = null;
  55332. }
  55333. // Remove from scene
  55334. var index = this._scene.spriteManagers.indexOf(this);
  55335. this._scene.spriteManagers.splice(index, 1);
  55336. // Callback
  55337. this.onDisposeObservable.notifyObservers(this);
  55338. this.onDisposeObservable.clear();
  55339. };
  55340. return SpriteManager;
  55341. }());
  55342. BABYLON.SpriteManager = SpriteManager;
  55343. })(BABYLON || (BABYLON = {}));
  55344. //# sourceMappingURL=babylon.spriteManager.js.map
  55345. var BABYLON;
  55346. (function (BABYLON) {
  55347. var Sprite = /** @class */ (function () {
  55348. function Sprite(name, manager) {
  55349. this.name = name;
  55350. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55351. this.width = 1.0;
  55352. this.height = 1.0;
  55353. this.angle = 0;
  55354. this.cellIndex = 0;
  55355. this.invertU = 0;
  55356. this.invertV = 0;
  55357. this.animations = new Array();
  55358. this.isPickable = false;
  55359. this._animationStarted = false;
  55360. this._loopAnimation = false;
  55361. this._fromIndex = 0;
  55362. this._toIndex = 0;
  55363. this._delay = 0;
  55364. this._direction = 1;
  55365. this._time = 0;
  55366. /**
  55367. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  55368. */
  55369. this.isVisible = true;
  55370. this._manager = manager;
  55371. this._manager.sprites.push(this);
  55372. this.position = BABYLON.Vector3.Zero();
  55373. }
  55374. Object.defineProperty(Sprite.prototype, "size", {
  55375. get: function () {
  55376. return this.width;
  55377. },
  55378. set: function (value) {
  55379. this.width = value;
  55380. this.height = value;
  55381. },
  55382. enumerable: true,
  55383. configurable: true
  55384. });
  55385. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  55386. this._fromIndex = from;
  55387. this._toIndex = to;
  55388. this._loopAnimation = loop;
  55389. this._delay = delay;
  55390. this._animationStarted = true;
  55391. this._direction = from < to ? 1 : -1;
  55392. this.cellIndex = from;
  55393. this._time = 0;
  55394. this._onAnimationEnd = onAnimationEnd;
  55395. };
  55396. Sprite.prototype.stopAnimation = function () {
  55397. this._animationStarted = false;
  55398. };
  55399. /** @hidden */
  55400. Sprite.prototype._animate = function (deltaTime) {
  55401. if (!this._animationStarted)
  55402. return;
  55403. this._time += deltaTime;
  55404. if (this._time > this._delay) {
  55405. this._time = this._time % this._delay;
  55406. this.cellIndex += this._direction;
  55407. if (this.cellIndex > this._toIndex) {
  55408. if (this._loopAnimation) {
  55409. this.cellIndex = this._fromIndex;
  55410. }
  55411. else {
  55412. this.cellIndex = this._toIndex;
  55413. this._animationStarted = false;
  55414. if (this._onAnimationEnd) {
  55415. this._onAnimationEnd();
  55416. }
  55417. if (this.disposeWhenFinishedAnimating) {
  55418. this.dispose();
  55419. }
  55420. }
  55421. }
  55422. }
  55423. };
  55424. Sprite.prototype.dispose = function () {
  55425. for (var i = 0; i < this._manager.sprites.length; i++) {
  55426. if (this._manager.sprites[i] == this) {
  55427. this._manager.sprites.splice(i, 1);
  55428. }
  55429. }
  55430. };
  55431. return Sprite;
  55432. }());
  55433. BABYLON.Sprite = Sprite;
  55434. })(BABYLON || (BABYLON = {}));
  55435. //# sourceMappingURL=babylon.sprite.js.map
  55436. var BABYLON;
  55437. (function (BABYLON) {
  55438. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  55439. if (!BABYLON.PickingInfo) {
  55440. return null;
  55441. }
  55442. var pickingInfo = null;
  55443. if (!camera) {
  55444. if (!this.activeCamera) {
  55445. return null;
  55446. }
  55447. camera = this.activeCamera;
  55448. }
  55449. if (this.spriteManagers.length > 0) {
  55450. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  55451. var spriteManager = this.spriteManagers[spriteIndex];
  55452. if (!spriteManager.isPickable) {
  55453. continue;
  55454. }
  55455. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  55456. if (!result || !result.hit)
  55457. continue;
  55458. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  55459. continue;
  55460. pickingInfo = result;
  55461. if (fastCheck) {
  55462. break;
  55463. }
  55464. }
  55465. }
  55466. return pickingInfo || new BABYLON.PickingInfo();
  55467. };
  55468. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  55469. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  55470. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  55471. };
  55472. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  55473. if (!this._tempSpritePickingRay) {
  55474. return null;
  55475. }
  55476. if (!camera) {
  55477. if (!this.activeCamera) {
  55478. return null;
  55479. }
  55480. camera = this.activeCamera;
  55481. }
  55482. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  55483. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  55484. };
  55485. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  55486. if (this._pointerOverSprite === sprite) {
  55487. return;
  55488. }
  55489. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  55490. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  55491. }
  55492. this._pointerOverSprite = sprite;
  55493. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  55494. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  55495. }
  55496. };
  55497. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  55498. return this._pointerOverSprite;
  55499. };
  55500. /**
  55501. * Defines the sprite scene component responsible to manage sprites
  55502. * in a given scene.
  55503. */
  55504. var SpriteSceneComponent = /** @class */ (function () {
  55505. /**
  55506. * Creates a new instance of the component for the given scene
  55507. * @param scene Defines the scene to register the component in
  55508. */
  55509. function SpriteSceneComponent(scene) {
  55510. /**
  55511. * The component name helpfull to identify the component in the list of scene components.
  55512. */
  55513. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  55514. this.scene = scene;
  55515. this.scene.spriteManagers = new Array();
  55516. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  55517. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  55518. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  55519. this._spritePredicate = function (sprite) {
  55520. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  55521. };
  55522. }
  55523. /**
  55524. * Registers the component in a given scene
  55525. */
  55526. SpriteSceneComponent.prototype.register = function () {
  55527. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  55528. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  55529. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  55530. };
  55531. /**
  55532. * Rebuilds the elements related to this component in case of
  55533. * context lost for instance.
  55534. */
  55535. SpriteSceneComponent.prototype.rebuild = function () {
  55536. /** Nothing to do for sprites */
  55537. };
  55538. /**
  55539. * Disposes the component and the associated ressources.
  55540. */
  55541. SpriteSceneComponent.prototype.dispose = function () {
  55542. this.scene.onBeforeSpritesRenderingObservable.clear();
  55543. this.scene.onAfterSpritesRenderingObservable.clear();
  55544. var spriteManagers = this.scene.spriteManagers;
  55545. while (spriteManagers.length) {
  55546. spriteManagers[0].dispose();
  55547. }
  55548. };
  55549. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  55550. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  55551. if (result) {
  55552. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  55553. }
  55554. return result;
  55555. };
  55556. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  55557. var scene = this.scene;
  55558. if (isMeshPicked) {
  55559. scene.setPointerOverSprite(null);
  55560. }
  55561. else {
  55562. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  55563. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  55564. scene.setPointerOverSprite(pickResult.pickedSprite);
  55565. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  55566. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  55567. }
  55568. else {
  55569. canvas.style.cursor = scene.hoverCursor;
  55570. }
  55571. }
  55572. else {
  55573. scene.setPointerOverSprite(null);
  55574. }
  55575. }
  55576. return pickResult;
  55577. };
  55578. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  55579. var scene = this.scene;
  55580. scene._pickedDownSprite = null;
  55581. if (scene.spriteManagers.length > 0) {
  55582. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  55583. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  55584. if (pickResult.pickedSprite.actionManager) {
  55585. scene._pickedDownSprite = pickResult.pickedSprite;
  55586. switch (evt.button) {
  55587. case 0:
  55588. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55589. break;
  55590. case 1:
  55591. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55592. break;
  55593. case 2:
  55594. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55595. break;
  55596. }
  55597. if (pickResult.pickedSprite.actionManager) {
  55598. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55599. }
  55600. }
  55601. }
  55602. }
  55603. return pickResult;
  55604. };
  55605. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  55606. var scene = this.scene;
  55607. if (scene.spriteManagers.length > 0) {
  55608. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  55609. if (spritePickResult) {
  55610. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  55611. if (spritePickResult.pickedSprite.actionManager) {
  55612. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  55613. if (spritePickResult.pickedSprite.actionManager) {
  55614. if (!this.scene._isPointerSwiping()) {
  55615. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  55616. }
  55617. }
  55618. }
  55619. }
  55620. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  55621. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  55622. }
  55623. }
  55624. }
  55625. return pickResult;
  55626. };
  55627. return SpriteSceneComponent;
  55628. }());
  55629. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  55630. })(BABYLON || (BABYLON = {}));
  55631. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  55632. var BABYLON;
  55633. (function (BABYLON) {
  55634. /**
  55635. * @hidden
  55636. */
  55637. var IntersectionInfo = /** @class */ (function () {
  55638. function IntersectionInfo(bu, bv, distance) {
  55639. this.bu = bu;
  55640. this.bv = bv;
  55641. this.distance = distance;
  55642. this.faceId = 0;
  55643. this.subMeshId = 0;
  55644. }
  55645. return IntersectionInfo;
  55646. }());
  55647. BABYLON.IntersectionInfo = IntersectionInfo;
  55648. /**
  55649. * Information about the result of picking within a scene
  55650. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  55651. */
  55652. var PickingInfo = /** @class */ (function () {
  55653. function PickingInfo() {
  55654. /**
  55655. * If the pick collided with an object
  55656. */
  55657. this.hit = false;
  55658. /**
  55659. * Distance away where the pick collided
  55660. */
  55661. this.distance = 0;
  55662. /**
  55663. * The location of pick collision
  55664. */
  55665. this.pickedPoint = null;
  55666. /**
  55667. * The mesh corresponding the the pick collision
  55668. */
  55669. this.pickedMesh = null;
  55670. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  55671. this.bu = 0;
  55672. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  55673. this.bv = 0;
  55674. /** The id of the face on the mesh that was picked */
  55675. this.faceId = -1;
  55676. /** Id of the the submesh that was picked */
  55677. this.subMeshId = 0;
  55678. /** If a sprite was picked, this will be the sprite the pick collided with */
  55679. this.pickedSprite = null;
  55680. /**
  55681. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  55682. */
  55683. this.originMesh = null;
  55684. /**
  55685. * The ray that was used to perform the picking.
  55686. */
  55687. this.ray = null;
  55688. }
  55689. /**
  55690. * Gets the normal correspodning to the face the pick collided with
  55691. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  55692. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  55693. * @returns The normal correspodning to the face the pick collided with
  55694. */
  55695. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  55696. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  55697. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  55698. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  55699. return null;
  55700. }
  55701. var indices = this.pickedMesh.getIndices();
  55702. if (!indices) {
  55703. return null;
  55704. }
  55705. var result;
  55706. if (useVerticesNormals) {
  55707. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55708. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  55709. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  55710. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  55711. normal0 = normal0.scale(this.bu);
  55712. normal1 = normal1.scale(this.bv);
  55713. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  55714. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  55715. }
  55716. else {
  55717. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55718. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  55719. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  55720. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  55721. var p1p2 = vertex1.subtract(vertex2);
  55722. var p3p2 = vertex3.subtract(vertex2);
  55723. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  55724. }
  55725. if (useWorldCoordinates) {
  55726. var wm = this.pickedMesh.getWorldMatrix();
  55727. if (this.pickedMesh.nonUniformScaling) {
  55728. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  55729. wm = BABYLON.Tmp.Matrix[0];
  55730. wm.setTranslationFromFloats(0, 0, 0);
  55731. wm.invert();
  55732. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  55733. wm = BABYLON.Tmp.Matrix[1];
  55734. }
  55735. result = BABYLON.Vector3.TransformNormal(result, wm);
  55736. }
  55737. result.normalize();
  55738. return result;
  55739. };
  55740. /**
  55741. * Gets the texture coordinates of where the pick occured
  55742. * @returns the vector containing the coordnates of the texture
  55743. */
  55744. PickingInfo.prototype.getTextureCoordinates = function () {
  55745. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55746. return null;
  55747. }
  55748. var indices = this.pickedMesh.getIndices();
  55749. if (!indices) {
  55750. return null;
  55751. }
  55752. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55753. if (!uvs) {
  55754. return null;
  55755. }
  55756. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  55757. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  55758. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  55759. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  55760. uv1 = uv1.scale(this.bu);
  55761. uv2 = uv2.scale(this.bv);
  55762. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  55763. };
  55764. return PickingInfo;
  55765. }());
  55766. BABYLON.PickingInfo = PickingInfo;
  55767. })(BABYLON || (BABYLON = {}));
  55768. //# sourceMappingURL=babylon.pickingInfo.js.map
  55769. var BABYLON;
  55770. (function (BABYLON) {
  55771. var Ray = /** @class */ (function () {
  55772. function Ray(origin, direction, length) {
  55773. if (length === void 0) { length = Number.MAX_VALUE; }
  55774. this.origin = origin;
  55775. this.direction = direction;
  55776. this.length = length;
  55777. }
  55778. // Methods
  55779. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  55780. var d = 0.0;
  55781. var maxValue = Number.MAX_VALUE;
  55782. var inv;
  55783. var min;
  55784. var max;
  55785. var temp;
  55786. if (Math.abs(this.direction.x) < 0.0000001) {
  55787. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  55788. return false;
  55789. }
  55790. }
  55791. else {
  55792. inv = 1.0 / this.direction.x;
  55793. min = (minimum.x - this.origin.x) * inv;
  55794. max = (maximum.x - this.origin.x) * inv;
  55795. if (max === -Infinity) {
  55796. max = Infinity;
  55797. }
  55798. if (min > max) {
  55799. temp = min;
  55800. min = max;
  55801. max = temp;
  55802. }
  55803. d = Math.max(min, d);
  55804. maxValue = Math.min(max, maxValue);
  55805. if (d > maxValue) {
  55806. return false;
  55807. }
  55808. }
  55809. if (Math.abs(this.direction.y) < 0.0000001) {
  55810. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  55811. return false;
  55812. }
  55813. }
  55814. else {
  55815. inv = 1.0 / this.direction.y;
  55816. min = (minimum.y - this.origin.y) * inv;
  55817. max = (maximum.y - this.origin.y) * inv;
  55818. if (max === -Infinity) {
  55819. max = Infinity;
  55820. }
  55821. if (min > max) {
  55822. temp = min;
  55823. min = max;
  55824. max = temp;
  55825. }
  55826. d = Math.max(min, d);
  55827. maxValue = Math.min(max, maxValue);
  55828. if (d > maxValue) {
  55829. return false;
  55830. }
  55831. }
  55832. if (Math.abs(this.direction.z) < 0.0000001) {
  55833. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  55834. return false;
  55835. }
  55836. }
  55837. else {
  55838. inv = 1.0 / this.direction.z;
  55839. min = (minimum.z - this.origin.z) * inv;
  55840. max = (maximum.z - this.origin.z) * inv;
  55841. if (max === -Infinity) {
  55842. max = Infinity;
  55843. }
  55844. if (min > max) {
  55845. temp = min;
  55846. min = max;
  55847. max = temp;
  55848. }
  55849. d = Math.max(min, d);
  55850. maxValue = Math.min(max, maxValue);
  55851. if (d > maxValue) {
  55852. return false;
  55853. }
  55854. }
  55855. return true;
  55856. };
  55857. Ray.prototype.intersectsBox = function (box) {
  55858. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  55859. };
  55860. Ray.prototype.intersectsSphere = function (sphere) {
  55861. var x = sphere.center.x - this.origin.x;
  55862. var y = sphere.center.y - this.origin.y;
  55863. var z = sphere.center.z - this.origin.z;
  55864. var pyth = (x * x) + (y * y) + (z * z);
  55865. var rr = sphere.radius * sphere.radius;
  55866. if (pyth <= rr) {
  55867. return true;
  55868. }
  55869. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  55870. if (dot < 0.0) {
  55871. return false;
  55872. }
  55873. var temp = pyth - (dot * dot);
  55874. return temp <= rr;
  55875. };
  55876. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55877. if (!this._edge1) {
  55878. this._edge1 = BABYLON.Vector3.Zero();
  55879. this._edge2 = BABYLON.Vector3.Zero();
  55880. this._pvec = BABYLON.Vector3.Zero();
  55881. this._tvec = BABYLON.Vector3.Zero();
  55882. this._qvec = BABYLON.Vector3.Zero();
  55883. }
  55884. vertex1.subtractToRef(vertex0, this._edge1);
  55885. vertex2.subtractToRef(vertex0, this._edge2);
  55886. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55887. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55888. if (det === 0) {
  55889. return null;
  55890. }
  55891. var invdet = 1 / det;
  55892. this.origin.subtractToRef(vertex0, this._tvec);
  55893. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55894. if (bu < 0 || bu > 1.0) {
  55895. return null;
  55896. }
  55897. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55898. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55899. if (bv < 0 || bu + bv > 1.0) {
  55900. return null;
  55901. }
  55902. //check if the distance is longer than the predefined length.
  55903. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55904. if (distance > this.length) {
  55905. return null;
  55906. }
  55907. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55908. };
  55909. Ray.prototype.intersectsPlane = function (plane) {
  55910. var distance;
  55911. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55912. if (Math.abs(result1) < 9.99999997475243E-07) {
  55913. return null;
  55914. }
  55915. else {
  55916. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55917. distance = (-plane.d - result2) / result1;
  55918. if (distance < 0.0) {
  55919. if (distance < -9.99999997475243E-07) {
  55920. return null;
  55921. }
  55922. else {
  55923. return 0;
  55924. }
  55925. }
  55926. return distance;
  55927. }
  55928. };
  55929. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55930. var tm = BABYLON.Tmp.Matrix[0];
  55931. mesh.getWorldMatrix().invertToRef(tm);
  55932. if (this._tmpRay) {
  55933. Ray.TransformToRef(this, tm, this._tmpRay);
  55934. }
  55935. else {
  55936. this._tmpRay = Ray.Transform(this, tm);
  55937. }
  55938. return mesh.intersects(this._tmpRay, fastCheck);
  55939. };
  55940. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55941. if (results) {
  55942. results.length = 0;
  55943. }
  55944. else {
  55945. results = [];
  55946. }
  55947. for (var i = 0; i < meshes.length; i++) {
  55948. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55949. if (pickInfo.hit) {
  55950. results.push(pickInfo);
  55951. }
  55952. }
  55953. results.sort(this._comparePickingInfo);
  55954. return results;
  55955. };
  55956. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55957. if (pickingInfoA.distance < pickingInfoB.distance) {
  55958. return -1;
  55959. }
  55960. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55961. return 1;
  55962. }
  55963. else {
  55964. return 0;
  55965. }
  55966. };
  55967. /**
  55968. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55969. * @param sega the first point of the segment to test the intersection against
  55970. * @param segb the second point of the segment to test the intersection against
  55971. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55972. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55973. */
  55974. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55975. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55976. var u = segb.subtract(sega);
  55977. var v = rsegb.subtract(this.origin);
  55978. var w = sega.subtract(this.origin);
  55979. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55980. var b = BABYLON.Vector3.Dot(u, v);
  55981. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55982. var d = BABYLON.Vector3.Dot(u, w);
  55983. var e = BABYLON.Vector3.Dot(v, w);
  55984. var D = a * c - b * b; // always >= 0
  55985. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55986. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55987. // compute the line parameters of the two closest points
  55988. if (D < Ray.smallnum) { // the lines are almost parallel
  55989. sN = 0.0; // force using point P0 on segment S1
  55990. sD = 1.0; // to prevent possible division by 0.0 later
  55991. tN = e;
  55992. tD = c;
  55993. }
  55994. else { // get the closest points on the infinite lines
  55995. sN = (b * e - c * d);
  55996. tN = (a * e - b * d);
  55997. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55998. sN = 0.0;
  55999. tN = e;
  56000. tD = c;
  56001. }
  56002. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  56003. sN = sD;
  56004. tN = e + b;
  56005. tD = c;
  56006. }
  56007. }
  56008. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  56009. tN = 0.0;
  56010. // recompute sc for this edge
  56011. if (-d < 0.0) {
  56012. sN = 0.0;
  56013. }
  56014. else if (-d > a)
  56015. sN = sD;
  56016. else {
  56017. sN = -d;
  56018. sD = a;
  56019. }
  56020. }
  56021. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  56022. tN = tD;
  56023. // recompute sc for this edge
  56024. if ((-d + b) < 0.0) {
  56025. sN = 0;
  56026. }
  56027. else if ((-d + b) > a) {
  56028. sN = sD;
  56029. }
  56030. else {
  56031. sN = (-d + b);
  56032. sD = a;
  56033. }
  56034. }
  56035. // finally do the division to get sc and tc
  56036. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  56037. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  56038. // get the difference of the two closest points
  56039. var qtc = v.multiplyByFloats(tc, tc, tc);
  56040. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  56041. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  56042. if (isIntersected) {
  56043. return qtc.length();
  56044. }
  56045. return -1;
  56046. };
  56047. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  56048. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  56049. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  56050. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  56051. this.direction.normalize();
  56052. return this;
  56053. };
  56054. // Statics
  56055. Ray.Zero = function () {
  56056. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  56057. };
  56058. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  56059. var result = Ray.Zero();
  56060. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  56061. };
  56062. /**
  56063. * 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
  56064. * transformed to the given world matrix.
  56065. * @param origin The origin point
  56066. * @param end The end point
  56067. * @param world a matrix to transform the ray to. Default is the identity matrix.
  56068. */
  56069. Ray.CreateNewFromTo = function (origin, end, world) {
  56070. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  56071. var direction = end.subtract(origin);
  56072. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  56073. direction.normalize();
  56074. return Ray.Transform(new Ray(origin, direction, length), world);
  56075. };
  56076. Ray.Transform = function (ray, matrix) {
  56077. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  56078. Ray.TransformToRef(ray, matrix, result);
  56079. return result;
  56080. };
  56081. Ray.TransformToRef = function (ray, matrix, result) {
  56082. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  56083. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  56084. result.length = ray.length;
  56085. var dir = result.direction;
  56086. var len = dir.length();
  56087. if (!(len === 0 || len === 1)) {
  56088. var num = 1.0 / len;
  56089. dir.x *= num;
  56090. dir.y *= num;
  56091. dir.z *= num;
  56092. result.length *= len;
  56093. }
  56094. };
  56095. Ray.smallnum = 0.00000001;
  56096. Ray.rayl = 10e8;
  56097. return Ray;
  56098. }());
  56099. BABYLON.Ray = Ray;
  56100. })(BABYLON || (BABYLON = {}));
  56101. //# sourceMappingURL=babylon.ray.js.map
  56102. var BABYLON;
  56103. (function (BABYLON) {
  56104. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  56105. if (boxMin.x > sphereCenter.x + sphereRadius)
  56106. return false;
  56107. if (sphereCenter.x - sphereRadius > boxMax.x)
  56108. return false;
  56109. if (boxMin.y > sphereCenter.y + sphereRadius)
  56110. return false;
  56111. if (sphereCenter.y - sphereRadius > boxMax.y)
  56112. return false;
  56113. if (boxMin.z > sphereCenter.z + sphereRadius)
  56114. return false;
  56115. if (sphereCenter.z - sphereRadius > boxMax.z)
  56116. return false;
  56117. return true;
  56118. };
  56119. var getLowestRoot = (function () {
  56120. var result = { root: 0, found: false };
  56121. return function (a, b, c, maxR) {
  56122. result.root = 0;
  56123. result.found = false;
  56124. var determinant = b * b - 4.0 * a * c;
  56125. if (determinant < 0)
  56126. return result;
  56127. var sqrtD = Math.sqrt(determinant);
  56128. var r1 = (-b - sqrtD) / (2.0 * a);
  56129. var r2 = (-b + sqrtD) / (2.0 * a);
  56130. if (r1 > r2) {
  56131. var temp = r2;
  56132. r2 = r1;
  56133. r1 = temp;
  56134. }
  56135. if (r1 > 0 && r1 < maxR) {
  56136. result.root = r1;
  56137. result.found = true;
  56138. return result;
  56139. }
  56140. if (r2 > 0 && r2 < maxR) {
  56141. result.root = r2;
  56142. result.found = true;
  56143. return result;
  56144. }
  56145. return result;
  56146. };
  56147. })();
  56148. /** @hidden */
  56149. var Collider = /** @class */ (function () {
  56150. function Collider() {
  56151. this._collisionPoint = BABYLON.Vector3.Zero();
  56152. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  56153. this._tempVector = BABYLON.Vector3.Zero();
  56154. this._tempVector2 = BABYLON.Vector3.Zero();
  56155. this._tempVector3 = BABYLON.Vector3.Zero();
  56156. this._tempVector4 = BABYLON.Vector3.Zero();
  56157. this._edge = BABYLON.Vector3.Zero();
  56158. this._baseToVertex = BABYLON.Vector3.Zero();
  56159. this._destinationPoint = BABYLON.Vector3.Zero();
  56160. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  56161. this._displacementVector = BABYLON.Vector3.Zero();
  56162. /** @hidden */
  56163. this._radius = BABYLON.Vector3.One();
  56164. /** @hidden */
  56165. this._retry = 0;
  56166. /** @hidden */
  56167. this._basePointWorld = BABYLON.Vector3.Zero();
  56168. this._velocityWorld = BABYLON.Vector3.Zero();
  56169. this._normalizedVelocity = BABYLON.Vector3.Zero();
  56170. this._collisionMask = -1;
  56171. }
  56172. Object.defineProperty(Collider.prototype, "collisionMask", {
  56173. get: function () {
  56174. return this._collisionMask;
  56175. },
  56176. set: function (mask) {
  56177. this._collisionMask = !isNaN(mask) ? mask : -1;
  56178. },
  56179. enumerable: true,
  56180. configurable: true
  56181. });
  56182. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  56183. /**
  56184. * Gets the plane normal used to compute the sliding response (in local space)
  56185. */
  56186. get: function () {
  56187. return this._slidePlaneNormal;
  56188. },
  56189. enumerable: true,
  56190. configurable: true
  56191. });
  56192. // Methods
  56193. /** @hidden */
  56194. Collider.prototype._initialize = function (source, dir, e) {
  56195. this._velocity = dir;
  56196. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  56197. this._basePoint = source;
  56198. source.multiplyToRef(this._radius, this._basePointWorld);
  56199. dir.multiplyToRef(this._radius, this._velocityWorld);
  56200. this._velocityWorldLength = this._velocityWorld.length();
  56201. this._epsilon = e;
  56202. this.collisionFound = false;
  56203. };
  56204. /** @hidden */
  56205. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  56206. pa.subtractToRef(point, this._tempVector);
  56207. pb.subtractToRef(point, this._tempVector2);
  56208. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  56209. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56210. if (d < 0)
  56211. return false;
  56212. pc.subtractToRef(point, this._tempVector3);
  56213. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  56214. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56215. if (d < 0)
  56216. return false;
  56217. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  56218. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56219. return d >= 0;
  56220. };
  56221. /** @hidden */
  56222. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  56223. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  56224. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  56225. if (distance > this._velocityWorldLength + max + sphereRadius) {
  56226. return false;
  56227. }
  56228. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  56229. return false;
  56230. return true;
  56231. };
  56232. /** @hidden */
  56233. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  56234. var t0;
  56235. var embeddedInPlane = false;
  56236. //defensive programming, actually not needed.
  56237. if (!trianglePlaneArray) {
  56238. trianglePlaneArray = [];
  56239. }
  56240. if (!trianglePlaneArray[faceIndex]) {
  56241. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  56242. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  56243. }
  56244. var trianglePlane = trianglePlaneArray[faceIndex];
  56245. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  56246. return;
  56247. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  56248. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  56249. if (normalDotVelocity == 0) {
  56250. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  56251. return;
  56252. embeddedInPlane = true;
  56253. t0 = 0;
  56254. }
  56255. else {
  56256. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  56257. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  56258. if (t0 > t1) {
  56259. var temp = t1;
  56260. t1 = t0;
  56261. t0 = temp;
  56262. }
  56263. if (t0 > 1.0 || t1 < 0.0)
  56264. return;
  56265. if (t0 < 0)
  56266. t0 = 0;
  56267. if (t0 > 1.0)
  56268. t0 = 1.0;
  56269. }
  56270. this._collisionPoint.copyFromFloats(0, 0, 0);
  56271. var found = false;
  56272. var t = 1.0;
  56273. if (!embeddedInPlane) {
  56274. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  56275. this._velocity.scaleToRef(t0, this._tempVector);
  56276. this._planeIntersectionPoint.addInPlace(this._tempVector);
  56277. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  56278. found = true;
  56279. t = t0;
  56280. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  56281. }
  56282. }
  56283. if (!found) {
  56284. var velocitySquaredLength = this._velocity.lengthSquared();
  56285. var a = velocitySquaredLength;
  56286. this._basePoint.subtractToRef(p1, this._tempVector);
  56287. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56288. var c = this._tempVector.lengthSquared() - 1.0;
  56289. var lowestRoot = getLowestRoot(a, b, c, t);
  56290. if (lowestRoot.found) {
  56291. t = lowestRoot.root;
  56292. found = true;
  56293. this._collisionPoint.copyFrom(p1);
  56294. }
  56295. this._basePoint.subtractToRef(p2, this._tempVector);
  56296. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56297. c = this._tempVector.lengthSquared() - 1.0;
  56298. lowestRoot = getLowestRoot(a, b, c, t);
  56299. if (lowestRoot.found) {
  56300. t = lowestRoot.root;
  56301. found = true;
  56302. this._collisionPoint.copyFrom(p2);
  56303. }
  56304. this._basePoint.subtractToRef(p3, this._tempVector);
  56305. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56306. c = this._tempVector.lengthSquared() - 1.0;
  56307. lowestRoot = getLowestRoot(a, b, c, t);
  56308. if (lowestRoot.found) {
  56309. t = lowestRoot.root;
  56310. found = true;
  56311. this._collisionPoint.copyFrom(p3);
  56312. }
  56313. p2.subtractToRef(p1, this._edge);
  56314. p1.subtractToRef(this._basePoint, this._baseToVertex);
  56315. var edgeSquaredLength = this._edge.lengthSquared();
  56316. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56317. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56318. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56319. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56320. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56321. lowestRoot = getLowestRoot(a, b, c, t);
  56322. if (lowestRoot.found) {
  56323. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56324. if (f >= 0.0 && f <= 1.0) {
  56325. t = lowestRoot.root;
  56326. found = true;
  56327. this._edge.scaleInPlace(f);
  56328. p1.addToRef(this._edge, this._collisionPoint);
  56329. }
  56330. }
  56331. p3.subtractToRef(p2, this._edge);
  56332. p2.subtractToRef(this._basePoint, this._baseToVertex);
  56333. edgeSquaredLength = this._edge.lengthSquared();
  56334. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56335. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56336. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56337. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56338. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56339. lowestRoot = getLowestRoot(a, b, c, t);
  56340. if (lowestRoot.found) {
  56341. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56342. if (f >= 0.0 && f <= 1.0) {
  56343. t = lowestRoot.root;
  56344. found = true;
  56345. this._edge.scaleInPlace(f);
  56346. p2.addToRef(this._edge, this._collisionPoint);
  56347. }
  56348. }
  56349. p1.subtractToRef(p3, this._edge);
  56350. p3.subtractToRef(this._basePoint, this._baseToVertex);
  56351. edgeSquaredLength = this._edge.lengthSquared();
  56352. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56353. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56354. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56355. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56356. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56357. lowestRoot = getLowestRoot(a, b, c, t);
  56358. if (lowestRoot.found) {
  56359. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56360. if (f >= 0.0 && f <= 1.0) {
  56361. t = lowestRoot.root;
  56362. found = true;
  56363. this._edge.scaleInPlace(f);
  56364. p3.addToRef(this._edge, this._collisionPoint);
  56365. }
  56366. }
  56367. }
  56368. if (found) {
  56369. var distToCollision = t * this._velocity.length();
  56370. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  56371. if (!this.intersectionPoint) {
  56372. this.intersectionPoint = this._collisionPoint.clone();
  56373. }
  56374. else {
  56375. this.intersectionPoint.copyFrom(this._collisionPoint);
  56376. }
  56377. this._nearestDistance = distToCollision;
  56378. this.collisionFound = true;
  56379. }
  56380. }
  56381. };
  56382. /** @hidden */
  56383. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  56384. for (var i = indexStart; i < indexEnd; i += 3) {
  56385. var p1 = pts[indices[i] - decal];
  56386. var p2 = pts[indices[i + 1] - decal];
  56387. var p3 = pts[indices[i + 2] - decal];
  56388. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  56389. }
  56390. };
  56391. /** @hidden */
  56392. Collider.prototype._getResponse = function (pos, vel) {
  56393. pos.addToRef(vel, this._destinationPoint);
  56394. vel.scaleInPlace((this._nearestDistance / vel.length()));
  56395. this._basePoint.addToRef(vel, pos);
  56396. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  56397. this._slidePlaneNormal.normalize();
  56398. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  56399. pos.addInPlace(this._displacementVector);
  56400. this.intersectionPoint.addInPlace(this._displacementVector);
  56401. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  56402. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  56403. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  56404. };
  56405. return Collider;
  56406. }());
  56407. BABYLON.Collider = Collider;
  56408. })(BABYLON || (BABYLON = {}));
  56409. //# sourceMappingURL=babylon.collider.js.map
  56410. var BABYLON;
  56411. (function (BABYLON) {
  56412. //WebWorker code will be inserted to this variable.
  56413. /** @hidden */
  56414. BABYLON.CollisionWorker = "";
  56415. /** Defines supported task for worker process */
  56416. var WorkerTaskType;
  56417. (function (WorkerTaskType) {
  56418. /** Initialization */
  56419. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  56420. /** Update of geometry */
  56421. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  56422. /** Evaluate collision */
  56423. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  56424. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  56425. /** Defines kind of replies returned by worker */
  56426. var WorkerReplyType;
  56427. (function (WorkerReplyType) {
  56428. /** Success */
  56429. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  56430. /** Unkown error */
  56431. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  56432. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  56433. /** @hidden */
  56434. var CollisionCoordinatorWorker = /** @class */ (function () {
  56435. function CollisionCoordinatorWorker() {
  56436. var _this = this;
  56437. this._scaledPosition = BABYLON.Vector3.Zero();
  56438. this._scaledVelocity = BABYLON.Vector3.Zero();
  56439. this.onMeshUpdated = function (transformNode) {
  56440. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  56441. };
  56442. this.onGeometryUpdated = function (geometry) {
  56443. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  56444. };
  56445. this._afterRender = function () {
  56446. if (!_this._init)
  56447. return;
  56448. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  56449. return;
  56450. }
  56451. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  56452. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  56453. if (_this._runningUpdated > 4) {
  56454. return;
  56455. }
  56456. ++_this._runningUpdated;
  56457. var payload = {
  56458. updatedMeshes: _this._addUpdateMeshesList,
  56459. updatedGeometries: _this._addUpdateGeometriesList,
  56460. removedGeometries: _this._toRemoveGeometryArray,
  56461. removedMeshes: _this._toRemoveMeshesArray
  56462. };
  56463. var message = {
  56464. payload: payload,
  56465. taskType: WorkerTaskType.UPDATE
  56466. };
  56467. var serializable = [];
  56468. for (var id in payload.updatedGeometries) {
  56469. if (payload.updatedGeometries.hasOwnProperty(id)) {
  56470. //prepare transferables
  56471. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  56472. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  56473. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  56474. }
  56475. }
  56476. _this._worker.postMessage(message, serializable);
  56477. _this._addUpdateMeshesList = {};
  56478. _this._addUpdateGeometriesList = {};
  56479. _this._toRemoveGeometryArray = [];
  56480. _this._toRemoveMeshesArray = [];
  56481. };
  56482. this._onMessageFromWorker = function (e) {
  56483. var returnData = e.data;
  56484. if (returnData.error != WorkerReplyType.SUCCESS) {
  56485. //TODO what errors can be returned from the worker?
  56486. BABYLON.Tools.Warn("error returned from worker!");
  56487. return;
  56488. }
  56489. switch (returnData.taskType) {
  56490. case WorkerTaskType.INIT:
  56491. _this._init = true;
  56492. //Update the worked with ALL of the scene's current state
  56493. _this._scene.meshes.forEach(function (mesh) {
  56494. _this.onMeshAdded(mesh);
  56495. });
  56496. _this._scene.getGeometries().forEach(function (geometry) {
  56497. _this.onGeometryAdded(geometry);
  56498. });
  56499. break;
  56500. case WorkerTaskType.UPDATE:
  56501. _this._runningUpdated--;
  56502. break;
  56503. case WorkerTaskType.COLLIDE:
  56504. var returnPayload = returnData.payload;
  56505. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  56506. return;
  56507. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  56508. if (callback) {
  56509. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  56510. if (mesh) {
  56511. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  56512. }
  56513. }
  56514. //cleanup
  56515. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  56516. break;
  56517. }
  56518. };
  56519. this._collisionsCallbackArray = [];
  56520. this._init = false;
  56521. this._runningUpdated = 0;
  56522. this._addUpdateMeshesList = {};
  56523. this._addUpdateGeometriesList = {};
  56524. this._toRemoveGeometryArray = [];
  56525. this._toRemoveMeshesArray = [];
  56526. }
  56527. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56528. if (!this._init)
  56529. return;
  56530. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  56531. return;
  56532. position.divideToRef(collider._radius, this._scaledPosition);
  56533. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56534. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  56535. var payload = {
  56536. collider: {
  56537. position: this._scaledPosition.asArray(),
  56538. velocity: this._scaledVelocity.asArray(),
  56539. radius: collider._radius.asArray()
  56540. },
  56541. collisionId: collisionIndex,
  56542. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  56543. maximumRetry: maximumRetry
  56544. };
  56545. var message = {
  56546. payload: payload,
  56547. taskType: WorkerTaskType.COLLIDE
  56548. };
  56549. this._worker.postMessage(message);
  56550. };
  56551. CollisionCoordinatorWorker.prototype.init = function (scene) {
  56552. this._scene = scene;
  56553. this._scene.registerAfterRender(this._afterRender);
  56554. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  56555. this._worker = new Worker(workerUrl);
  56556. this._worker.onmessage = this._onMessageFromWorker;
  56557. var message = {
  56558. payload: {},
  56559. taskType: WorkerTaskType.INIT
  56560. };
  56561. this._worker.postMessage(message);
  56562. };
  56563. CollisionCoordinatorWorker.prototype.destroy = function () {
  56564. this._scene.unregisterAfterRender(this._afterRender);
  56565. this._worker.terminate();
  56566. };
  56567. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  56568. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  56569. this.onMeshUpdated(mesh);
  56570. };
  56571. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  56572. this._toRemoveMeshesArray.push(mesh.uniqueId);
  56573. };
  56574. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  56575. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  56576. geometry.onGeometryUpdated = this.onGeometryUpdated;
  56577. this.onGeometryUpdated(geometry);
  56578. };
  56579. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  56580. this._toRemoveGeometryArray.push(geometry.id);
  56581. };
  56582. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  56583. var submeshes = [];
  56584. if (mesh.subMeshes) {
  56585. submeshes = mesh.subMeshes.map(function (sm, idx) {
  56586. var boundingInfo = sm.getBoundingInfo();
  56587. return {
  56588. position: idx,
  56589. verticesStart: sm.verticesStart,
  56590. verticesCount: sm.verticesCount,
  56591. indexStart: sm.indexStart,
  56592. indexCount: sm.indexCount,
  56593. hasMaterial: !!sm.getMaterial(),
  56594. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56595. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56596. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56597. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  56598. };
  56599. });
  56600. }
  56601. var geometryId = null;
  56602. if (mesh instanceof BABYLON.Mesh) {
  56603. var geometry = mesh.geometry;
  56604. geometryId = geometry ? geometry.id : null;
  56605. }
  56606. else if (mesh instanceof BABYLON.InstancedMesh) {
  56607. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  56608. geometryId = geometry ? geometry.id : null;
  56609. }
  56610. var boundingInfo = mesh.getBoundingInfo();
  56611. return {
  56612. uniqueId: mesh.uniqueId,
  56613. id: mesh.id,
  56614. name: mesh.name,
  56615. geometryId: geometryId,
  56616. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56617. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56618. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56619. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  56620. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  56621. subMeshes: submeshes,
  56622. checkCollisions: mesh.checkCollisions
  56623. };
  56624. };
  56625. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  56626. return {
  56627. id: geometry.id,
  56628. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  56629. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  56630. indices: new Uint32Array(geometry.getIndices() || []),
  56631. };
  56632. };
  56633. return CollisionCoordinatorWorker;
  56634. }());
  56635. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  56636. /** @hidden */
  56637. var CollisionCoordinatorLegacy = /** @class */ (function () {
  56638. function CollisionCoordinatorLegacy() {
  56639. this._scaledPosition = BABYLON.Vector3.Zero();
  56640. this._scaledVelocity = BABYLON.Vector3.Zero();
  56641. this._finalPosition = BABYLON.Vector3.Zero();
  56642. }
  56643. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56644. position.divideToRef(collider._radius, this._scaledPosition);
  56645. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56646. collider.collidedMesh = null;
  56647. collider._retry = 0;
  56648. collider._initialVelocity = this._scaledVelocity;
  56649. collider._initialPosition = this._scaledPosition;
  56650. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  56651. this._finalPosition.multiplyInPlace(collider._radius);
  56652. //run the callback
  56653. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  56654. };
  56655. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  56656. this._scene = scene;
  56657. };
  56658. CollisionCoordinatorLegacy.prototype.destroy = function () {
  56659. //Legacy need no destruction method.
  56660. };
  56661. //No update in legacy mode
  56662. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  56663. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  56664. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  56665. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  56666. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  56667. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  56668. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  56669. if (excludedMesh === void 0) { excludedMesh = null; }
  56670. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  56671. if (collider._retry >= maximumRetry) {
  56672. finalPosition.copyFrom(position);
  56673. return;
  56674. }
  56675. // Check if this is a mesh else camera or -1
  56676. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  56677. collider._initialize(position, velocity, closeDistance);
  56678. // Check all meshes
  56679. for (var index = 0; index < this._scene.meshes.length; index++) {
  56680. var mesh = this._scene.meshes[index];
  56681. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  56682. mesh._checkCollision(collider);
  56683. }
  56684. }
  56685. if (!collider.collisionFound) {
  56686. position.addToRef(velocity, finalPosition);
  56687. return;
  56688. }
  56689. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  56690. collider._getResponse(position, velocity);
  56691. }
  56692. if (velocity.length() <= closeDistance) {
  56693. finalPosition.copyFrom(position);
  56694. return;
  56695. }
  56696. collider._retry++;
  56697. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  56698. };
  56699. return CollisionCoordinatorLegacy;
  56700. }());
  56701. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  56702. })(BABYLON || (BABYLON = {}));
  56703. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  56704. var BABYLON;
  56705. (function (BABYLON) {
  56706. /**
  56707. * A particle represents one of the element emitted by a particle system.
  56708. * This is mainly define by its coordinates, direction, velocity and age.
  56709. */
  56710. var Particle = /** @class */ (function () {
  56711. /**
  56712. * Creates a new instance Particle
  56713. * @param particleSystem the particle system the particle belongs to
  56714. */
  56715. function Particle(
  56716. /**
  56717. * The particle system the particle belongs to.
  56718. */
  56719. particleSystem) {
  56720. this.particleSystem = particleSystem;
  56721. /**
  56722. * The world position of the particle in the scene.
  56723. */
  56724. this.position = BABYLON.Vector3.Zero();
  56725. /**
  56726. * The world direction of the particle in the scene.
  56727. */
  56728. this.direction = BABYLON.Vector3.Zero();
  56729. /**
  56730. * The color of the particle.
  56731. */
  56732. this.color = new BABYLON.Color4(0, 0, 0, 0);
  56733. /**
  56734. * The color change of the particle per step.
  56735. */
  56736. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  56737. /**
  56738. * Defines how long will the life of the particle be.
  56739. */
  56740. this.lifeTime = 1.0;
  56741. /**
  56742. * The current age of the particle.
  56743. */
  56744. this.age = 0;
  56745. /**
  56746. * The current size of the particle.
  56747. */
  56748. this.size = 0;
  56749. /**
  56750. * The current scale of the particle.
  56751. */
  56752. this.scale = new BABYLON.Vector2(1, 1);
  56753. /**
  56754. * The current angle of the particle.
  56755. */
  56756. this.angle = 0;
  56757. /**
  56758. * Defines how fast is the angle changing.
  56759. */
  56760. this.angularSpeed = 0;
  56761. /**
  56762. * Defines the cell index used by the particle to be rendered from a sprite.
  56763. */
  56764. this.cellIndex = 0;
  56765. /** @hidden */
  56766. this._attachedSubEmitters = null;
  56767. /** @hidden */
  56768. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  56769. /** @hidden */
  56770. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  56771. /** @hidden */
  56772. this._currentSize1 = 0;
  56773. /** @hidden */
  56774. this._currentSize2 = 0;
  56775. /** @hidden */
  56776. this._currentAngularSpeed1 = 0;
  56777. /** @hidden */
  56778. this._currentAngularSpeed2 = 0;
  56779. /** @hidden */
  56780. this._currentVelocity1 = 0;
  56781. /** @hidden */
  56782. this._currentVelocity2 = 0;
  56783. /** @hidden */
  56784. this._currentLimitVelocity1 = 0;
  56785. /** @hidden */
  56786. this._currentLimitVelocity2 = 0;
  56787. /** @hidden */
  56788. this._currentDrag1 = 0;
  56789. /** @hidden */
  56790. this._currentDrag2 = 0;
  56791. this.id = Particle._Count++;
  56792. if (!this.particleSystem.isAnimationSheetEnabled) {
  56793. return;
  56794. }
  56795. this.updateCellInfoFromSystem();
  56796. }
  56797. Particle.prototype.updateCellInfoFromSystem = function () {
  56798. this.cellIndex = this.particleSystem.startSpriteCellID;
  56799. };
  56800. /**
  56801. * Defines how the sprite cell index is updated for the particle
  56802. */
  56803. Particle.prototype.updateCellIndex = function () {
  56804. var offsetAge = this.age;
  56805. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  56806. if (this.particleSystem.spriteRandomStartCell) {
  56807. if (this._randomCellOffset === undefined) {
  56808. this._randomCellOffset = Math.random() * this.lifeTime;
  56809. }
  56810. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  56811. changeSpeed = 1;
  56812. offsetAge = this._randomCellOffset;
  56813. }
  56814. else {
  56815. offsetAge += this._randomCellOffset;
  56816. }
  56817. }
  56818. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  56819. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  56820. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  56821. };
  56822. /** @hidden */
  56823. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  56824. if (subEmitter.particleSystem.emitter.position) {
  56825. var emitterMesh = subEmitter.particleSystem.emitter;
  56826. emitterMesh.position.copyFrom(this.position);
  56827. if (subEmitter.inheritDirection) {
  56828. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  56829. // Look at using Y as forward
  56830. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  56831. }
  56832. }
  56833. else {
  56834. var emitterPosition = subEmitter.particleSystem.emitter;
  56835. emitterPosition.copyFrom(this.position);
  56836. }
  56837. // Set inheritedVelocityOffset to be used when new particles are created
  56838. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  56839. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  56840. };
  56841. /** @hidden */
  56842. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  56843. var _this = this;
  56844. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  56845. this._attachedSubEmitters.forEach(function (subEmitter) {
  56846. _this._inheritParticleInfoToSubEmitter(subEmitter);
  56847. });
  56848. }
  56849. };
  56850. /** @hidden */
  56851. Particle.prototype._reset = function () {
  56852. this.age = 0;
  56853. this._currentColorGradient = null;
  56854. this._currentSizeGradient = null;
  56855. this._currentAngularSpeedGradient = null;
  56856. this._currentVelocityGradient = null;
  56857. this._currentLimitVelocityGradient = null;
  56858. this._currentDragGradient = null;
  56859. this.cellIndex = this.particleSystem.startSpriteCellID;
  56860. this._randomCellOffset = undefined;
  56861. };
  56862. /**
  56863. * Copy the properties of particle to another one.
  56864. * @param other the particle to copy the information to.
  56865. */
  56866. Particle.prototype.copyTo = function (other) {
  56867. other.position.copyFrom(this.position);
  56868. if (this._initialDirection) {
  56869. if (other._initialDirection) {
  56870. other._initialDirection.copyFrom(this._initialDirection);
  56871. }
  56872. else {
  56873. other._initialDirection = this._initialDirection.clone();
  56874. }
  56875. }
  56876. else {
  56877. other._initialDirection = null;
  56878. }
  56879. other.direction.copyFrom(this.direction);
  56880. other.color.copyFrom(this.color);
  56881. other.colorStep.copyFrom(this.colorStep);
  56882. other.lifeTime = this.lifeTime;
  56883. other.age = this.age;
  56884. other._randomCellOffset = this._randomCellOffset;
  56885. other.size = this.size;
  56886. other.scale.copyFrom(this.scale);
  56887. other.angle = this.angle;
  56888. other.angularSpeed = this.angularSpeed;
  56889. other.particleSystem = this.particleSystem;
  56890. other.cellIndex = this.cellIndex;
  56891. other.id = this.id;
  56892. other._attachedSubEmitters = this._attachedSubEmitters;
  56893. if (this._currentColorGradient) {
  56894. other._currentColorGradient = this._currentColorGradient;
  56895. other._currentColor1.copyFrom(this._currentColor1);
  56896. other._currentColor2.copyFrom(this._currentColor2);
  56897. }
  56898. if (this._currentSizeGradient) {
  56899. other._currentSizeGradient = this._currentSizeGradient;
  56900. other._currentSize1 = this._currentSize1;
  56901. other._currentSize2 = this._currentSize2;
  56902. }
  56903. if (this._currentAngularSpeedGradient) {
  56904. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  56905. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  56906. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  56907. }
  56908. if (this._currentVelocityGradient) {
  56909. other._currentVelocityGradient = this._currentVelocityGradient;
  56910. other._currentVelocity1 = this._currentVelocity1;
  56911. other._currentVelocity2 = this._currentVelocity2;
  56912. }
  56913. if (this._currentLimitVelocityGradient) {
  56914. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  56915. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  56916. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  56917. }
  56918. if (this._currentDragGradient) {
  56919. other._currentDragGradient = this._currentDragGradient;
  56920. other._currentDrag1 = this._currentDrag1;
  56921. other._currentDrag2 = this._currentDrag2;
  56922. }
  56923. if (this.particleSystem.isAnimationSheetEnabled) {
  56924. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  56925. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  56926. }
  56927. if (this.particleSystem.useRampGradients) {
  56928. other.remapData.copyFrom(this.remapData);
  56929. }
  56930. if (this._randomNoiseCoordinates1) {
  56931. if (other._randomNoiseCoordinates1) {
  56932. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  56933. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  56934. }
  56935. else {
  56936. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  56937. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  56938. }
  56939. }
  56940. };
  56941. Particle._Count = 0;
  56942. return Particle;
  56943. }());
  56944. BABYLON.Particle = Particle;
  56945. })(BABYLON || (BABYLON = {}));
  56946. //# sourceMappingURL=babylon.particle.js.map
  56947. var BABYLON;
  56948. (function (BABYLON) {
  56949. /**
  56950. * This represents the base class for particle system in Babylon.
  56951. * 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.
  56952. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56953. * @example https://doc.babylonjs.com/babylon101/particles
  56954. */
  56955. var BaseParticleSystem = /** @class */ (function () {
  56956. /**
  56957. * Instantiates a particle system.
  56958. * 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.
  56959. * @param name The name of the particle system
  56960. */
  56961. function BaseParticleSystem(name) {
  56962. /**
  56963. * List of animations used by the particle system.
  56964. */
  56965. this.animations = [];
  56966. /**
  56967. * The rendering group used by the Particle system to chose when to render.
  56968. */
  56969. this.renderingGroupId = 0;
  56970. /**
  56971. * The emitter represents the Mesh or position we are attaching the particle system to.
  56972. */
  56973. this.emitter = null;
  56974. /**
  56975. * The maximum number of particles to emit per frame
  56976. */
  56977. this.emitRate = 10;
  56978. /**
  56979. * If you want to launch only a few particles at once, that can be done, as well.
  56980. */
  56981. this.manualEmitCount = -1;
  56982. /**
  56983. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56984. */
  56985. this.updateSpeed = 0.01;
  56986. /**
  56987. * The amount of time the particle system is running (depends of the overall update speed).
  56988. */
  56989. this.targetStopDuration = 0;
  56990. /**
  56991. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  56992. */
  56993. this.disposeOnStop = false;
  56994. /**
  56995. * Minimum power of emitting particles.
  56996. */
  56997. this.minEmitPower = 1;
  56998. /**
  56999. * Maximum power of emitting particles.
  57000. */
  57001. this.maxEmitPower = 1;
  57002. /**
  57003. * Minimum life time of emitting particles.
  57004. */
  57005. this.minLifeTime = 1;
  57006. /**
  57007. * Maximum life time of emitting particles.
  57008. */
  57009. this.maxLifeTime = 1;
  57010. /**
  57011. * Minimum Size of emitting particles.
  57012. */
  57013. this.minSize = 1;
  57014. /**
  57015. * Maximum Size of emitting particles.
  57016. */
  57017. this.maxSize = 1;
  57018. /**
  57019. * Minimum scale of emitting particles on X axis.
  57020. */
  57021. this.minScaleX = 1;
  57022. /**
  57023. * Maximum scale of emitting particles on X axis.
  57024. */
  57025. this.maxScaleX = 1;
  57026. /**
  57027. * Minimum scale of emitting particles on Y axis.
  57028. */
  57029. this.minScaleY = 1;
  57030. /**
  57031. * Maximum scale of emitting particles on Y axis.
  57032. */
  57033. this.maxScaleY = 1;
  57034. /**
  57035. * Gets or sets the minimal initial rotation in radians.
  57036. */
  57037. this.minInitialRotation = 0;
  57038. /**
  57039. * Gets or sets the maximal initial rotation in radians.
  57040. */
  57041. this.maxInitialRotation = 0;
  57042. /**
  57043. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57044. */
  57045. this.minAngularSpeed = 0;
  57046. /**
  57047. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57048. */
  57049. this.maxAngularSpeed = 0;
  57050. /**
  57051. * The layer mask we are rendering the particles through.
  57052. */
  57053. this.layerMask = 0x0FFFFFFF;
  57054. /**
  57055. * This can help using your own shader to render the particle system.
  57056. * The according effect will be created
  57057. */
  57058. this.customShader = null;
  57059. /**
  57060. * By default particle system starts as soon as they are created. This prevents the
  57061. * automatic start to happen and let you decide when to start emitting particles.
  57062. */
  57063. this.preventAutoStart = false;
  57064. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  57065. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  57066. /**
  57067. * Callback triggered when the particle animation is ending.
  57068. */
  57069. this.onAnimationEnd = null;
  57070. /**
  57071. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57072. */
  57073. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57074. /**
  57075. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57076. * to override the particles.
  57077. */
  57078. this.forceDepthWrite = false;
  57079. /** 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 */
  57080. this.preWarmCycles = 0;
  57081. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  57082. this.preWarmStepOffset = 1;
  57083. /**
  57084. * 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)
  57085. */
  57086. this.spriteCellChangeSpeed = 1;
  57087. /**
  57088. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  57089. */
  57090. this.startSpriteCellID = 0;
  57091. /**
  57092. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  57093. */
  57094. this.endSpriteCellID = 0;
  57095. /**
  57096. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  57097. */
  57098. this.spriteCellWidth = 0;
  57099. /**
  57100. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  57101. */
  57102. this.spriteCellHeight = 0;
  57103. /**
  57104. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  57105. */
  57106. this.spriteRandomStartCell = false;
  57107. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  57108. this.translationPivot = new BABYLON.Vector2(0, 0);
  57109. /**
  57110. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  57111. */
  57112. this.beginAnimationOnStart = false;
  57113. /**
  57114. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  57115. */
  57116. this.beginAnimationFrom = 0;
  57117. /**
  57118. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  57119. */
  57120. this.beginAnimationTo = 60;
  57121. /**
  57122. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  57123. */
  57124. this.beginAnimationLoop = false;
  57125. /**
  57126. * You can use gravity if you want to give an orientation to your particles.
  57127. */
  57128. this.gravity = BABYLON.Vector3.Zero();
  57129. this._colorGradients = null;
  57130. this._sizeGradients = null;
  57131. this._lifeTimeGradients = null;
  57132. this._angularSpeedGradients = null;
  57133. this._velocityGradients = null;
  57134. this._limitVelocityGradients = null;
  57135. this._dragGradients = null;
  57136. this._emitRateGradients = null;
  57137. this._startSizeGradients = null;
  57138. this._rampGradients = null;
  57139. this._colorRemapGradients = null;
  57140. this._alphaRemapGradients = null;
  57141. /**
  57142. * Defines the delay in milliseconds before starting the system (0 by default)
  57143. */
  57144. this.startDelay = 0;
  57145. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  57146. this.limitVelocityDamping = 0.4;
  57147. /**
  57148. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  57149. */
  57150. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57151. /**
  57152. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  57153. */
  57154. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57155. /**
  57156. * Color the particle will have at the end of its lifetime
  57157. */
  57158. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  57159. /**
  57160. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  57161. */
  57162. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57163. /** @hidden */
  57164. this._isSubEmitter = false;
  57165. /**
  57166. * Gets or sets the billboard mode to use when isBillboardBased = true.
  57167. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  57168. */
  57169. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  57170. this._isBillboardBased = true;
  57171. /**
  57172. * Local cache of defines for image processing.
  57173. */
  57174. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  57175. this.id = name;
  57176. this.name = name;
  57177. }
  57178. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  57179. /**
  57180. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  57181. */
  57182. get: function () {
  57183. return this._isAnimationSheetEnabled;
  57184. },
  57185. set: function (value) {
  57186. if (this._isAnimationSheetEnabled == value) {
  57187. return;
  57188. }
  57189. this._isAnimationSheetEnabled = value;
  57190. this._reset();
  57191. },
  57192. enumerable: true,
  57193. configurable: true
  57194. });
  57195. /**
  57196. * Get hosting scene
  57197. * @returns the scene
  57198. */
  57199. BaseParticleSystem.prototype.getScene = function () {
  57200. return this._scene;
  57201. };
  57202. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  57203. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  57204. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  57205. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  57206. };
  57207. /**
  57208. * Gets the current list of drag gradients.
  57209. * You must use addDragGradient and removeDragGradient to udpate this list
  57210. * @returns the list of drag gradients
  57211. */
  57212. BaseParticleSystem.prototype.getDragGradients = function () {
  57213. return this._dragGradients;
  57214. };
  57215. /**
  57216. * Gets the current list of limit velocity gradients.
  57217. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  57218. * @returns the list of limit velocity gradients
  57219. */
  57220. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  57221. return this._limitVelocityGradients;
  57222. };
  57223. /**
  57224. * Gets the current list of color gradients.
  57225. * You must use addColorGradient and removeColorGradient to udpate this list
  57226. * @returns the list of color gradients
  57227. */
  57228. BaseParticleSystem.prototype.getColorGradients = function () {
  57229. return this._colorGradients;
  57230. };
  57231. /**
  57232. * Gets the current list of size gradients.
  57233. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57234. * @returns the list of size gradients
  57235. */
  57236. BaseParticleSystem.prototype.getSizeGradients = function () {
  57237. return this._sizeGradients;
  57238. };
  57239. /**
  57240. * Gets the current list of color remap gradients.
  57241. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  57242. * @returns the list of color remap gradients
  57243. */
  57244. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  57245. return this._colorRemapGradients;
  57246. };
  57247. /**
  57248. * Gets the current list of alpha remap gradients.
  57249. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  57250. * @returns the list of alpha remap gradients
  57251. */
  57252. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  57253. return this._alphaRemapGradients;
  57254. };
  57255. /**
  57256. * Gets the current list of life time gradients.
  57257. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  57258. * @returns the list of life time gradients
  57259. */
  57260. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  57261. return this._lifeTimeGradients;
  57262. };
  57263. /**
  57264. * Gets the current list of angular speed gradients.
  57265. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  57266. * @returns the list of angular speed gradients
  57267. */
  57268. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  57269. return this._angularSpeedGradients;
  57270. };
  57271. /**
  57272. * Gets the current list of velocity gradients.
  57273. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  57274. * @returns the list of velocity gradients
  57275. */
  57276. BaseParticleSystem.prototype.getVelocityGradients = function () {
  57277. return this._velocityGradients;
  57278. };
  57279. /**
  57280. * Gets the current list of start size gradients.
  57281. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  57282. * @returns the list of start size gradients
  57283. */
  57284. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  57285. return this._startSizeGradients;
  57286. };
  57287. /**
  57288. * Gets the current list of emit rate gradients.
  57289. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  57290. * @returns the list of emit rate gradients
  57291. */
  57292. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  57293. return this._emitRateGradients;
  57294. };
  57295. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  57296. /**
  57297. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57298. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57299. */
  57300. get: function () {
  57301. if (this.particleEmitterType.direction1) {
  57302. return this.particleEmitterType.direction1;
  57303. }
  57304. return BABYLON.Vector3.Zero();
  57305. },
  57306. set: function (value) {
  57307. if (this.particleEmitterType.direction1) {
  57308. this.particleEmitterType.direction1 = value;
  57309. }
  57310. },
  57311. enumerable: true,
  57312. configurable: true
  57313. });
  57314. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  57315. /**
  57316. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57317. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57318. */
  57319. get: function () {
  57320. if (this.particleEmitterType.direction2) {
  57321. return this.particleEmitterType.direction2;
  57322. }
  57323. return BABYLON.Vector3.Zero();
  57324. },
  57325. set: function (value) {
  57326. if (this.particleEmitterType.direction2) {
  57327. this.particleEmitterType.direction2 = value;
  57328. }
  57329. },
  57330. enumerable: true,
  57331. configurable: true
  57332. });
  57333. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  57334. /**
  57335. * 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.
  57336. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57337. */
  57338. get: function () {
  57339. if (this.particleEmitterType.minEmitBox) {
  57340. return this.particleEmitterType.minEmitBox;
  57341. }
  57342. return BABYLON.Vector3.Zero();
  57343. },
  57344. set: function (value) {
  57345. if (this.particleEmitterType.minEmitBox) {
  57346. this.particleEmitterType.minEmitBox = value;
  57347. }
  57348. },
  57349. enumerable: true,
  57350. configurable: true
  57351. });
  57352. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  57353. /**
  57354. * 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.
  57355. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57356. */
  57357. get: function () {
  57358. if (this.particleEmitterType.maxEmitBox) {
  57359. return this.particleEmitterType.maxEmitBox;
  57360. }
  57361. return BABYLON.Vector3.Zero();
  57362. },
  57363. set: function (value) {
  57364. if (this.particleEmitterType.maxEmitBox) {
  57365. this.particleEmitterType.maxEmitBox = value;
  57366. }
  57367. },
  57368. enumerable: true,
  57369. configurable: true
  57370. });
  57371. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  57372. /**
  57373. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57374. */
  57375. get: function () {
  57376. return this._isBillboardBased;
  57377. },
  57378. set: function (value) {
  57379. if (this._isBillboardBased === value) {
  57380. return;
  57381. }
  57382. this._isBillboardBased = value;
  57383. this._reset();
  57384. },
  57385. enumerable: true,
  57386. configurable: true
  57387. });
  57388. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  57389. /**
  57390. * Gets the image processing configuration used either in this material.
  57391. */
  57392. get: function () {
  57393. return this._imageProcessingConfiguration;
  57394. },
  57395. /**
  57396. * Sets the Default image processing configuration used either in the this material.
  57397. *
  57398. * If sets to null, the scene one is in use.
  57399. */
  57400. set: function (value) {
  57401. this._attachImageProcessingConfiguration(value);
  57402. },
  57403. enumerable: true,
  57404. configurable: true
  57405. });
  57406. /**
  57407. * Attaches a new image processing configuration to the Standard Material.
  57408. * @param configuration
  57409. */
  57410. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  57411. if (configuration === this._imageProcessingConfiguration) {
  57412. return;
  57413. }
  57414. // Pick the scene configuration if needed.
  57415. if (!configuration) {
  57416. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  57417. }
  57418. else {
  57419. this._imageProcessingConfiguration = configuration;
  57420. }
  57421. };
  57422. /** @hidden */
  57423. BaseParticleSystem.prototype._reset = function () {
  57424. };
  57425. /** @hidden */
  57426. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  57427. if (!gradients) {
  57428. return this;
  57429. }
  57430. var index = 0;
  57431. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  57432. var valueGradient = gradients_1[_i];
  57433. if (valueGradient.gradient === gradient) {
  57434. gradients.splice(index, 1);
  57435. break;
  57436. }
  57437. index++;
  57438. }
  57439. if (texture) {
  57440. texture.dispose();
  57441. }
  57442. return this;
  57443. };
  57444. /**
  57445. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  57446. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57447. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57448. * @returns the emitter
  57449. */
  57450. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  57451. var particleEmitter = new BABYLON.PointParticleEmitter();
  57452. particleEmitter.direction1 = direction1;
  57453. particleEmitter.direction2 = direction2;
  57454. this.particleEmitterType = particleEmitter;
  57455. return particleEmitter;
  57456. };
  57457. /**
  57458. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  57459. * @param radius The radius of the hemisphere to emit from
  57460. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  57461. * @returns the emitter
  57462. */
  57463. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  57464. if (radius === void 0) { radius = 1; }
  57465. if (radiusRange === void 0) { radiusRange = 1; }
  57466. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  57467. this.particleEmitterType = particleEmitter;
  57468. return particleEmitter;
  57469. };
  57470. /**
  57471. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  57472. * @param radius The radius of the sphere to emit from
  57473. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  57474. * @returns the emitter
  57475. */
  57476. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  57477. if (radius === void 0) { radius = 1; }
  57478. if (radiusRange === void 0) { radiusRange = 1; }
  57479. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  57480. this.particleEmitterType = particleEmitter;
  57481. return particleEmitter;
  57482. };
  57483. /**
  57484. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  57485. * @param radius The radius of the sphere to emit from
  57486. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  57487. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  57488. * @returns the emitter
  57489. */
  57490. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  57491. if (radius === void 0) { radius = 1; }
  57492. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57493. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57494. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  57495. this.particleEmitterType = particleEmitter;
  57496. return particleEmitter;
  57497. };
  57498. /**
  57499. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  57500. * @param radius The radius of the emission cylinder
  57501. * @param height The height of the emission cylinder
  57502. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  57503. * @param directionRandomizer How much to randomize the particle direction [0-1]
  57504. * @returns the emitter
  57505. */
  57506. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  57507. if (radius === void 0) { radius = 1; }
  57508. if (height === void 0) { height = 1; }
  57509. if (radiusRange === void 0) { radiusRange = 1; }
  57510. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57511. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  57512. this.particleEmitterType = particleEmitter;
  57513. return particleEmitter;
  57514. };
  57515. /**
  57516. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  57517. * @param radius The radius of the cylinder to emit from
  57518. * @param height The height of the emission cylinder
  57519. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57520. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  57521. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  57522. * @returns the emitter
  57523. */
  57524. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  57525. if (radius === void 0) { radius = 1; }
  57526. if (height === void 0) { height = 1; }
  57527. if (radiusRange === void 0) { radiusRange = 1; }
  57528. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57529. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57530. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  57531. this.particleEmitterType = particleEmitter;
  57532. return particleEmitter;
  57533. };
  57534. /**
  57535. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  57536. * @param radius The radius of the cone to emit from
  57537. * @param angle The base angle of the cone
  57538. * @returns the emitter
  57539. */
  57540. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  57541. if (radius === void 0) { radius = 1; }
  57542. if (angle === void 0) { angle = Math.PI / 4; }
  57543. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  57544. this.particleEmitterType = particleEmitter;
  57545. return particleEmitter;
  57546. };
  57547. /**
  57548. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  57549. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57550. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57551. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57552. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57553. * @returns the emitter
  57554. */
  57555. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  57556. var particleEmitter = new BABYLON.BoxParticleEmitter();
  57557. this.particleEmitterType = particleEmitter;
  57558. this.direction1 = direction1;
  57559. this.direction2 = direction2;
  57560. this.minEmitBox = minEmitBox;
  57561. this.maxEmitBox = maxEmitBox;
  57562. return particleEmitter;
  57563. };
  57564. /**
  57565. * Source color is added to the destination color without alpha affecting the result
  57566. */
  57567. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  57568. /**
  57569. * Blend current color and particle color using particle’s alpha
  57570. */
  57571. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  57572. /**
  57573. * Add current color and particle color multiplied by particle’s alpha
  57574. */
  57575. BaseParticleSystem.BLENDMODE_ADD = 2;
  57576. /**
  57577. * Multiply current color with particle color
  57578. */
  57579. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  57580. /**
  57581. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  57582. */
  57583. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  57584. return BaseParticleSystem;
  57585. }());
  57586. BABYLON.BaseParticleSystem = BaseParticleSystem;
  57587. })(BABYLON || (BABYLON = {}));
  57588. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  57589. var BABYLON;
  57590. (function (BABYLON) {
  57591. /**
  57592. * This represents a particle system in Babylon.
  57593. * 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.
  57594. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  57595. * @example https://doc.babylonjs.com/babylon101/particles
  57596. */
  57597. var ParticleSystem = /** @class */ (function (_super) {
  57598. __extends(ParticleSystem, _super);
  57599. /**
  57600. * Instantiates a particle system.
  57601. * 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.
  57602. * @param name The name of the particle system
  57603. * @param capacity The max number of particles alive at the same time
  57604. * @param scene The scene the particle system belongs to
  57605. * @param customEffect a custom effect used to change the way particles are rendered by default
  57606. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  57607. * @param epsilon Offset used to render the particles
  57608. */
  57609. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  57610. if (customEffect === void 0) { customEffect = null; }
  57611. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57612. if (epsilon === void 0) { epsilon = 0.01; }
  57613. var _this = _super.call(this, name) || this;
  57614. /**
  57615. * @hidden
  57616. */
  57617. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  57618. /**
  57619. * An event triggered when the system is disposed
  57620. */
  57621. _this.onDisposeObservable = new BABYLON.Observable();
  57622. _this._particles = new Array();
  57623. _this._stockParticles = new Array();
  57624. _this._newPartsExcess = 0;
  57625. _this._vertexBuffers = {};
  57626. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  57627. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  57628. _this._scaledDirection = BABYLON.Vector3.Zero();
  57629. _this._scaledGravity = BABYLON.Vector3.Zero();
  57630. _this._currentRenderId = -1;
  57631. _this._useInstancing = false;
  57632. _this._started = false;
  57633. _this._stopped = false;
  57634. _this._actualFrame = 0;
  57635. /** @hidden */
  57636. _this._currentEmitRate1 = 0;
  57637. /** @hidden */
  57638. _this._currentEmitRate2 = 0;
  57639. /** @hidden */
  57640. _this._currentStartSize1 = 0;
  57641. /** @hidden */
  57642. _this._currentStartSize2 = 0;
  57643. _this._rawTextureWidth = 256;
  57644. _this._useRampGradients = false;
  57645. /**
  57646. * @hidden
  57647. * If the particle systems emitter should be disposed when the particle system is disposed
  57648. */
  57649. _this._disposeEmitterOnDispose = false;
  57650. // start of sub system methods
  57651. /**
  57652. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  57653. * Its lifetime will start back at 0.
  57654. */
  57655. _this.recycleParticle = function (particle) {
  57656. // move particle from activeParticle list to stock particles
  57657. var lastParticle = _this._particles.pop();
  57658. if (lastParticle !== particle) {
  57659. lastParticle.copyTo(particle);
  57660. }
  57661. _this._stockParticles.push(lastParticle);
  57662. };
  57663. _this._createParticle = function () {
  57664. var particle;
  57665. if (_this._stockParticles.length !== 0) {
  57666. particle = _this._stockParticles.pop();
  57667. particle._reset();
  57668. }
  57669. else {
  57670. particle = new BABYLON.Particle(_this);
  57671. }
  57672. // Attach emitters
  57673. if (_this._subEmitters && _this._subEmitters.length > 0) {
  57674. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  57675. particle._attachedSubEmitters = [];
  57676. subEmitters.forEach(function (subEmitter) {
  57677. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  57678. var newEmitter = subEmitter.clone();
  57679. particle._attachedSubEmitters.push(newEmitter);
  57680. newEmitter.particleSystem.start();
  57681. }
  57682. });
  57683. }
  57684. return particle;
  57685. };
  57686. _this._emitFromParticle = function (particle) {
  57687. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  57688. return;
  57689. }
  57690. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  57691. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  57692. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  57693. var subSystem = subEmitter.clone();
  57694. particle._inheritParticleInfoToSubEmitter(subSystem);
  57695. subSystem.particleSystem._rootParticleSystem = _this;
  57696. _this.activeSubSystems.push(subSystem.particleSystem);
  57697. subSystem.particleSystem.start();
  57698. }
  57699. });
  57700. };
  57701. _this._capacity = capacity;
  57702. _this._epsilon = epsilon;
  57703. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  57704. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57705. // Setup the default processing configuration to the scene.
  57706. _this._attachImageProcessingConfiguration(null);
  57707. _this._customEffect = customEffect;
  57708. _this._scene.particleSystems.push(_this);
  57709. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  57710. _this._createIndexBuffer();
  57711. _this._createVertexBuffers();
  57712. // Default emitter type
  57713. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57714. // Update
  57715. _this.updateFunction = function (particles) {
  57716. var noiseTextureSize = null;
  57717. var noiseTextureData = null;
  57718. if (_this.noiseTexture) { // We need to get texture data back to CPU
  57719. noiseTextureSize = _this.noiseTexture.getSize();
  57720. noiseTextureData = (_this.noiseTexture.getContent());
  57721. }
  57722. var _loop_1 = function () {
  57723. particle = particles[index];
  57724. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  57725. var previousAge = particle.age;
  57726. particle.age += scaledUpdateSpeed;
  57727. // Evaluate step to death
  57728. if (particle.age > particle.lifeTime) {
  57729. var diff = particle.age - previousAge;
  57730. var oldDiff = particle.lifeTime - previousAge;
  57731. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  57732. particle.age = particle.lifeTime;
  57733. }
  57734. var ratio = particle.age / particle.lifeTime;
  57735. // Color
  57736. if (_this._colorGradients && _this._colorGradients.length > 0) {
  57737. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  57738. if (currentGradient !== particle._currentColorGradient) {
  57739. particle._currentColor1.copyFrom(particle._currentColor2);
  57740. nextGradient.getColorToRef(particle._currentColor2);
  57741. particle._currentColorGradient = currentGradient;
  57742. }
  57743. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  57744. });
  57745. }
  57746. else {
  57747. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  57748. particle.color.addInPlace(_this._scaledColorStep);
  57749. if (particle.color.a < 0) {
  57750. particle.color.a = 0;
  57751. }
  57752. }
  57753. // Angular speed
  57754. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  57755. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  57756. if (currentGradient !== particle._currentAngularSpeedGradient) {
  57757. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  57758. particle._currentAngularSpeed2 = nextGradient.getFactor();
  57759. particle._currentAngularSpeedGradient = currentGradient;
  57760. }
  57761. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  57762. });
  57763. }
  57764. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  57765. // Direction
  57766. var directionScale = scaledUpdateSpeed;
  57767. /// Velocity
  57768. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  57769. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  57770. if (currentGradient !== particle._currentVelocityGradient) {
  57771. particle._currentVelocity1 = particle._currentVelocity2;
  57772. particle._currentVelocity2 = nextGradient.getFactor();
  57773. particle._currentVelocityGradient = currentGradient;
  57774. }
  57775. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  57776. });
  57777. }
  57778. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  57779. /// Limit velocity
  57780. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  57781. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  57782. if (currentGradient !== particle._currentLimitVelocityGradient) {
  57783. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  57784. particle._currentLimitVelocity2 = nextGradient.getFactor();
  57785. particle._currentLimitVelocityGradient = currentGradient;
  57786. }
  57787. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  57788. var currentVelocity = particle.direction.length();
  57789. if (currentVelocity > limitVelocity) {
  57790. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  57791. }
  57792. });
  57793. }
  57794. /// Drag
  57795. if (_this._dragGradients && _this._dragGradients.length > 0) {
  57796. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  57797. if (currentGradient !== particle._currentDragGradient) {
  57798. particle._currentDrag1 = particle._currentDrag2;
  57799. particle._currentDrag2 = nextGradient.getFactor();
  57800. particle._currentDragGradient = currentGradient;
  57801. }
  57802. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  57803. _this._scaledDirection.scaleInPlace(1.0 - drag);
  57804. });
  57805. }
  57806. particle.position.addInPlace(_this._scaledDirection);
  57807. // Noise
  57808. if (noiseTextureData && noiseTextureSize) {
  57809. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57810. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57811. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57812. var force = BABYLON.Tmp.Vector3[0];
  57813. var scaledForce = BABYLON.Tmp.Vector3[1];
  57814. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  57815. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  57816. particle.direction.addInPlace(scaledForce);
  57817. }
  57818. // Gravity
  57819. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  57820. particle.direction.addInPlace(_this._scaledGravity);
  57821. // Size
  57822. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  57823. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  57824. if (currentGradient !== particle._currentSizeGradient) {
  57825. particle._currentSize1 = particle._currentSize2;
  57826. particle._currentSize2 = nextGradient.getFactor();
  57827. particle._currentSizeGradient = currentGradient;
  57828. }
  57829. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  57830. });
  57831. }
  57832. // Remap data
  57833. if (_this._useRampGradients) {
  57834. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  57835. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  57836. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57837. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  57838. particle.remapData.x = min;
  57839. particle.remapData.y = max - min;
  57840. });
  57841. }
  57842. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  57843. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  57844. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57845. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  57846. particle.remapData.z = min;
  57847. particle.remapData.w = max - min;
  57848. });
  57849. }
  57850. }
  57851. if (_this._isAnimationSheetEnabled) {
  57852. particle.updateCellIndex();
  57853. }
  57854. // Update the position of the attached sub-emitters to match their attached particle
  57855. particle._inheritParticleInfoToSubEmitters();
  57856. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  57857. _this._emitFromParticle(particle);
  57858. if (particle._attachedSubEmitters) {
  57859. particle._attachedSubEmitters.forEach(function (subEmitter) {
  57860. subEmitter.particleSystem.disposeOnStop = true;
  57861. subEmitter.particleSystem.stop();
  57862. });
  57863. particle._attachedSubEmitters = null;
  57864. }
  57865. _this.recycleParticle(particle);
  57866. index--;
  57867. return "continue";
  57868. }
  57869. };
  57870. var particle;
  57871. for (var index = 0; index < particles.length; index++) {
  57872. _loop_1();
  57873. }
  57874. };
  57875. return _this;
  57876. }
  57877. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  57878. /**
  57879. * Sets a callback that will be triggered when the system is disposed
  57880. */
  57881. set: function (callback) {
  57882. if (this._onDisposeObserver) {
  57883. this.onDisposeObservable.remove(this._onDisposeObserver);
  57884. }
  57885. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  57886. },
  57887. enumerable: true,
  57888. configurable: true
  57889. });
  57890. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  57891. /** Gets or sets a boolean indicating that ramp gradients must be used
  57892. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  57893. */
  57894. get: function () {
  57895. return this._useRampGradients;
  57896. },
  57897. set: function (value) {
  57898. if (this._useRampGradients === value) {
  57899. return;
  57900. }
  57901. this._useRampGradients = value;
  57902. this._resetEffect();
  57903. },
  57904. enumerable: true,
  57905. configurable: true
  57906. });
  57907. Object.defineProperty(ParticleSystem.prototype, "particles", {
  57908. //end of Sub-emitter
  57909. /**
  57910. * Gets the current list of active particles
  57911. */
  57912. get: function () {
  57913. return this._particles;
  57914. },
  57915. enumerable: true,
  57916. configurable: true
  57917. });
  57918. /**
  57919. * Returns the string "ParticleSystem"
  57920. * @returns a string containing the class name
  57921. */
  57922. ParticleSystem.prototype.getClassName = function () {
  57923. return "ParticleSystem";
  57924. };
  57925. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  57926. var newGradient = new BABYLON.FactorGradient();
  57927. newGradient.gradient = gradient;
  57928. newGradient.factor1 = factor;
  57929. newGradient.factor2 = factor2;
  57930. factorGradients.push(newGradient);
  57931. factorGradients.sort(function (a, b) {
  57932. if (a.gradient < b.gradient) {
  57933. return -1;
  57934. }
  57935. else if (a.gradient > b.gradient) {
  57936. return 1;
  57937. }
  57938. return 0;
  57939. });
  57940. };
  57941. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  57942. if (!factorGradients) {
  57943. return;
  57944. }
  57945. var index = 0;
  57946. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  57947. var factorGradient = factorGradients_1[_i];
  57948. if (factorGradient.gradient === gradient) {
  57949. factorGradients.splice(index, 1);
  57950. break;
  57951. }
  57952. index++;
  57953. }
  57954. };
  57955. /**
  57956. * Adds a new life time gradient
  57957. * @param gradient defines the gradient to use (between 0 and 1)
  57958. * @param factor defines the life time factor to affect to the specified gradient
  57959. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57960. * @returns the current particle system
  57961. */
  57962. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  57963. if (!this._lifeTimeGradients) {
  57964. this._lifeTimeGradients = [];
  57965. }
  57966. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  57967. return this;
  57968. };
  57969. /**
  57970. * Remove a specific life time gradient
  57971. * @param gradient defines the gradient to remove
  57972. * @returns the current particle system
  57973. */
  57974. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  57975. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  57976. return this;
  57977. };
  57978. /**
  57979. * Adds a new size gradient
  57980. * @param gradient defines the gradient to use (between 0 and 1)
  57981. * @param factor defines the size factor to affect to the specified gradient
  57982. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57983. * @returns the current particle system
  57984. */
  57985. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  57986. if (!this._sizeGradients) {
  57987. this._sizeGradients = [];
  57988. }
  57989. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  57990. return this;
  57991. };
  57992. /**
  57993. * Remove a specific size gradient
  57994. * @param gradient defines the gradient to remove
  57995. * @returns the current particle system
  57996. */
  57997. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57998. this._removeFactorGradient(this._sizeGradients, gradient);
  57999. return this;
  58000. };
  58001. /**
  58002. * Adds a new color remap gradient
  58003. * @param gradient defines the gradient to use (between 0 and 1)
  58004. * @param min defines the color remap minimal range
  58005. * @param max defines the color remap maximal range
  58006. * @returns the current particle system
  58007. */
  58008. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  58009. if (!this._colorRemapGradients) {
  58010. this._colorRemapGradients = [];
  58011. }
  58012. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  58013. return this;
  58014. };
  58015. /**
  58016. * Remove a specific color remap gradient
  58017. * @param gradient defines the gradient to remove
  58018. * @returns the current particle system
  58019. */
  58020. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  58021. this._removeFactorGradient(this._colorRemapGradients, gradient);
  58022. return this;
  58023. };
  58024. /**
  58025. * Adds a new alpha remap gradient
  58026. * @param gradient defines the gradient to use (between 0 and 1)
  58027. * @param min defines the alpha remap minimal range
  58028. * @param max defines the alpha remap maximal range
  58029. * @returns the current particle system
  58030. */
  58031. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  58032. if (!this._alphaRemapGradients) {
  58033. this._alphaRemapGradients = [];
  58034. }
  58035. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  58036. return this;
  58037. };
  58038. /**
  58039. * Remove a specific alpha remap gradient
  58040. * @param gradient defines the gradient to remove
  58041. * @returns the current particle system
  58042. */
  58043. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  58044. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  58045. return this;
  58046. };
  58047. /**
  58048. * Adds a new angular speed gradient
  58049. * @param gradient defines the gradient to use (between 0 and 1)
  58050. * @param factor defines the angular speed to affect to the specified gradient
  58051. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58052. * @returns the current particle system
  58053. */
  58054. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  58055. if (!this._angularSpeedGradients) {
  58056. this._angularSpeedGradients = [];
  58057. }
  58058. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  58059. return this;
  58060. };
  58061. /**
  58062. * Remove a specific angular speed gradient
  58063. * @param gradient defines the gradient to remove
  58064. * @returns the current particle system
  58065. */
  58066. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  58067. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  58068. return this;
  58069. };
  58070. /**
  58071. * Adds a new velocity gradient
  58072. * @param gradient defines the gradient to use (between 0 and 1)
  58073. * @param factor defines the velocity to affect to the specified gradient
  58074. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58075. * @returns the current particle system
  58076. */
  58077. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  58078. if (!this._velocityGradients) {
  58079. this._velocityGradients = [];
  58080. }
  58081. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  58082. return this;
  58083. };
  58084. /**
  58085. * Remove a specific velocity gradient
  58086. * @param gradient defines the gradient to remove
  58087. * @returns the current particle system
  58088. */
  58089. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  58090. this._removeFactorGradient(this._velocityGradients, gradient);
  58091. return this;
  58092. };
  58093. /**
  58094. * Adds a new limit velocity gradient
  58095. * @param gradient defines the gradient to use (between 0 and 1)
  58096. * @param factor defines the limit velocity value to affect to the specified gradient
  58097. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58098. * @returns the current particle system
  58099. */
  58100. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  58101. if (!this._limitVelocityGradients) {
  58102. this._limitVelocityGradients = [];
  58103. }
  58104. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  58105. return this;
  58106. };
  58107. /**
  58108. * Remove a specific limit velocity gradient
  58109. * @param gradient defines the gradient to remove
  58110. * @returns the current particle system
  58111. */
  58112. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  58113. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  58114. return this;
  58115. };
  58116. /**
  58117. * Adds a new drag gradient
  58118. * @param gradient defines the gradient to use (between 0 and 1)
  58119. * @param factor defines the drag value to affect to the specified gradient
  58120. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58121. * @returns the current particle system
  58122. */
  58123. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  58124. if (!this._dragGradients) {
  58125. this._dragGradients = [];
  58126. }
  58127. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  58128. return this;
  58129. };
  58130. /**
  58131. * Remove a specific drag gradient
  58132. * @param gradient defines the gradient to remove
  58133. * @returns the current particle system
  58134. */
  58135. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  58136. this._removeFactorGradient(this._dragGradients, gradient);
  58137. return this;
  58138. };
  58139. /**
  58140. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  58141. * @param gradient defines the gradient to use (between 0 and 1)
  58142. * @param factor defines the emit rate value to affect to the specified gradient
  58143. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58144. * @returns the current particle system
  58145. */
  58146. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  58147. if (!this._emitRateGradients) {
  58148. this._emitRateGradients = [];
  58149. }
  58150. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  58151. if (!this._currentEmitRateGradient) {
  58152. this._currentEmitRateGradient = this._emitRateGradients[0];
  58153. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  58154. this._currentEmitRate2 = this._currentEmitRate1;
  58155. }
  58156. if (this._emitRateGradients.length === 2) {
  58157. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  58158. }
  58159. return this;
  58160. };
  58161. /**
  58162. * Remove a specific emit rate gradient
  58163. * @param gradient defines the gradient to remove
  58164. * @returns the current particle system
  58165. */
  58166. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  58167. this._removeFactorGradient(this._emitRateGradients, gradient);
  58168. return this;
  58169. };
  58170. /**
  58171. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  58172. * @param gradient defines the gradient to use (between 0 and 1)
  58173. * @param factor defines the start size value to affect to the specified gradient
  58174. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58175. * @returns the current particle system
  58176. */
  58177. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  58178. if (!this._startSizeGradients) {
  58179. this._startSizeGradients = [];
  58180. }
  58181. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  58182. if (!this._currentStartSizeGradient) {
  58183. this._currentStartSizeGradient = this._startSizeGradients[0];
  58184. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  58185. this._currentStartSize2 = this._currentStartSize1;
  58186. }
  58187. if (this._startSizeGradients.length === 2) {
  58188. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  58189. }
  58190. return this;
  58191. };
  58192. /**
  58193. * Remove a specific start size gradient
  58194. * @param gradient defines the gradient to remove
  58195. * @returns the current particle system
  58196. */
  58197. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  58198. this._removeFactorGradient(this._emitRateGradients, gradient);
  58199. return this;
  58200. };
  58201. ParticleSystem.prototype._createRampGradientTexture = function () {
  58202. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  58203. return;
  58204. }
  58205. var data = new Uint8Array(this._rawTextureWidth * 4);
  58206. var tmpColor = BABYLON.Tmp.Color3[0];
  58207. for (var x = 0; x < this._rawTextureWidth; x++) {
  58208. var ratio = x / this._rawTextureWidth;
  58209. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  58210. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  58211. data[x * 4] = tmpColor.r * 255;
  58212. data[x * 4 + 1] = tmpColor.g * 255;
  58213. data[x * 4 + 2] = tmpColor.b * 255;
  58214. data[x * 4 + 3] = 255;
  58215. });
  58216. }
  58217. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58218. };
  58219. /**
  58220. * Gets the current list of ramp gradients.
  58221. * You must use addRampGradient and removeRampGradient to udpate this list
  58222. * @returns the list of ramp gradients
  58223. */
  58224. ParticleSystem.prototype.getRampGradients = function () {
  58225. return this._rampGradients;
  58226. };
  58227. /**
  58228. * Adds a new ramp gradient used to remap particle colors
  58229. * @param gradient defines the gradient to use (between 0 and 1)
  58230. * @param color defines the color to affect to the specified gradient
  58231. * @returns the current particle system
  58232. */
  58233. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  58234. if (!this._rampGradients) {
  58235. this._rampGradients = [];
  58236. }
  58237. var rampGradient = new BABYLON.Color3Gradient();
  58238. rampGradient.gradient = gradient;
  58239. rampGradient.color = color;
  58240. this._rampGradients.push(rampGradient);
  58241. this._rampGradients.sort(function (a, b) {
  58242. if (a.gradient < b.gradient) {
  58243. return -1;
  58244. }
  58245. else if (a.gradient > b.gradient) {
  58246. return 1;
  58247. }
  58248. return 0;
  58249. });
  58250. if (this._rampGradientsTexture) {
  58251. this._rampGradientsTexture.dispose();
  58252. this._rampGradientsTexture = null;
  58253. }
  58254. this._createRampGradientTexture();
  58255. return this;
  58256. };
  58257. /**
  58258. * Remove a specific ramp gradient
  58259. * @param gradient defines the gradient to remove
  58260. * @returns the current particle system
  58261. */
  58262. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  58263. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  58264. this._rampGradientsTexture = null;
  58265. if (this._rampGradients && this._rampGradients.length > 0) {
  58266. this._createRampGradientTexture();
  58267. }
  58268. return this;
  58269. };
  58270. /**
  58271. * Adds a new color gradient
  58272. * @param gradient defines the gradient to use (between 0 and 1)
  58273. * @param color1 defines the color to affect to the specified gradient
  58274. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  58275. */
  58276. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  58277. if (!this._colorGradients) {
  58278. this._colorGradients = [];
  58279. }
  58280. var colorGradient = new BABYLON.ColorGradient();
  58281. colorGradient.gradient = gradient;
  58282. colorGradient.color1 = color1;
  58283. colorGradient.color2 = color2;
  58284. this._colorGradients.push(colorGradient);
  58285. this._colorGradients.sort(function (a, b) {
  58286. if (a.gradient < b.gradient) {
  58287. return -1;
  58288. }
  58289. else if (a.gradient > b.gradient) {
  58290. return 1;
  58291. }
  58292. return 0;
  58293. });
  58294. return this;
  58295. };
  58296. /**
  58297. * Remove a specific color gradient
  58298. * @param gradient defines the gradient to remove
  58299. */
  58300. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  58301. if (!this._colorGradients) {
  58302. return this;
  58303. }
  58304. var index = 0;
  58305. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  58306. var colorGradient = _a[_i];
  58307. if (colorGradient.gradient === gradient) {
  58308. this._colorGradients.splice(index, 1);
  58309. break;
  58310. }
  58311. index++;
  58312. }
  58313. return this;
  58314. };
  58315. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  58316. u = Math.abs(u) * 0.5 + 0.5;
  58317. v = Math.abs(v) * 0.5 + 0.5;
  58318. var wrappedU = ((u * width) % width) | 0;
  58319. var wrappedV = ((v * height) % height) | 0;
  58320. var position = (wrappedU + wrappedV * width) * 4;
  58321. return pixels[position] / 255;
  58322. };
  58323. ParticleSystem.prototype._reset = function () {
  58324. this._resetEffect();
  58325. };
  58326. ParticleSystem.prototype._resetEffect = function () {
  58327. if (this._vertexBuffer) {
  58328. this._vertexBuffer.dispose();
  58329. this._vertexBuffer = null;
  58330. }
  58331. if (this._spriteBuffer) {
  58332. this._spriteBuffer.dispose();
  58333. this._spriteBuffer = null;
  58334. }
  58335. this._createVertexBuffers();
  58336. };
  58337. ParticleSystem.prototype._createVertexBuffers = function () {
  58338. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  58339. if (this._isAnimationSheetEnabled) {
  58340. this._vertexBufferSize += 1;
  58341. }
  58342. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58343. this._vertexBufferSize += 3;
  58344. }
  58345. if (this._useRampGradients) {
  58346. this._vertexBufferSize += 4;
  58347. }
  58348. var engine = this._scene.getEngine();
  58349. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  58350. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  58351. var dataOffset = 0;
  58352. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  58353. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  58354. dataOffset += 3;
  58355. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  58356. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  58357. dataOffset += 4;
  58358. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  58359. this._vertexBuffers["angle"] = options;
  58360. dataOffset += 1;
  58361. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  58362. this._vertexBuffers["size"] = size;
  58363. dataOffset += 2;
  58364. if (this._isAnimationSheetEnabled) {
  58365. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  58366. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  58367. dataOffset += 1;
  58368. }
  58369. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58370. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  58371. this._vertexBuffers["direction"] = directionBuffer;
  58372. dataOffset += 3;
  58373. }
  58374. if (this._useRampGradients) {
  58375. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  58376. this._vertexBuffers["remapData"] = rampDataBuffer;
  58377. dataOffset += 4;
  58378. }
  58379. var offsets;
  58380. if (this._useInstancing) {
  58381. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  58382. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  58383. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  58384. }
  58385. else {
  58386. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  58387. dataOffset += 2;
  58388. }
  58389. this._vertexBuffers["offset"] = offsets;
  58390. };
  58391. ParticleSystem.prototype._createIndexBuffer = function () {
  58392. if (this._useInstancing) {
  58393. return;
  58394. }
  58395. var indices = [];
  58396. var index = 0;
  58397. for (var count = 0; count < this._capacity; count++) {
  58398. indices.push(index);
  58399. indices.push(index + 1);
  58400. indices.push(index + 2);
  58401. indices.push(index);
  58402. indices.push(index + 2);
  58403. indices.push(index + 3);
  58404. index += 4;
  58405. }
  58406. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  58407. };
  58408. /**
  58409. * Gets the maximum number of particles active at the same time.
  58410. * @returns The max number of active particles.
  58411. */
  58412. ParticleSystem.prototype.getCapacity = function () {
  58413. return this._capacity;
  58414. };
  58415. /**
  58416. * Gets whether there are still active particles in the system.
  58417. * @returns True if it is alive, otherwise false.
  58418. */
  58419. ParticleSystem.prototype.isAlive = function () {
  58420. return this._alive;
  58421. };
  58422. /**
  58423. * Gets if the system has been started. (Note: this will still be true after stop is called)
  58424. * @returns True if it has been started, otherwise false.
  58425. */
  58426. ParticleSystem.prototype.isStarted = function () {
  58427. return this._started;
  58428. };
  58429. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  58430. var _this = this;
  58431. this._subEmitters = new Array();
  58432. if (this.subEmitters) {
  58433. this.subEmitters.forEach(function (subEmitter) {
  58434. if (subEmitter instanceof ParticleSystem) {
  58435. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  58436. }
  58437. else if (subEmitter instanceof BABYLON.SubEmitter) {
  58438. _this._subEmitters.push([subEmitter]);
  58439. }
  58440. else if (subEmitter instanceof Array) {
  58441. _this._subEmitters.push(subEmitter);
  58442. }
  58443. });
  58444. }
  58445. };
  58446. /**
  58447. * Starts the particle system and begins to emit
  58448. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  58449. */
  58450. ParticleSystem.prototype.start = function (delay) {
  58451. var _this = this;
  58452. if (delay === void 0) { delay = this.startDelay; }
  58453. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  58454. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  58455. }
  58456. if (delay) {
  58457. setTimeout(function () {
  58458. _this.start(0);
  58459. }, delay);
  58460. return;
  58461. }
  58462. // Convert the subEmitters field to the constant type field _subEmitters
  58463. this._prepareSubEmitterInternalArray();
  58464. this._started = true;
  58465. this._stopped = false;
  58466. this._actualFrame = 0;
  58467. if (this._subEmitters && this._subEmitters.length != 0) {
  58468. this.activeSubSystems = new Array();
  58469. }
  58470. if (this.preWarmCycles) {
  58471. if (this.emitter instanceof BABYLON.AbstractMesh) {
  58472. this.emitter.computeWorldMatrix(true);
  58473. }
  58474. var noiseTextureAsProcedural_1 = this.noiseTexture;
  58475. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  58476. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  58477. setTimeout(function () {
  58478. for (var index = 0; index < _this.preWarmCycles; index++) {
  58479. _this.animate(true);
  58480. noiseTextureAsProcedural_1.render();
  58481. }
  58482. });
  58483. });
  58484. }
  58485. else {
  58486. for (var index = 0; index < this.preWarmCycles; index++) {
  58487. this.animate(true);
  58488. }
  58489. }
  58490. }
  58491. // Animations
  58492. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  58493. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  58494. }
  58495. };
  58496. /**
  58497. * Stops the particle system.
  58498. * @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.
  58499. */
  58500. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  58501. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  58502. this._stopped = true;
  58503. if (stopSubEmitters) {
  58504. this._stopSubEmitters();
  58505. }
  58506. };
  58507. // animation sheet
  58508. /**
  58509. * Remove all active particles
  58510. */
  58511. ParticleSystem.prototype.reset = function () {
  58512. this._stockParticles = [];
  58513. this._particles = [];
  58514. };
  58515. /**
  58516. * @hidden (for internal use only)
  58517. */
  58518. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  58519. var offset = index * this._vertexBufferSize;
  58520. this._vertexData[offset++] = particle.position.x;
  58521. this._vertexData[offset++] = particle.position.y;
  58522. this._vertexData[offset++] = particle.position.z;
  58523. this._vertexData[offset++] = particle.color.r;
  58524. this._vertexData[offset++] = particle.color.g;
  58525. this._vertexData[offset++] = particle.color.b;
  58526. this._vertexData[offset++] = particle.color.a;
  58527. this._vertexData[offset++] = particle.angle;
  58528. this._vertexData[offset++] = particle.scale.x * particle.size;
  58529. this._vertexData[offset++] = particle.scale.y * particle.size;
  58530. if (this._isAnimationSheetEnabled) {
  58531. this._vertexData[offset++] = particle.cellIndex;
  58532. }
  58533. if (!this._isBillboardBased) {
  58534. if (particle._initialDirection) {
  58535. this._vertexData[offset++] = particle._initialDirection.x;
  58536. this._vertexData[offset++] = particle._initialDirection.y;
  58537. this._vertexData[offset++] = particle._initialDirection.z;
  58538. }
  58539. else {
  58540. this._vertexData[offset++] = particle.direction.x;
  58541. this._vertexData[offset++] = particle.direction.y;
  58542. this._vertexData[offset++] = particle.direction.z;
  58543. }
  58544. }
  58545. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58546. this._vertexData[offset++] = particle.direction.x;
  58547. this._vertexData[offset++] = particle.direction.y;
  58548. this._vertexData[offset++] = particle.direction.z;
  58549. }
  58550. if (this._useRampGradients) {
  58551. this._vertexData[offset++] = particle.remapData.x;
  58552. this._vertexData[offset++] = particle.remapData.y;
  58553. this._vertexData[offset++] = particle.remapData.z;
  58554. this._vertexData[offset++] = particle.remapData.w;
  58555. }
  58556. if (!this._useInstancing) {
  58557. if (this._isAnimationSheetEnabled) {
  58558. if (offsetX === 0)
  58559. offsetX = this._epsilon;
  58560. else if (offsetX === 1)
  58561. offsetX = 1 - this._epsilon;
  58562. if (offsetY === 0)
  58563. offsetY = this._epsilon;
  58564. else if (offsetY === 1)
  58565. offsetY = 1 - this._epsilon;
  58566. }
  58567. this._vertexData[offset++] = offsetX;
  58568. this._vertexData[offset++] = offsetY;
  58569. }
  58570. };
  58571. ParticleSystem.prototype._stopSubEmitters = function () {
  58572. if (!this.activeSubSystems) {
  58573. return;
  58574. }
  58575. this.activeSubSystems.forEach(function (subSystem) {
  58576. subSystem.stop(true);
  58577. });
  58578. this.activeSubSystems = new Array();
  58579. };
  58580. ParticleSystem.prototype._removeFromRoot = function () {
  58581. if (!this._rootParticleSystem) {
  58582. return;
  58583. }
  58584. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  58585. if (index !== -1) {
  58586. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  58587. }
  58588. this._rootParticleSystem = null;
  58589. };
  58590. // End of sub system methods
  58591. ParticleSystem.prototype._update = function (newParticles) {
  58592. var _this = this;
  58593. // Update current
  58594. this._alive = this._particles.length > 0;
  58595. if (this.emitter.position) {
  58596. var emitterMesh = this.emitter;
  58597. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  58598. }
  58599. else {
  58600. var emitterPosition = this.emitter;
  58601. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58602. }
  58603. this.updateFunction(this._particles);
  58604. // Add new ones
  58605. var particle;
  58606. var _loop_2 = function () {
  58607. if (this_1._particles.length === this_1._capacity) {
  58608. return "break";
  58609. }
  58610. particle = this_1._createParticle();
  58611. this_1._particles.push(particle);
  58612. // Emitter
  58613. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  58614. if (this_1.startPositionFunction) {
  58615. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  58616. }
  58617. else {
  58618. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  58619. }
  58620. if (this_1.startDirectionFunction) {
  58621. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  58622. }
  58623. else {
  58624. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  58625. }
  58626. if (emitPower === 0) {
  58627. if (!particle._initialDirection) {
  58628. particle._initialDirection = particle.direction.clone();
  58629. }
  58630. else {
  58631. particle._initialDirection.copyFrom(particle.direction);
  58632. }
  58633. }
  58634. else {
  58635. particle._initialDirection = null;
  58636. }
  58637. particle.direction.scaleInPlace(emitPower);
  58638. // Life time
  58639. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  58640. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  58641. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  58642. var factorGradient1 = currentGradient;
  58643. var factorGradient2 = nextGradient;
  58644. var lifeTime1 = factorGradient1.getFactor();
  58645. var lifeTime2 = factorGradient2.getFactor();
  58646. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  58647. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  58648. });
  58649. }
  58650. else {
  58651. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  58652. }
  58653. // Size
  58654. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  58655. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  58656. }
  58657. else {
  58658. particle._currentSizeGradient = this_1._sizeGradients[0];
  58659. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  58660. particle.size = particle._currentSize1;
  58661. if (this_1._sizeGradients.length > 1) {
  58662. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  58663. }
  58664. else {
  58665. particle._currentSize2 = particle._currentSize1;
  58666. }
  58667. }
  58668. // Size and scale
  58669. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  58670. // Adjust scale by start size
  58671. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  58672. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  58673. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  58674. if (currentGradient !== _this._currentStartSizeGradient) {
  58675. _this._currentStartSize1 = _this._currentStartSize2;
  58676. _this._currentStartSize2 = nextGradient.getFactor();
  58677. _this._currentStartSizeGradient = currentGradient;
  58678. }
  58679. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  58680. particle.scale.scaleInPlace(value);
  58681. });
  58682. }
  58683. // Angle
  58684. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  58685. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  58686. }
  58687. else {
  58688. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  58689. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  58690. particle._currentAngularSpeed1 = particle.angularSpeed;
  58691. if (this_1._angularSpeedGradients.length > 1) {
  58692. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  58693. }
  58694. else {
  58695. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  58696. }
  58697. }
  58698. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  58699. // Velocity
  58700. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  58701. particle._currentVelocityGradient = this_1._velocityGradients[0];
  58702. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  58703. if (this_1._velocityGradients.length > 1) {
  58704. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  58705. }
  58706. else {
  58707. particle._currentVelocity2 = particle._currentVelocity1;
  58708. }
  58709. }
  58710. // Limit velocity
  58711. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  58712. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  58713. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  58714. if (this_1._limitVelocityGradients.length > 1) {
  58715. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  58716. }
  58717. else {
  58718. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  58719. }
  58720. }
  58721. // Drag
  58722. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  58723. particle._currentDragGradient = this_1._dragGradients[0];
  58724. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  58725. if (this_1._dragGradients.length > 1) {
  58726. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  58727. }
  58728. else {
  58729. particle._currentDrag2 = particle._currentDrag1;
  58730. }
  58731. }
  58732. // Color
  58733. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  58734. step = BABYLON.Scalar.RandomRange(0, 1.0);
  58735. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  58736. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  58737. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  58738. }
  58739. else {
  58740. particle._currentColorGradient = this_1._colorGradients[0];
  58741. particle._currentColorGradient.getColorToRef(particle.color);
  58742. particle._currentColor1.copyFrom(particle.color);
  58743. if (this_1._colorGradients.length > 1) {
  58744. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  58745. }
  58746. else {
  58747. particle._currentColor2.copyFrom(particle.color);
  58748. }
  58749. }
  58750. // Sheet
  58751. if (this_1._isAnimationSheetEnabled) {
  58752. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  58753. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  58754. }
  58755. // Inherited Velocity
  58756. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  58757. // Ramp
  58758. if (this_1._useRampGradients) {
  58759. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  58760. }
  58761. // Noise texture coordinates
  58762. if (this_1.noiseTexture) {
  58763. if (particle._randomNoiseCoordinates1) {
  58764. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  58765. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  58766. }
  58767. else {
  58768. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  58769. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  58770. }
  58771. }
  58772. // Update the position of the attached sub-emitters to match their attached particle
  58773. particle._inheritParticleInfoToSubEmitters();
  58774. };
  58775. var this_1 = this, step;
  58776. for (var index = 0; index < newParticles; index++) {
  58777. var state_1 = _loop_2();
  58778. if (state_1 === "break")
  58779. break;
  58780. }
  58781. };
  58782. /** @hidden */
  58783. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  58784. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58785. if (isBillboardBased === void 0) { isBillboardBased = false; }
  58786. if (useRampGradients === void 0) { useRampGradients = false; }
  58787. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  58788. if (isAnimationSheetEnabled) {
  58789. attributeNamesOrOptions.push("cellIndex");
  58790. }
  58791. if (!isBillboardBased) {
  58792. attributeNamesOrOptions.push("direction");
  58793. }
  58794. if (useRampGradients) {
  58795. attributeNamesOrOptions.push("remapData");
  58796. }
  58797. return attributeNamesOrOptions;
  58798. };
  58799. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  58800. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58801. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  58802. if (isAnimationSheetEnabled) {
  58803. effectCreationOption.push("particlesInfos");
  58804. }
  58805. return effectCreationOption;
  58806. };
  58807. ParticleSystem.prototype._getEffect = function (blendMode) {
  58808. if (this._customEffect) {
  58809. return this._customEffect;
  58810. }
  58811. ;
  58812. var defines = [];
  58813. if (this._scene.clipPlane) {
  58814. defines.push("#define CLIPPLANE");
  58815. }
  58816. if (this._scene.clipPlane2) {
  58817. defines.push("#define CLIPPLANE2");
  58818. }
  58819. if (this._scene.clipPlane3) {
  58820. defines.push("#define CLIPPLANE3");
  58821. }
  58822. if (this._scene.clipPlane4) {
  58823. defines.push("#define CLIPPLANE4");
  58824. }
  58825. if (this._isAnimationSheetEnabled) {
  58826. defines.push("#define ANIMATESHEET");
  58827. }
  58828. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  58829. defines.push("#define BLENDMULTIPLYMODE");
  58830. }
  58831. if (this._useRampGradients) {
  58832. defines.push("#define RAMPGRADIENT");
  58833. }
  58834. if (this._isBillboardBased) {
  58835. defines.push("#define BILLBOARD");
  58836. switch (this.billboardMode) {
  58837. case ParticleSystem.BILLBOARDMODE_Y:
  58838. defines.push("#define BILLBOARDY");
  58839. break;
  58840. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  58841. defines.push("#define BILLBOARDSTRETCHED");
  58842. break;
  58843. case ParticleSystem.BILLBOARDMODE_ALL:
  58844. default:
  58845. break;
  58846. }
  58847. }
  58848. if (this._imageProcessingConfiguration) {
  58849. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  58850. defines.push(this._imageProcessingConfigurationDefines.toString());
  58851. }
  58852. // Effect
  58853. var join = defines.join("\n");
  58854. if (this._cachedDefines !== join) {
  58855. this._cachedDefines = join;
  58856. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  58857. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  58858. var samplers = ["diffuseSampler", "rampSampler"];
  58859. if (BABYLON.ImageProcessingConfiguration) {
  58860. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  58861. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  58862. }
  58863. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  58864. }
  58865. return this._effect;
  58866. };
  58867. /**
  58868. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  58869. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  58870. */
  58871. ParticleSystem.prototype.animate = function (preWarmOnly) {
  58872. var _this = this;
  58873. if (preWarmOnly === void 0) { preWarmOnly = false; }
  58874. if (!this._started)
  58875. return;
  58876. if (!preWarmOnly) {
  58877. // Check
  58878. if (!this.isReady())
  58879. return;
  58880. if (this._currentRenderId === this._scene.getRenderId()) {
  58881. return;
  58882. }
  58883. this._currentRenderId = this._scene.getRenderId();
  58884. }
  58885. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  58886. // Determine the number of particles we need to create
  58887. var newParticles;
  58888. if (this.manualEmitCount > -1) {
  58889. newParticles = this.manualEmitCount;
  58890. this._newPartsExcess = 0;
  58891. this.manualEmitCount = 0;
  58892. }
  58893. else {
  58894. var rate_1 = this.emitRate;
  58895. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  58896. var ratio = this._actualFrame / this.targetStopDuration;
  58897. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  58898. if (currentGradient !== _this._currentEmitRateGradient) {
  58899. _this._currentEmitRate1 = _this._currentEmitRate2;
  58900. _this._currentEmitRate2 = nextGradient.getFactor();
  58901. _this._currentEmitRateGradient = currentGradient;
  58902. }
  58903. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  58904. });
  58905. }
  58906. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  58907. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  58908. }
  58909. if (this._newPartsExcess > 1.0) {
  58910. newParticles += this._newPartsExcess >> 0;
  58911. this._newPartsExcess -= this._newPartsExcess >> 0;
  58912. }
  58913. this._alive = false;
  58914. if (!this._stopped) {
  58915. this._actualFrame += this._scaledUpdateSpeed;
  58916. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  58917. this.stop();
  58918. }
  58919. else {
  58920. newParticles = 0;
  58921. }
  58922. this._update(newParticles);
  58923. // Stopped?
  58924. if (this._stopped) {
  58925. if (!this._alive) {
  58926. this._started = false;
  58927. if (this.onAnimationEnd) {
  58928. this.onAnimationEnd();
  58929. }
  58930. if (this.disposeOnStop) {
  58931. this._scene._toBeDisposed.push(this);
  58932. }
  58933. }
  58934. }
  58935. if (!preWarmOnly) {
  58936. // Update VBO
  58937. var offset = 0;
  58938. for (var index = 0; index < this._particles.length; index++) {
  58939. var particle = this._particles[index];
  58940. this._appendParticleVertices(offset, particle);
  58941. offset += this._useInstancing ? 1 : 4;
  58942. }
  58943. if (this._vertexBuffer) {
  58944. this._vertexBuffer.update(this._vertexData);
  58945. }
  58946. }
  58947. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  58948. this.stop();
  58949. }
  58950. };
  58951. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  58952. this._appendParticleVertex(offset++, particle, 0, 0);
  58953. if (!this._useInstancing) {
  58954. this._appendParticleVertex(offset++, particle, 1, 0);
  58955. this._appendParticleVertex(offset++, particle, 1, 1);
  58956. this._appendParticleVertex(offset++, particle, 0, 1);
  58957. }
  58958. };
  58959. /**
  58960. * Rebuilds the particle system.
  58961. */
  58962. ParticleSystem.prototype.rebuild = function () {
  58963. this._createIndexBuffer();
  58964. if (this._vertexBuffer) {
  58965. this._vertexBuffer._rebuild();
  58966. }
  58967. };
  58968. /**
  58969. * Is this system ready to be used/rendered
  58970. * @return true if the system is ready
  58971. */
  58972. ParticleSystem.prototype.isReady = function () {
  58973. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  58974. return false;
  58975. }
  58976. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  58977. if (!this._getEffect(this.blendMode).isReady()) {
  58978. return false;
  58979. }
  58980. }
  58981. else {
  58982. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  58983. return false;
  58984. }
  58985. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  58986. return false;
  58987. }
  58988. }
  58989. return true;
  58990. };
  58991. ParticleSystem.prototype._render = function (blendMode) {
  58992. var effect = this._getEffect(blendMode);
  58993. var engine = this._scene.getEngine();
  58994. // Render
  58995. engine.enableEffect(effect);
  58996. var viewMatrix = this._scene.getViewMatrix();
  58997. effect.setTexture("diffuseSampler", this.particleTexture);
  58998. effect.setMatrix("view", viewMatrix);
  58999. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  59000. if (this._isAnimationSheetEnabled && this.particleTexture) {
  59001. var baseSize = this.particleTexture.getBaseSize();
  59002. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  59003. }
  59004. effect.setVector2("translationPivot", this.translationPivot);
  59005. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  59006. if (this._isBillboardBased) {
  59007. var camera = this._scene.activeCamera;
  59008. effect.setVector3("eyePosition", camera.globalPosition);
  59009. }
  59010. if (this._rampGradientsTexture) {
  59011. effect.setTexture("rampSampler", this._rampGradientsTexture);
  59012. }
  59013. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  59014. var invView = viewMatrix.clone();
  59015. invView.invert();
  59016. effect.setMatrix("invView", invView);
  59017. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  59018. }
  59019. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  59020. // image processing
  59021. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  59022. this._imageProcessingConfiguration.bind(effect);
  59023. }
  59024. // Draw order
  59025. switch (blendMode) {
  59026. case ParticleSystem.BLENDMODE_ADD:
  59027. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  59028. break;
  59029. case ParticleSystem.BLENDMODE_ONEONE:
  59030. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  59031. break;
  59032. case ParticleSystem.BLENDMODE_STANDARD:
  59033. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  59034. break;
  59035. case ParticleSystem.BLENDMODE_MULTIPLY:
  59036. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  59037. break;
  59038. }
  59039. if (this._useInstancing) {
  59040. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  59041. }
  59042. else {
  59043. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  59044. }
  59045. return this._particles.length;
  59046. };
  59047. /**
  59048. * Renders the particle system in its current state.
  59049. * @returns the current number of particles
  59050. */
  59051. ParticleSystem.prototype.render = function () {
  59052. // Check
  59053. if (!this.isReady() || !this._particles.length) {
  59054. return 0;
  59055. }
  59056. var engine = this._scene.getEngine();
  59057. engine.setState(false);
  59058. if (this.forceDepthWrite) {
  59059. engine.setDepthWrite(true);
  59060. }
  59061. var outparticles = 0;
  59062. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  59063. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  59064. }
  59065. outparticles = this._render(this.blendMode);
  59066. engine.unbindInstanceAttributes();
  59067. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59068. return outparticles;
  59069. };
  59070. /**
  59071. * Disposes the particle system and free the associated resources
  59072. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  59073. */
  59074. ParticleSystem.prototype.dispose = function (disposeTexture) {
  59075. if (disposeTexture === void 0) { disposeTexture = true; }
  59076. if (this._vertexBuffer) {
  59077. this._vertexBuffer.dispose();
  59078. this._vertexBuffer = null;
  59079. }
  59080. if (this._spriteBuffer) {
  59081. this._spriteBuffer.dispose();
  59082. this._spriteBuffer = null;
  59083. }
  59084. if (this._indexBuffer) {
  59085. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  59086. this._indexBuffer = null;
  59087. }
  59088. if (disposeTexture && this.particleTexture) {
  59089. this.particleTexture.dispose();
  59090. this.particleTexture = null;
  59091. }
  59092. if (disposeTexture && this.noiseTexture) {
  59093. this.noiseTexture.dispose();
  59094. this.noiseTexture = null;
  59095. }
  59096. if (this._rampGradientsTexture) {
  59097. this._rampGradientsTexture.dispose();
  59098. this._rampGradientsTexture = null;
  59099. }
  59100. this._removeFromRoot();
  59101. if (this._subEmitters && this._subEmitters.length) {
  59102. for (var index = 0; index < this._subEmitters.length; index++) {
  59103. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  59104. var subEmitter = _a[_i];
  59105. subEmitter.dispose();
  59106. }
  59107. }
  59108. this._subEmitters = [];
  59109. this.subEmitters = [];
  59110. }
  59111. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  59112. this.emitter.dispose(true);
  59113. }
  59114. // Remove from scene
  59115. var index = this._scene.particleSystems.indexOf(this);
  59116. if (index > -1) {
  59117. this._scene.particleSystems.splice(index, 1);
  59118. }
  59119. this._scene._activeParticleSystems.dispose();
  59120. // Callback
  59121. this.onDisposeObservable.notifyObservers(this);
  59122. this.onDisposeObservable.clear();
  59123. this.reset();
  59124. };
  59125. // Clone
  59126. /**
  59127. * Clones the particle system.
  59128. * @param name The name of the cloned object
  59129. * @param newEmitter The new emitter to use
  59130. * @returns the cloned particle system
  59131. */
  59132. ParticleSystem.prototype.clone = function (name, newEmitter) {
  59133. var custom = null;
  59134. var program = null;
  59135. if (this.customShader != null) {
  59136. program = this.customShader;
  59137. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  59138. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  59139. }
  59140. else if (this._customEffect) {
  59141. custom = this._customEffect;
  59142. }
  59143. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  59144. result.customShader = program;
  59145. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  59146. if (newEmitter === undefined) {
  59147. newEmitter = this.emitter;
  59148. }
  59149. result.noiseTexture = this.noiseTexture;
  59150. result.emitter = newEmitter;
  59151. if (this.particleTexture) {
  59152. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  59153. }
  59154. // Clone gradients
  59155. if (this._colorGradients) {
  59156. this._colorGradients.forEach(function (v) {
  59157. result.addColorGradient(v.gradient, v.color1, v.color2);
  59158. });
  59159. }
  59160. if (this._dragGradients) {
  59161. this._dragGradients.forEach(function (v) {
  59162. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  59163. });
  59164. }
  59165. if (this._angularSpeedGradients) {
  59166. this._angularSpeedGradients.forEach(function (v) {
  59167. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  59168. });
  59169. }
  59170. if (this._emitRateGradients) {
  59171. this._emitRateGradients.forEach(function (v) {
  59172. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  59173. });
  59174. }
  59175. if (this._lifeTimeGradients) {
  59176. this._lifeTimeGradients.forEach(function (v) {
  59177. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  59178. });
  59179. }
  59180. if (this._limitVelocityGradients) {
  59181. this._limitVelocityGradients.forEach(function (v) {
  59182. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  59183. });
  59184. }
  59185. if (this._sizeGradients) {
  59186. this._sizeGradients.forEach(function (v) {
  59187. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  59188. });
  59189. }
  59190. if (this._startSizeGradients) {
  59191. this._startSizeGradients.forEach(function (v) {
  59192. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  59193. });
  59194. }
  59195. if (this._velocityGradients) {
  59196. this._velocityGradients.forEach(function (v) {
  59197. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  59198. });
  59199. }
  59200. if (this._rampGradients) {
  59201. this._rampGradients.forEach(function (v) {
  59202. result.addRampGradient(v.gradient, v.color);
  59203. });
  59204. }
  59205. if (this._colorRemapGradients) {
  59206. this._colorRemapGradients.forEach(function (v) {
  59207. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  59208. });
  59209. }
  59210. if (this._alphaRemapGradients) {
  59211. this._alphaRemapGradients.forEach(function (v) {
  59212. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  59213. });
  59214. }
  59215. if (!this.preventAutoStart) {
  59216. result.start();
  59217. }
  59218. return result;
  59219. };
  59220. /**
  59221. * Serializes the particle system to a JSON object.
  59222. * @returns the JSON object
  59223. */
  59224. ParticleSystem.prototype.serialize = function () {
  59225. var serializationObject = {};
  59226. ParticleSystem._Serialize(serializationObject, this);
  59227. serializationObject.textureMask = this.textureMask.asArray();
  59228. serializationObject.customShader = this.customShader;
  59229. serializationObject.preventAutoStart = this.preventAutoStart;
  59230. // SubEmitters
  59231. if (this.subEmitters) {
  59232. serializationObject.subEmitters = [];
  59233. if (!this._subEmitters) {
  59234. this._prepareSubEmitterInternalArray();
  59235. }
  59236. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  59237. var subs = _a[_i];
  59238. var cell = [];
  59239. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  59240. var sub = subs_1[_b];
  59241. cell.push(sub.serialize());
  59242. }
  59243. serializationObject.subEmitters.push(cell);
  59244. }
  59245. }
  59246. return serializationObject;
  59247. };
  59248. /** @hidden */
  59249. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  59250. serializationObject.name = particleSystem.name;
  59251. serializationObject.id = particleSystem.id;
  59252. serializationObject.capacity = particleSystem.getCapacity();
  59253. // Emitter
  59254. if (particleSystem.emitter.position) {
  59255. var emitterMesh = particleSystem.emitter;
  59256. serializationObject.emitterId = emitterMesh.id;
  59257. }
  59258. else {
  59259. var emitterPosition = particleSystem.emitter;
  59260. serializationObject.emitter = emitterPosition.asArray();
  59261. }
  59262. // Emitter
  59263. if (particleSystem.particleEmitterType) {
  59264. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  59265. }
  59266. if (particleSystem.particleTexture) {
  59267. serializationObject.textureName = particleSystem.particleTexture.name;
  59268. serializationObject.invertY = particleSystem.particleTexture._invertY;
  59269. }
  59270. // Animations
  59271. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  59272. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  59273. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  59274. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  59275. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  59276. // Particle system
  59277. serializationObject.startDelay = particleSystem.startDelay;
  59278. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  59279. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  59280. serializationObject.billboardMode = particleSystem.billboardMode;
  59281. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  59282. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  59283. serializationObject.minSize = particleSystem.minSize;
  59284. serializationObject.maxSize = particleSystem.maxSize;
  59285. serializationObject.minScaleX = particleSystem.minScaleX;
  59286. serializationObject.maxScaleX = particleSystem.maxScaleX;
  59287. serializationObject.minScaleY = particleSystem.minScaleY;
  59288. serializationObject.maxScaleY = particleSystem.maxScaleY;
  59289. serializationObject.minEmitPower = particleSystem.minEmitPower;
  59290. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  59291. serializationObject.minLifeTime = particleSystem.minLifeTime;
  59292. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  59293. serializationObject.emitRate = particleSystem.emitRate;
  59294. serializationObject.gravity = particleSystem.gravity.asArray();
  59295. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  59296. serializationObject.color1 = particleSystem.color1.asArray();
  59297. serializationObject.color2 = particleSystem.color2.asArray();
  59298. serializationObject.colorDead = particleSystem.colorDead.asArray();
  59299. serializationObject.updateSpeed = particleSystem.updateSpeed;
  59300. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  59301. serializationObject.blendMode = particleSystem.blendMode;
  59302. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  59303. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  59304. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  59305. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  59306. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  59307. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  59308. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  59309. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  59310. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  59311. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  59312. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  59313. var colorGradients = particleSystem.getColorGradients();
  59314. if (colorGradients) {
  59315. serializationObject.colorGradients = [];
  59316. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  59317. var colorGradient = colorGradients_1[_i];
  59318. var serializedGradient = {
  59319. gradient: colorGradient.gradient,
  59320. color1: colorGradient.color1.asArray()
  59321. };
  59322. if (colorGradient.color2) {
  59323. serializedGradient.color2 = colorGradient.color2.asArray();
  59324. }
  59325. serializationObject.colorGradients.push(serializedGradient);
  59326. }
  59327. }
  59328. var rampGradients = particleSystem.getRampGradients();
  59329. if (rampGradients) {
  59330. serializationObject.rampGradients = [];
  59331. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  59332. var rampGradient = rampGradients_1[_a];
  59333. var serializedGradient = {
  59334. gradient: rampGradient.gradient,
  59335. color: rampGradient.color.asArray()
  59336. };
  59337. serializationObject.rampGradients.push(serializedGradient);
  59338. }
  59339. serializationObject.useRampGradients = particleSystem.useRampGradients;
  59340. }
  59341. var colorRemapGradients = particleSystem.getColorRemapGradients();
  59342. if (colorRemapGradients) {
  59343. serializationObject.colorRemapGradients = [];
  59344. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  59345. var colorRemapGradient = colorRemapGradients_1[_b];
  59346. var serializedGradient = {
  59347. gradient: colorRemapGradient.gradient,
  59348. factor1: colorRemapGradient.factor1
  59349. };
  59350. if (colorRemapGradient.factor2 !== undefined) {
  59351. serializedGradient.factor2 = colorRemapGradient.factor2;
  59352. }
  59353. serializationObject.colorRemapGradients.push(serializedGradient);
  59354. }
  59355. }
  59356. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  59357. if (alphaRemapGradients) {
  59358. serializationObject.alphaRemapGradients = [];
  59359. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  59360. var alphaRemapGradient = alphaRemapGradients_1[_c];
  59361. var serializedGradient = {
  59362. gradient: alphaRemapGradient.gradient,
  59363. factor1: alphaRemapGradient.factor1
  59364. };
  59365. if (alphaRemapGradient.factor2 !== undefined) {
  59366. serializedGradient.factor2 = alphaRemapGradient.factor2;
  59367. }
  59368. serializationObject.alphaRemapGradients.push(serializedGradient);
  59369. }
  59370. }
  59371. var sizeGradients = particleSystem.getSizeGradients();
  59372. if (sizeGradients) {
  59373. serializationObject.sizeGradients = [];
  59374. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  59375. var sizeGradient = sizeGradients_1[_d];
  59376. var serializedGradient = {
  59377. gradient: sizeGradient.gradient,
  59378. factor1: sizeGradient.factor1
  59379. };
  59380. if (sizeGradient.factor2 !== undefined) {
  59381. serializedGradient.factor2 = sizeGradient.factor2;
  59382. }
  59383. serializationObject.sizeGradients.push(serializedGradient);
  59384. }
  59385. }
  59386. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  59387. if (angularSpeedGradients) {
  59388. serializationObject.angularSpeedGradients = [];
  59389. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  59390. var angularSpeedGradient = angularSpeedGradients_1[_e];
  59391. var serializedGradient = {
  59392. gradient: angularSpeedGradient.gradient,
  59393. factor1: angularSpeedGradient.factor1
  59394. };
  59395. if (angularSpeedGradient.factor2 !== undefined) {
  59396. serializedGradient.factor2 = angularSpeedGradient.factor2;
  59397. }
  59398. serializationObject.angularSpeedGradients.push(serializedGradient);
  59399. }
  59400. }
  59401. var velocityGradients = particleSystem.getVelocityGradients();
  59402. if (velocityGradients) {
  59403. serializationObject.velocityGradients = [];
  59404. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  59405. var velocityGradient = velocityGradients_1[_f];
  59406. var serializedGradient = {
  59407. gradient: velocityGradient.gradient,
  59408. factor1: velocityGradient.factor1
  59409. };
  59410. if (velocityGradient.factor2 !== undefined) {
  59411. serializedGradient.factor2 = velocityGradient.factor2;
  59412. }
  59413. serializationObject.velocityGradients.push(serializedGradient);
  59414. }
  59415. }
  59416. var dragGradients = particleSystem.getDragGradients();
  59417. if (dragGradients) {
  59418. serializationObject.dragyGradients = [];
  59419. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  59420. var dragGradient = dragGradients_1[_g];
  59421. var serializedGradient = {
  59422. gradient: dragGradient.gradient,
  59423. factor1: dragGradient.factor1
  59424. };
  59425. if (dragGradient.factor2 !== undefined) {
  59426. serializedGradient.factor2 = dragGradient.factor2;
  59427. }
  59428. serializationObject.dragGradients.push(serializedGradient);
  59429. }
  59430. }
  59431. var emitRateGradients = particleSystem.getEmitRateGradients();
  59432. if (emitRateGradients) {
  59433. serializationObject.emitRateGradients = [];
  59434. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  59435. var emitRateGradient = emitRateGradients_1[_h];
  59436. var serializedGradient = {
  59437. gradient: emitRateGradient.gradient,
  59438. factor1: emitRateGradient.factor1
  59439. };
  59440. if (emitRateGradient.factor2 !== undefined) {
  59441. serializedGradient.factor2 = emitRateGradient.factor2;
  59442. }
  59443. serializationObject.emitRateGradients.push(serializedGradient);
  59444. }
  59445. }
  59446. var startSizeGradients = particleSystem.getStartSizeGradients();
  59447. if (startSizeGradients) {
  59448. serializationObject.startSizeGradients = [];
  59449. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  59450. var startSizeGradient = startSizeGradients_1[_j];
  59451. var serializedGradient = {
  59452. gradient: startSizeGradient.gradient,
  59453. factor1: startSizeGradient.factor1
  59454. };
  59455. if (startSizeGradient.factor2 !== undefined) {
  59456. serializedGradient.factor2 = startSizeGradient.factor2;
  59457. }
  59458. serializationObject.startSizeGradients.push(serializedGradient);
  59459. }
  59460. }
  59461. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  59462. if (lifeTimeGradients) {
  59463. serializationObject.lifeTimeGradients = [];
  59464. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  59465. var lifeTimeGradient = lifeTimeGradients_1[_k];
  59466. var serializedGradient = {
  59467. gradient: lifeTimeGradient.gradient,
  59468. factor1: lifeTimeGradient.factor1
  59469. };
  59470. if (lifeTimeGradient.factor2 !== undefined) {
  59471. serializedGradient.factor2 = lifeTimeGradient.factor2;
  59472. }
  59473. serializationObject.lifeTimeGradients.push(serializedGradient);
  59474. }
  59475. }
  59476. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  59477. if (limitVelocityGradients) {
  59478. serializationObject.limitVelocityGradients = [];
  59479. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  59480. var limitVelocityGradient = limitVelocityGradients_1[_l];
  59481. var serializedGradient = {
  59482. gradient: limitVelocityGradient.gradient,
  59483. factor1: limitVelocityGradient.factor1
  59484. };
  59485. if (limitVelocityGradient.factor2 !== undefined) {
  59486. serializedGradient.factor2 = limitVelocityGradient.factor2;
  59487. }
  59488. serializationObject.limitVelocityGradients.push(serializedGradient);
  59489. }
  59490. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  59491. }
  59492. if (particleSystem.noiseTexture) {
  59493. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  59494. }
  59495. };
  59496. /** @hidden */
  59497. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  59498. // Texture
  59499. if (parsedParticleSystem.textureName) {
  59500. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  59501. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  59502. }
  59503. // Emitter
  59504. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  59505. particleSystem.emitter = BABYLON.Vector3.Zero();
  59506. }
  59507. else if (parsedParticleSystem.emitterId) {
  59508. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  59509. }
  59510. else {
  59511. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  59512. }
  59513. // Misc.
  59514. if (parsedParticleSystem.renderingGroupId !== undefined) {
  59515. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  59516. }
  59517. if (parsedParticleSystem.isBillboardBased !== undefined) {
  59518. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  59519. }
  59520. if (parsedParticleSystem.billboardMode !== undefined) {
  59521. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  59522. }
  59523. // Animations
  59524. if (parsedParticleSystem.animations) {
  59525. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  59526. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  59527. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  59528. }
  59529. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  59530. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  59531. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  59532. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  59533. }
  59534. if (parsedParticleSystem.autoAnimate) {
  59535. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  59536. }
  59537. // Particle system
  59538. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  59539. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  59540. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  59541. particleSystem.minSize = parsedParticleSystem.minSize;
  59542. particleSystem.maxSize = parsedParticleSystem.maxSize;
  59543. if (parsedParticleSystem.minScaleX) {
  59544. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  59545. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  59546. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  59547. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  59548. }
  59549. if (parsedParticleSystem.preWarmCycles !== undefined) {
  59550. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  59551. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  59552. }
  59553. if (parsedParticleSystem.minInitialRotation !== undefined) {
  59554. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  59555. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  59556. }
  59557. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  59558. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  59559. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  59560. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  59561. particleSystem.emitRate = parsedParticleSystem.emitRate;
  59562. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  59563. if (parsedParticleSystem.noiseStrength) {
  59564. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  59565. }
  59566. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  59567. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  59568. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  59569. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  59570. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  59571. particleSystem.blendMode = parsedParticleSystem.blendMode;
  59572. if (parsedParticleSystem.colorGradients) {
  59573. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  59574. var colorGradient = _a[_i];
  59575. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  59576. }
  59577. }
  59578. if (parsedParticleSystem.rampGradients) {
  59579. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  59580. var rampGradient = _c[_b];
  59581. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  59582. }
  59583. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  59584. }
  59585. if (parsedParticleSystem.colorRemapGradients) {
  59586. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  59587. var colorRemapGradient = _e[_d];
  59588. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  59589. }
  59590. }
  59591. if (parsedParticleSystem.alphaRemapGradients) {
  59592. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  59593. var alphaRemapGradient = _g[_f];
  59594. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  59595. }
  59596. }
  59597. if (parsedParticleSystem.sizeGradients) {
  59598. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  59599. var sizeGradient = _j[_h];
  59600. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  59601. }
  59602. }
  59603. if (parsedParticleSystem.sizeGradients) {
  59604. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  59605. var sizeGradient = _l[_k];
  59606. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  59607. }
  59608. }
  59609. if (parsedParticleSystem.angularSpeedGradients) {
  59610. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  59611. var angularSpeedGradient = _o[_m];
  59612. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  59613. }
  59614. }
  59615. if (parsedParticleSystem.velocityGradients) {
  59616. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  59617. var velocityGradient = _q[_p];
  59618. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  59619. }
  59620. }
  59621. if (parsedParticleSystem.dragGradients) {
  59622. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  59623. var dragGradient = _s[_r];
  59624. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  59625. }
  59626. }
  59627. if (parsedParticleSystem.emitRateGradients) {
  59628. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  59629. var emitRateGradient = _u[_t];
  59630. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  59631. }
  59632. }
  59633. if (parsedParticleSystem.startSizeGradients) {
  59634. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  59635. var startSizeGradient = _w[_v];
  59636. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  59637. }
  59638. }
  59639. if (parsedParticleSystem.lifeTimeGradients) {
  59640. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  59641. var lifeTimeGradient = _y[_x];
  59642. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  59643. }
  59644. }
  59645. if (parsedParticleSystem.limitVelocityGradients) {
  59646. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  59647. var limitVelocityGradient = _0[_z];
  59648. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  59649. }
  59650. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  59651. }
  59652. if (parsedParticleSystem.noiseTexture) {
  59653. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  59654. }
  59655. // Emitter
  59656. var emitterType;
  59657. if (parsedParticleSystem.particleEmitterType) {
  59658. switch (parsedParticleSystem.particleEmitterType.type) {
  59659. case "SphereParticleEmitter":
  59660. emitterType = new BABYLON.SphereParticleEmitter();
  59661. break;
  59662. case "SphereDirectedParticleEmitter":
  59663. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  59664. break;
  59665. case "ConeEmitter":
  59666. case "ConeParticleEmitter":
  59667. emitterType = new BABYLON.ConeParticleEmitter();
  59668. break;
  59669. case "CylinderParticleEmitter":
  59670. emitterType = new BABYLON.CylinderParticleEmitter();
  59671. break;
  59672. case "HemisphericParticleEmitter":
  59673. emitterType = new BABYLON.HemisphericParticleEmitter();
  59674. break;
  59675. case "BoxEmitter":
  59676. case "BoxParticleEmitter":
  59677. default:
  59678. emitterType = new BABYLON.BoxParticleEmitter();
  59679. break;
  59680. }
  59681. emitterType.parse(parsedParticleSystem.particleEmitterType);
  59682. }
  59683. else {
  59684. emitterType = new BABYLON.BoxParticleEmitter();
  59685. emitterType.parse(parsedParticleSystem);
  59686. }
  59687. particleSystem.particleEmitterType = emitterType;
  59688. // Animation sheet
  59689. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  59690. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  59691. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  59692. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  59693. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  59694. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  59695. };
  59696. /**
  59697. * Parses a JSON object to create a particle system.
  59698. * @param parsedParticleSystem The JSON object to parse
  59699. * @param scene The scene to create the particle system in
  59700. * @param rootUrl The root url to use to load external dependencies like texture
  59701. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  59702. * @returns the Parsed particle system
  59703. */
  59704. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  59705. if (doNotStart === void 0) { doNotStart = false; }
  59706. var name = parsedParticleSystem.name;
  59707. var custom = null;
  59708. var program = null;
  59709. if (parsedParticleSystem.customShader) {
  59710. program = parsedParticleSystem.customShader;
  59711. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  59712. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  59713. }
  59714. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  59715. particleSystem.customShader = program;
  59716. if (parsedParticleSystem.id) {
  59717. particleSystem.id = parsedParticleSystem.id;
  59718. }
  59719. // SubEmitters
  59720. if (parsedParticleSystem.subEmitters) {
  59721. particleSystem.subEmitters = [];
  59722. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  59723. var cell = _a[_i];
  59724. var cellArray = [];
  59725. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  59726. var sub = cell_1[_b];
  59727. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  59728. }
  59729. particleSystem.subEmitters.push(cellArray);
  59730. }
  59731. }
  59732. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  59733. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  59734. // Auto start
  59735. if (parsedParticleSystem.preventAutoStart) {
  59736. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  59737. }
  59738. if (!doNotStart && !particleSystem.preventAutoStart) {
  59739. particleSystem.start();
  59740. }
  59741. return particleSystem;
  59742. };
  59743. /**
  59744. * Billboard mode will only apply to Y axis
  59745. */
  59746. ParticleSystem.BILLBOARDMODE_Y = 2;
  59747. /**
  59748. * Billboard mode will apply to all axes
  59749. */
  59750. ParticleSystem.BILLBOARDMODE_ALL = 7;
  59751. /**
  59752. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  59753. */
  59754. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  59755. return ParticleSystem;
  59756. }(BABYLON.BaseParticleSystem));
  59757. BABYLON.ParticleSystem = ParticleSystem;
  59758. })(BABYLON || (BABYLON = {}));
  59759. //# sourceMappingURL=babylon.particleSystem.js.map
  59760. var BABYLON;
  59761. (function (BABYLON) {
  59762. /**
  59763. * Particle emitter emitting particles from the inside of a box.
  59764. * It emits the particles randomly between 2 given directions.
  59765. */
  59766. var BoxParticleEmitter = /** @class */ (function () {
  59767. /**
  59768. * Creates a new instance BoxParticleEmitter
  59769. */
  59770. function BoxParticleEmitter() {
  59771. /**
  59772. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59773. */
  59774. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  59775. /**
  59776. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59777. */
  59778. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  59779. /**
  59780. * 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.
  59781. */
  59782. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  59783. /**
  59784. * 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.
  59785. */
  59786. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  59787. }
  59788. /**
  59789. * Called by the particle System when the direction is computed for the created particle.
  59790. * @param worldMatrix is the world matrix of the particle system
  59791. * @param directionToUpdate is the direction vector to update with the result
  59792. * @param particle is the particle we are computed the direction for
  59793. */
  59794. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59795. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59796. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59797. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59798. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59799. };
  59800. /**
  59801. * Called by the particle System when the position is computed for the created particle.
  59802. * @param worldMatrix is the world matrix of the particle system
  59803. * @param positionToUpdate is the position vector to update with the result
  59804. * @param particle is the particle we are computed the position for
  59805. */
  59806. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59807. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  59808. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  59809. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  59810. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  59811. };
  59812. /**
  59813. * Clones the current emitter and returns a copy of it
  59814. * @returns the new emitter
  59815. */
  59816. BoxParticleEmitter.prototype.clone = function () {
  59817. var newOne = new BoxParticleEmitter();
  59818. BABYLON.Tools.DeepCopy(this, newOne);
  59819. return newOne;
  59820. };
  59821. /**
  59822. * Called by the GPUParticleSystem to setup the update shader
  59823. * @param effect defines the update shader
  59824. */
  59825. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  59826. effect.setVector3("direction1", this.direction1);
  59827. effect.setVector3("direction2", this.direction2);
  59828. effect.setVector3("minEmitBox", this.minEmitBox);
  59829. effect.setVector3("maxEmitBox", this.maxEmitBox);
  59830. };
  59831. /**
  59832. * Returns a string to use to update the GPU particles update shader
  59833. * @returns a string containng the defines string
  59834. */
  59835. BoxParticleEmitter.prototype.getEffectDefines = function () {
  59836. return "#define BOXEMITTER";
  59837. };
  59838. /**
  59839. * Returns the string "BoxParticleEmitter"
  59840. * @returns a string containing the class name
  59841. */
  59842. BoxParticleEmitter.prototype.getClassName = function () {
  59843. return "BoxParticleEmitter";
  59844. };
  59845. /**
  59846. * Serializes the particle system to a JSON object.
  59847. * @returns the JSON object
  59848. */
  59849. BoxParticleEmitter.prototype.serialize = function () {
  59850. var serializationObject = {};
  59851. serializationObject.type = this.getClassName();
  59852. serializationObject.direction1 = this.direction1.asArray();
  59853. serializationObject.direction2 = this.direction2.asArray();
  59854. serializationObject.minEmitBox = this.minEmitBox.asArray();
  59855. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  59856. return serializationObject;
  59857. };
  59858. /**
  59859. * Parse properties from a JSON object
  59860. * @param serializationObject defines the JSON object
  59861. */
  59862. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  59863. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  59864. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  59865. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  59866. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  59867. };
  59868. return BoxParticleEmitter;
  59869. }());
  59870. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  59871. })(BABYLON || (BABYLON = {}));
  59872. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  59873. var BABYLON;
  59874. (function (BABYLON) {
  59875. /**
  59876. * Particle emitter emitting particles from the inside of a cylinder.
  59877. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  59878. */
  59879. var CylinderParticleEmitter = /** @class */ (function () {
  59880. /**
  59881. * Creates a new instance CylinderParticleEmitter
  59882. * @param radius the radius of the emission cylinder (1 by default)
  59883. * @param height the height of the emission cylinder (1 by default)
  59884. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59885. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  59886. */
  59887. function CylinderParticleEmitter(
  59888. /**
  59889. * The radius of the emission cylinder.
  59890. */
  59891. radius,
  59892. /**
  59893. * The height of the emission cylinder.
  59894. */
  59895. height,
  59896. /**
  59897. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  59898. */
  59899. radiusRange,
  59900. /**
  59901. * How much to randomize the particle direction [0-1].
  59902. */
  59903. directionRandomizer) {
  59904. if (radius === void 0) { radius = 1; }
  59905. if (height === void 0) { height = 1; }
  59906. if (radiusRange === void 0) { radiusRange = 1; }
  59907. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59908. this.radius = radius;
  59909. this.height = height;
  59910. this.radiusRange = radiusRange;
  59911. this.directionRandomizer = directionRandomizer;
  59912. }
  59913. /**
  59914. * Called by the particle System when the direction is computed for the created particle.
  59915. * @param worldMatrix is the world matrix of the particle system
  59916. * @param directionToUpdate is the direction vector to update with the result
  59917. * @param particle is the particle we are computed the direction for
  59918. */
  59919. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59920. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59921. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  59922. var angle = Math.atan2(direction.x, direction.z);
  59923. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  59924. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  59925. direction.x = Math.sin(angle);
  59926. direction.z = Math.cos(angle);
  59927. direction.normalize();
  59928. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59929. };
  59930. /**
  59931. * Called by the particle System when the position is computed for the created particle.
  59932. * @param worldMatrix is the world matrix of the particle system
  59933. * @param positionToUpdate is the position vector to update with the result
  59934. * @param particle is the particle we are computed the position for
  59935. */
  59936. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59937. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  59938. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  59939. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  59940. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  59941. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  59942. var xPos = positionRadius * Math.cos(angle);
  59943. var zPos = positionRadius * Math.sin(angle);
  59944. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  59945. };
  59946. /**
  59947. * Clones the current emitter and returns a copy of it
  59948. * @returns the new emitter
  59949. */
  59950. CylinderParticleEmitter.prototype.clone = function () {
  59951. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  59952. BABYLON.Tools.DeepCopy(this, newOne);
  59953. return newOne;
  59954. };
  59955. /**
  59956. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  59957. * @param effect defines the update shader
  59958. */
  59959. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  59960. effect.setFloat("radius", this.radius);
  59961. effect.setFloat("height", this.height);
  59962. effect.setFloat("radiusRange", this.radiusRange);
  59963. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59964. };
  59965. /**
  59966. * Returns a string to use to update the GPU particles update shader
  59967. * @returns a string containng the defines string
  59968. */
  59969. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  59970. return "#define CYLINDEREMITTER";
  59971. };
  59972. /**
  59973. * Returns the string "CylinderParticleEmitter"
  59974. * @returns a string containing the class name
  59975. */
  59976. CylinderParticleEmitter.prototype.getClassName = function () {
  59977. return "CylinderParticleEmitter";
  59978. };
  59979. /**
  59980. * Serializes the particle system to a JSON object.
  59981. * @returns the JSON object
  59982. */
  59983. CylinderParticleEmitter.prototype.serialize = function () {
  59984. var serializationObject = {};
  59985. serializationObject.type = this.getClassName();
  59986. serializationObject.radius = this.radius;
  59987. serializationObject.height = this.height;
  59988. serializationObject.radiusRange = this.radiusRange;
  59989. serializationObject.directionRandomizer = this.directionRandomizer;
  59990. return serializationObject;
  59991. };
  59992. /**
  59993. * Parse properties from a JSON object
  59994. * @param serializationObject defines the JSON object
  59995. */
  59996. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  59997. this.radius = serializationObject.radius;
  59998. this.height = serializationObject.height;
  59999. this.radiusRange = serializationObject.radiusRange;
  60000. this.directionRandomizer = serializationObject.directionRandomizer;
  60001. };
  60002. return CylinderParticleEmitter;
  60003. }());
  60004. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  60005. /**
  60006. * Particle emitter emitting particles from the inside of a cylinder.
  60007. * It emits the particles randomly between two vectors.
  60008. */
  60009. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  60010. __extends(CylinderDirectedParticleEmitter, _super);
  60011. /**
  60012. * Creates a new instance CylinderDirectedParticleEmitter
  60013. * @param radius the radius of the emission cylinder (1 by default)
  60014. * @param height the height of the emission cylinder (1 by default)
  60015. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60016. * @param direction1 the min limit of the emission direction (up vector by default)
  60017. * @param direction2 the max limit of the emission direction (up vector by default)
  60018. */
  60019. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  60020. /**
  60021. * The min limit of the emission direction.
  60022. */
  60023. direction1,
  60024. /**
  60025. * The max limit of the emission direction.
  60026. */
  60027. direction2) {
  60028. if (radius === void 0) { radius = 1; }
  60029. if (height === void 0) { height = 1; }
  60030. if (radiusRange === void 0) { radiusRange = 1; }
  60031. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  60032. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  60033. var _this = _super.call(this, radius, height, radiusRange) || this;
  60034. _this.direction1 = direction1;
  60035. _this.direction2 = direction2;
  60036. return _this;
  60037. }
  60038. /**
  60039. * Called by the particle System when the direction is computed for the created particle.
  60040. * @param worldMatrix is the world matrix of the particle system
  60041. * @param directionToUpdate is the direction vector to update with the result
  60042. * @param particle is the particle we are computed the direction for
  60043. */
  60044. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60045. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60046. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60047. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60048. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60049. };
  60050. /**
  60051. * Clones the current emitter and returns a copy of it
  60052. * @returns the new emitter
  60053. */
  60054. CylinderDirectedParticleEmitter.prototype.clone = function () {
  60055. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  60056. BABYLON.Tools.DeepCopy(this, newOne);
  60057. return newOne;
  60058. };
  60059. /**
  60060. * Called by the GPUParticleSystem to setup the update shader
  60061. * @param effect defines the update shader
  60062. */
  60063. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  60064. effect.setFloat("radius", this.radius);
  60065. effect.setFloat("height", this.height);
  60066. effect.setFloat("radiusRange", this.radiusRange);
  60067. effect.setVector3("direction1", this.direction1);
  60068. effect.setVector3("direction2", this.direction2);
  60069. };
  60070. /**
  60071. * Returns a string to use to update the GPU particles update shader
  60072. * @returns a string containng the defines string
  60073. */
  60074. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  60075. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  60076. };
  60077. /**
  60078. * Returns the string "CylinderDirectedParticleEmitter"
  60079. * @returns a string containing the class name
  60080. */
  60081. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  60082. return "CylinderDirectedParticleEmitter";
  60083. };
  60084. /**
  60085. * Serializes the particle system to a JSON object.
  60086. * @returns the JSON object
  60087. */
  60088. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  60089. var serializationObject = _super.prototype.serialize.call(this);
  60090. serializationObject.direction1 = this.direction1.asArray();
  60091. serializationObject.direction2 = this.direction2.asArray();
  60092. return serializationObject;
  60093. };
  60094. /**
  60095. * Parse properties from a JSON object
  60096. * @param serializationObject defines the JSON object
  60097. */
  60098. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  60099. _super.prototype.parse.call(this, serializationObject);
  60100. this.direction1.copyFrom(serializationObject.direction1);
  60101. this.direction2.copyFrom(serializationObject.direction2);
  60102. };
  60103. return CylinderDirectedParticleEmitter;
  60104. }(CylinderParticleEmitter));
  60105. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  60106. })(BABYLON || (BABYLON = {}));
  60107. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  60108. var BABYLON;
  60109. (function (BABYLON) {
  60110. /**
  60111. * Particle emitter emitting particles from the inside of a cone.
  60112. * It emits the particles alongside the cone volume from the base to the particle.
  60113. * The emission direction might be randomized.
  60114. */
  60115. var ConeParticleEmitter = /** @class */ (function () {
  60116. /**
  60117. * Creates a new instance ConeParticleEmitter
  60118. * @param radius the radius of the emission cone (1 by default)
  60119. * @param angles the cone base angle (PI by default)
  60120. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  60121. */
  60122. function ConeParticleEmitter(radius, angle,
  60123. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  60124. directionRandomizer) {
  60125. if (radius === void 0) { radius = 1; }
  60126. if (angle === void 0) { angle = Math.PI; }
  60127. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60128. this.directionRandomizer = directionRandomizer;
  60129. /**
  60130. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  60131. */
  60132. this.radiusRange = 1;
  60133. /**
  60134. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  60135. */
  60136. this.heightRange = 1;
  60137. /**
  60138. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  60139. */
  60140. this.emitFromSpawnPointOnly = false;
  60141. this.angle = angle;
  60142. this.radius = radius;
  60143. }
  60144. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  60145. /**
  60146. * Gets or sets the radius of the emission cone
  60147. */
  60148. get: function () {
  60149. return this._radius;
  60150. },
  60151. set: function (value) {
  60152. this._radius = value;
  60153. this._buildHeight();
  60154. },
  60155. enumerable: true,
  60156. configurable: true
  60157. });
  60158. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  60159. /**
  60160. * Gets or sets the angle of the emission cone
  60161. */
  60162. get: function () {
  60163. return this._angle;
  60164. },
  60165. set: function (value) {
  60166. this._angle = value;
  60167. this._buildHeight();
  60168. },
  60169. enumerable: true,
  60170. configurable: true
  60171. });
  60172. ConeParticleEmitter.prototype._buildHeight = function () {
  60173. if (this._angle !== 0) {
  60174. this._height = this._radius / Math.tan(this._angle / 2);
  60175. }
  60176. else {
  60177. this._height = 1;
  60178. }
  60179. };
  60180. /**
  60181. * Called by the particle System when the direction is computed for the created particle.
  60182. * @param worldMatrix is the world matrix of the particle system
  60183. * @param directionToUpdate is the direction vector to update with the result
  60184. * @param particle is the particle we are computed the direction for
  60185. */
  60186. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60187. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  60188. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  60189. }
  60190. else {
  60191. // measure the direction Vector from the emitter to the particle.
  60192. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60193. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60194. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60195. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60196. direction.x += randX;
  60197. direction.y += randY;
  60198. direction.z += randZ;
  60199. direction.normalize();
  60200. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60201. }
  60202. };
  60203. /**
  60204. * Called by the particle System when the position is computed for the created particle.
  60205. * @param worldMatrix is the world matrix of the particle system
  60206. * @param positionToUpdate is the position vector to update with the result
  60207. * @param particle is the particle we are computed the position for
  60208. */
  60209. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60210. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  60211. var h;
  60212. if (!this.emitFromSpawnPointOnly) {
  60213. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  60214. // Better distribution in a cone at normal angles.
  60215. h = 1 - h * h;
  60216. }
  60217. else {
  60218. h = 0.0001;
  60219. }
  60220. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  60221. radius = radius * h;
  60222. var randX = radius * Math.sin(s);
  60223. var randZ = radius * Math.cos(s);
  60224. var randY = h * this._height;
  60225. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  60226. };
  60227. /**
  60228. * Clones the current emitter and returns a copy of it
  60229. * @returns the new emitter
  60230. */
  60231. ConeParticleEmitter.prototype.clone = function () {
  60232. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  60233. BABYLON.Tools.DeepCopy(this, newOne);
  60234. return newOne;
  60235. };
  60236. /**
  60237. * Called by the GPUParticleSystem to setup the update shader
  60238. * @param effect defines the update shader
  60239. */
  60240. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  60241. effect.setFloat2("radius", this._radius, this.radiusRange);
  60242. effect.setFloat("coneAngle", this._angle);
  60243. effect.setFloat2("height", this._height, this.heightRange);
  60244. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60245. };
  60246. /**
  60247. * Returns a string to use to update the GPU particles update shader
  60248. * @returns a string containng the defines string
  60249. */
  60250. ConeParticleEmitter.prototype.getEffectDefines = function () {
  60251. var defines = "#define CONEEMITTER";
  60252. if (this.emitFromSpawnPointOnly) {
  60253. defines += "\n#define CONEEMITTERSPAWNPOINT";
  60254. }
  60255. return defines;
  60256. };
  60257. /**
  60258. * Returns the string "ConeParticleEmitter"
  60259. * @returns a string containing the class name
  60260. */
  60261. ConeParticleEmitter.prototype.getClassName = function () {
  60262. return "ConeParticleEmitter";
  60263. };
  60264. /**
  60265. * Serializes the particle system to a JSON object.
  60266. * @returns the JSON object
  60267. */
  60268. ConeParticleEmitter.prototype.serialize = function () {
  60269. var serializationObject = {};
  60270. serializationObject.type = this.getClassName();
  60271. serializationObject.radius = this._radius;
  60272. serializationObject.angle = this._angle;
  60273. serializationObject.directionRandomizer = this.directionRandomizer;
  60274. return serializationObject;
  60275. };
  60276. /**
  60277. * Parse properties from a JSON object
  60278. * @param serializationObject defines the JSON object
  60279. */
  60280. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  60281. this.radius = serializationObject.radius;
  60282. this.angle = serializationObject.angle;
  60283. this.directionRandomizer = serializationObject.directionRandomizer;
  60284. };
  60285. return ConeParticleEmitter;
  60286. }());
  60287. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  60288. })(BABYLON || (BABYLON = {}));
  60289. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  60290. var BABYLON;
  60291. (function (BABYLON) {
  60292. /**
  60293. * Particle emitter emitting particles from the inside of a sphere.
  60294. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  60295. */
  60296. var SphereParticleEmitter = /** @class */ (function () {
  60297. /**
  60298. * Creates a new instance SphereParticleEmitter
  60299. * @param radius the radius of the emission sphere (1 by default)
  60300. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60301. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  60302. */
  60303. function SphereParticleEmitter(
  60304. /**
  60305. * The radius of the emission sphere.
  60306. */
  60307. radius,
  60308. /**
  60309. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  60310. */
  60311. radiusRange,
  60312. /**
  60313. * How much to randomize the particle direction [0-1].
  60314. */
  60315. directionRandomizer) {
  60316. if (radius === void 0) { radius = 1; }
  60317. if (radiusRange === void 0) { radiusRange = 1; }
  60318. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60319. this.radius = radius;
  60320. this.radiusRange = radiusRange;
  60321. this.directionRandomizer = directionRandomizer;
  60322. }
  60323. /**
  60324. * Called by the particle System when the direction is computed for the created particle.
  60325. * @param worldMatrix is the world matrix of the particle system
  60326. * @param directionToUpdate is the direction vector to update with the result
  60327. * @param particle is the particle we are computed the direction for
  60328. */
  60329. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60330. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60331. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60332. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60333. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60334. direction.x += randX;
  60335. direction.y += randY;
  60336. direction.z += randZ;
  60337. direction.normalize();
  60338. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60339. };
  60340. /**
  60341. * Called by the particle System when the position is computed for the created particle.
  60342. * @param worldMatrix is the world matrix of the particle system
  60343. * @param positionToUpdate is the position vector to update with the result
  60344. * @param particle is the particle we are computed the position for
  60345. */
  60346. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60347. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  60348. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  60349. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  60350. var theta = Math.acos(2 * v - 1);
  60351. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  60352. var randY = randRadius * Math.cos(theta);
  60353. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  60354. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  60355. };
  60356. /**
  60357. * Clones the current emitter and returns a copy of it
  60358. * @returns the new emitter
  60359. */
  60360. SphereParticleEmitter.prototype.clone = function () {
  60361. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  60362. BABYLON.Tools.DeepCopy(this, newOne);
  60363. return newOne;
  60364. };
  60365. /**
  60366. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60367. * @param effect defines the update shader
  60368. */
  60369. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  60370. effect.setFloat("radius", this.radius);
  60371. effect.setFloat("radiusRange", this.radiusRange);
  60372. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60373. };
  60374. /**
  60375. * Returns a string to use to update the GPU particles update shader
  60376. * @returns a string containng the defines string
  60377. */
  60378. SphereParticleEmitter.prototype.getEffectDefines = function () {
  60379. return "#define SPHEREEMITTER";
  60380. };
  60381. /**
  60382. * Returns the string "SphereParticleEmitter"
  60383. * @returns a string containing the class name
  60384. */
  60385. SphereParticleEmitter.prototype.getClassName = function () {
  60386. return "SphereParticleEmitter";
  60387. };
  60388. /**
  60389. * Serializes the particle system to a JSON object.
  60390. * @returns the JSON object
  60391. */
  60392. SphereParticleEmitter.prototype.serialize = function () {
  60393. var serializationObject = {};
  60394. serializationObject.type = this.getClassName();
  60395. serializationObject.radius = this.radius;
  60396. serializationObject.radiusRange = this.radiusRange;
  60397. serializationObject.directionRandomizer = this.directionRandomizer;
  60398. return serializationObject;
  60399. };
  60400. /**
  60401. * Parse properties from a JSON object
  60402. * @param serializationObject defines the JSON object
  60403. */
  60404. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  60405. this.radius = serializationObject.radius;
  60406. this.radiusRange = serializationObject.radiusRange;
  60407. this.directionRandomizer = serializationObject.directionRandomizer;
  60408. };
  60409. return SphereParticleEmitter;
  60410. }());
  60411. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  60412. /**
  60413. * Particle emitter emitting particles from the inside of a sphere.
  60414. * It emits the particles randomly between two vectors.
  60415. */
  60416. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  60417. __extends(SphereDirectedParticleEmitter, _super);
  60418. /**
  60419. * Creates a new instance SphereDirectedParticleEmitter
  60420. * @param radius the radius of the emission sphere (1 by default)
  60421. * @param direction1 the min limit of the emission direction (up vector by default)
  60422. * @param direction2 the max limit of the emission direction (up vector by default)
  60423. */
  60424. function SphereDirectedParticleEmitter(radius,
  60425. /**
  60426. * The min limit of the emission direction.
  60427. */
  60428. direction1,
  60429. /**
  60430. * The max limit of the emission direction.
  60431. */
  60432. direction2) {
  60433. if (radius === void 0) { radius = 1; }
  60434. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  60435. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  60436. var _this = _super.call(this, radius) || this;
  60437. _this.direction1 = direction1;
  60438. _this.direction2 = direction2;
  60439. return _this;
  60440. }
  60441. /**
  60442. * Called by the particle System when the direction is computed for the created particle.
  60443. * @param worldMatrix is the world matrix of the particle system
  60444. * @param directionToUpdate is the direction vector to update with the result
  60445. * @param particle is the particle we are computed the direction for
  60446. */
  60447. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60448. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60449. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60450. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60451. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60452. };
  60453. /**
  60454. * Clones the current emitter and returns a copy of it
  60455. * @returns the new emitter
  60456. */
  60457. SphereDirectedParticleEmitter.prototype.clone = function () {
  60458. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  60459. BABYLON.Tools.DeepCopy(this, newOne);
  60460. return newOne;
  60461. };
  60462. /**
  60463. * Called by the GPUParticleSystem to setup the update shader
  60464. * @param effect defines the update shader
  60465. */
  60466. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  60467. effect.setFloat("radius", this.radius);
  60468. effect.setFloat("radiusRange", this.radiusRange);
  60469. effect.setVector3("direction1", this.direction1);
  60470. effect.setVector3("direction2", this.direction2);
  60471. };
  60472. /**
  60473. * Returns a string to use to update the GPU particles update shader
  60474. * @returns a string containng the defines string
  60475. */
  60476. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  60477. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  60478. };
  60479. /**
  60480. * Returns the string "SphereDirectedParticleEmitter"
  60481. * @returns a string containing the class name
  60482. */
  60483. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  60484. return "SphereDirectedParticleEmitter";
  60485. };
  60486. /**
  60487. * Serializes the particle system to a JSON object.
  60488. * @returns the JSON object
  60489. */
  60490. SphereDirectedParticleEmitter.prototype.serialize = function () {
  60491. var serializationObject = _super.prototype.serialize.call(this);
  60492. serializationObject.direction1 = this.direction1.asArray();
  60493. serializationObject.direction2 = this.direction2.asArray();
  60494. return serializationObject;
  60495. };
  60496. /**
  60497. * Parse properties from a JSON object
  60498. * @param serializationObject defines the JSON object
  60499. */
  60500. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  60501. _super.prototype.parse.call(this, serializationObject);
  60502. this.direction1.copyFrom(serializationObject.direction1);
  60503. this.direction2.copyFrom(serializationObject.direction2);
  60504. };
  60505. return SphereDirectedParticleEmitter;
  60506. }(SphereParticleEmitter));
  60507. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  60508. })(BABYLON || (BABYLON = {}));
  60509. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  60510. var BABYLON;
  60511. (function (BABYLON) {
  60512. /**
  60513. * Particle emitter emitting particles from the inside of a hemisphere.
  60514. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  60515. */
  60516. var HemisphericParticleEmitter = /** @class */ (function () {
  60517. /**
  60518. * Creates a new instance HemisphericParticleEmitter
  60519. * @param radius the radius of the emission hemisphere (1 by default)
  60520. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60521. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  60522. */
  60523. function HemisphericParticleEmitter(
  60524. /**
  60525. * The radius of the emission hemisphere.
  60526. */
  60527. radius,
  60528. /**
  60529. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  60530. */
  60531. radiusRange,
  60532. /**
  60533. * How much to randomize the particle direction [0-1].
  60534. */
  60535. directionRandomizer) {
  60536. if (radius === void 0) { radius = 1; }
  60537. if (radiusRange === void 0) { radiusRange = 1; }
  60538. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60539. this.radius = radius;
  60540. this.radiusRange = radiusRange;
  60541. this.directionRandomizer = directionRandomizer;
  60542. }
  60543. /**
  60544. * Called by the particle System when the direction is computed for the created particle.
  60545. * @param worldMatrix is the world matrix of the particle system
  60546. * @param directionToUpdate is the direction vector to update with the result
  60547. * @param particle is the particle we are computed the direction for
  60548. */
  60549. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60550. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60551. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60552. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60553. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60554. direction.x += randX;
  60555. direction.y += randY;
  60556. direction.z += randZ;
  60557. direction.normalize();
  60558. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60559. };
  60560. /**
  60561. * Called by the particle System when the position is computed for the created particle.
  60562. * @param worldMatrix is the world matrix of the particle system
  60563. * @param positionToUpdate is the position vector to update with the result
  60564. * @param particle is the particle we are computed the position for
  60565. */
  60566. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60567. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  60568. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  60569. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  60570. var theta = Math.acos(2 * v - 1);
  60571. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  60572. var randY = randRadius * Math.cos(theta);
  60573. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  60574. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  60575. };
  60576. /**
  60577. * Clones the current emitter and returns a copy of it
  60578. * @returns the new emitter
  60579. */
  60580. HemisphericParticleEmitter.prototype.clone = function () {
  60581. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  60582. BABYLON.Tools.DeepCopy(this, newOne);
  60583. return newOne;
  60584. };
  60585. /**
  60586. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60587. * @param effect defines the update shader
  60588. */
  60589. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  60590. effect.setFloat("radius", this.radius);
  60591. effect.setFloat("radiusRange", this.radiusRange);
  60592. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60593. };
  60594. /**
  60595. * Returns a string to use to update the GPU particles update shader
  60596. * @returns a string containng the defines string
  60597. */
  60598. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  60599. return "#define HEMISPHERICEMITTER";
  60600. };
  60601. /**
  60602. * Returns the string "HemisphericParticleEmitter"
  60603. * @returns a string containing the class name
  60604. */
  60605. HemisphericParticleEmitter.prototype.getClassName = function () {
  60606. return "HemisphericParticleEmitter";
  60607. };
  60608. /**
  60609. * Serializes the particle system to a JSON object.
  60610. * @returns the JSON object
  60611. */
  60612. HemisphericParticleEmitter.prototype.serialize = function () {
  60613. var serializationObject = {};
  60614. serializationObject.type = this.getClassName();
  60615. serializationObject.radius = this.radius;
  60616. serializationObject.radiusRange = this.radiusRange;
  60617. serializationObject.directionRandomizer = this.directionRandomizer;
  60618. return serializationObject;
  60619. };
  60620. /**
  60621. * Parse properties from a JSON object
  60622. * @param serializationObject defines the JSON object
  60623. */
  60624. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  60625. this.radius = serializationObject.radius;
  60626. this.radiusRange = serializationObject.radiusRange;
  60627. this.directionRandomizer = serializationObject.directionRandomizer;
  60628. };
  60629. return HemisphericParticleEmitter;
  60630. }());
  60631. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  60632. })(BABYLON || (BABYLON = {}));
  60633. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  60634. var BABYLON;
  60635. (function (BABYLON) {
  60636. /**
  60637. * Particle emitter emitting particles from a point.
  60638. * It emits the particles randomly between 2 given directions.
  60639. */
  60640. var PointParticleEmitter = /** @class */ (function () {
  60641. /**
  60642. * Creates a new instance PointParticleEmitter
  60643. */
  60644. function PointParticleEmitter() {
  60645. /**
  60646. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60647. */
  60648. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  60649. /**
  60650. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60651. */
  60652. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  60653. }
  60654. /**
  60655. * Called by the particle System when the direction is computed for the created particle.
  60656. * @param worldMatrix is the world matrix of the particle system
  60657. * @param directionToUpdate is the direction vector to update with the result
  60658. * @param particle is the particle we are computed the direction for
  60659. */
  60660. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60661. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60662. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60663. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60664. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60665. };
  60666. /**
  60667. * Called by the particle System when the position is computed for the created particle.
  60668. * @param worldMatrix is the world matrix of the particle system
  60669. * @param positionToUpdate is the position vector to update with the result
  60670. * @param particle is the particle we are computed the position for
  60671. */
  60672. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60673. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  60674. };
  60675. /**
  60676. * Clones the current emitter and returns a copy of it
  60677. * @returns the new emitter
  60678. */
  60679. PointParticleEmitter.prototype.clone = function () {
  60680. var newOne = new PointParticleEmitter();
  60681. BABYLON.Tools.DeepCopy(this, newOne);
  60682. return newOne;
  60683. };
  60684. /**
  60685. * Called by the GPUParticleSystem to setup the update shader
  60686. * @param effect defines the update shader
  60687. */
  60688. PointParticleEmitter.prototype.applyToShader = function (effect) {
  60689. effect.setVector3("direction1", this.direction1);
  60690. effect.setVector3("direction2", this.direction2);
  60691. };
  60692. /**
  60693. * Returns a string to use to update the GPU particles update shader
  60694. * @returns a string containng the defines string
  60695. */
  60696. PointParticleEmitter.prototype.getEffectDefines = function () {
  60697. return "#define POINTEMITTER";
  60698. };
  60699. /**
  60700. * Returns the string "PointParticleEmitter"
  60701. * @returns a string containing the class name
  60702. */
  60703. PointParticleEmitter.prototype.getClassName = function () {
  60704. return "PointParticleEmitter";
  60705. };
  60706. /**
  60707. * Serializes the particle system to a JSON object.
  60708. * @returns the JSON object
  60709. */
  60710. PointParticleEmitter.prototype.serialize = function () {
  60711. var serializationObject = {};
  60712. serializationObject.type = this.getClassName();
  60713. serializationObject.direction1 = this.direction1.asArray();
  60714. serializationObject.direction2 = this.direction2.asArray();
  60715. return serializationObject;
  60716. };
  60717. /**
  60718. * Parse properties from a JSON object
  60719. * @param serializationObject defines the JSON object
  60720. */
  60721. PointParticleEmitter.prototype.parse = function (serializationObject) {
  60722. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  60723. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  60724. };
  60725. return PointParticleEmitter;
  60726. }());
  60727. BABYLON.PointParticleEmitter = PointParticleEmitter;
  60728. })(BABYLON || (BABYLON = {}));
  60729. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  60730. var BABYLON;
  60731. (function (BABYLON) {
  60732. // Adds the parsers to the scene parsers.
  60733. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  60734. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  60735. if (!individualParser) {
  60736. return;
  60737. }
  60738. // Particles Systems
  60739. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60740. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60741. var parsedParticleSystem = parsedData.particleSystems[index];
  60742. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  60743. }
  60744. }
  60745. });
  60746. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  60747. if (parsedParticleSystem.activeParticleCount) {
  60748. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60749. return ps;
  60750. }
  60751. else {
  60752. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60753. return ps;
  60754. }
  60755. });
  60756. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  60757. if (uniformsNames === void 0) { uniformsNames = []; }
  60758. if (samplers === void 0) { samplers = []; }
  60759. if (defines === void 0) { defines = ""; }
  60760. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  60761. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  60762. if (defines.indexOf(" BILLBOARD") === -1) {
  60763. defines += "\n#define BILLBOARD\n";
  60764. }
  60765. if (samplers.indexOf("diffuseSampler") === -1) {
  60766. samplers.push("diffuseSampler");
  60767. }
  60768. return this.createEffect({
  60769. vertex: "particles",
  60770. fragmentElement: fragmentName
  60771. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  60772. };
  60773. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  60774. var results = new Array();
  60775. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  60776. var particleSystem = this.getScene().particleSystems[index];
  60777. if (particleSystem.emitter === this) {
  60778. results.push(particleSystem);
  60779. }
  60780. }
  60781. return results;
  60782. };
  60783. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  60784. var results = new Array();
  60785. var descendants = this.getDescendants();
  60786. descendants.push(this);
  60787. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  60788. var particleSystem = this.getScene().particleSystems[index];
  60789. var emitter = particleSystem.emitter;
  60790. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  60791. results.push(particleSystem);
  60792. }
  60793. }
  60794. return results;
  60795. };
  60796. })(BABYLON || (BABYLON = {}));
  60797. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  60798. var BABYLON;
  60799. (function (BABYLON) {
  60800. /**
  60801. * Type of sub emitter
  60802. */
  60803. var SubEmitterType;
  60804. (function (SubEmitterType) {
  60805. /**
  60806. * Attached to the particle over it's lifetime
  60807. */
  60808. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  60809. /**
  60810. * Created when the particle dies
  60811. */
  60812. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  60813. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  60814. /**
  60815. * Sub emitter class used to emit particles from an existing particle
  60816. */
  60817. var SubEmitter = /** @class */ (function () {
  60818. /**
  60819. * Creates a sub emitter
  60820. * @param particleSystem the particle system to be used by the sub emitter
  60821. */
  60822. function SubEmitter(
  60823. /**
  60824. * the particle system to be used by the sub emitter
  60825. */
  60826. particleSystem) {
  60827. this.particleSystem = particleSystem;
  60828. /**
  60829. * Type of the submitter (Default: END)
  60830. */
  60831. this.type = SubEmitterType.END;
  60832. /**
  60833. * 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)
  60834. * Note: This only is supported when using an emitter of type Mesh
  60835. */
  60836. this.inheritDirection = false;
  60837. /**
  60838. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  60839. */
  60840. this.inheritedVelocityAmount = 0;
  60841. }
  60842. /**
  60843. * Clones the sub emitter
  60844. * @returns the cloned sub emitter
  60845. */
  60846. SubEmitter.prototype.clone = function () {
  60847. // Clone particle system
  60848. var emitter = this.particleSystem.emitter;
  60849. if (!emitter) {
  60850. emitter = new BABYLON.Vector3();
  60851. }
  60852. else if (emitter instanceof BABYLON.Vector3) {
  60853. emitter = emitter.clone();
  60854. }
  60855. else if (emitter instanceof BABYLON.AbstractMesh) {
  60856. emitter = new BABYLON.Mesh("", emitter.getScene());
  60857. emitter.isVisible = false;
  60858. }
  60859. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  60860. // Clone properties
  60861. clone.type = this.type;
  60862. clone.inheritDirection = this.inheritDirection;
  60863. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  60864. clone.particleSystem._disposeEmitterOnDispose = true;
  60865. clone.particleSystem.disposeOnStop = true;
  60866. return clone;
  60867. };
  60868. /**
  60869. * Serialize current object to a JSON object
  60870. * @returns the serialized object
  60871. */
  60872. SubEmitter.prototype.serialize = function () {
  60873. var serializationObject = {};
  60874. serializationObject.type = this.type;
  60875. serializationObject.inheritDirection = this.inheritDirection;
  60876. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  60877. serializationObject.particleSystem = this.particleSystem.serialize();
  60878. return serializationObject;
  60879. };
  60880. /**
  60881. * Creates a new SubEmitter from a serialized JSON version
  60882. * @param serializationObject defines the JSON object to read from
  60883. * @param scene defines the hosting scene
  60884. * @param rootUrl defines the rootUrl for data loading
  60885. * @returns a new SubEmitter
  60886. */
  60887. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  60888. var system = serializationObject.particleSystem;
  60889. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  60890. subEmitter.type = serializationObject.type;
  60891. subEmitter.inheritDirection = serializationObject.inheritDirection;
  60892. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  60893. subEmitter.particleSystem._isSubEmitter = true;
  60894. return subEmitter;
  60895. };
  60896. /** Release associated resources */
  60897. SubEmitter.prototype.dispose = function () {
  60898. this.particleSystem.dispose();
  60899. };
  60900. return SubEmitter;
  60901. }());
  60902. BABYLON.SubEmitter = SubEmitter;
  60903. })(BABYLON || (BABYLON = {}));
  60904. //# sourceMappingURL=babylon.subEmitter.js.map
  60905. var BABYLON;
  60906. (function (BABYLON) {
  60907. var ShaderMaterial = /** @class */ (function (_super) {
  60908. __extends(ShaderMaterial, _super);
  60909. function ShaderMaterial(name, scene, shaderPath, options) {
  60910. var _this = _super.call(this, name, scene) || this;
  60911. _this._textures = {};
  60912. _this._textureArrays = {};
  60913. _this._floats = {};
  60914. _this._ints = {};
  60915. _this._floatsArrays = {};
  60916. _this._colors3 = {};
  60917. _this._colors3Arrays = {};
  60918. _this._colors4 = {};
  60919. _this._vectors2 = {};
  60920. _this._vectors3 = {};
  60921. _this._vectors4 = {};
  60922. _this._matrices = {};
  60923. _this._matrices3x3 = {};
  60924. _this._matrices2x2 = {};
  60925. _this._vectors2Arrays = {};
  60926. _this._vectors3Arrays = {};
  60927. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  60928. _this._shaderPath = shaderPath;
  60929. options.needAlphaBlending = options.needAlphaBlending || false;
  60930. options.needAlphaTesting = options.needAlphaTesting || false;
  60931. options.attributes = options.attributes || ["position", "normal", "uv"];
  60932. options.uniforms = options.uniforms || ["worldViewProjection"];
  60933. options.uniformBuffers = options.uniformBuffers || [];
  60934. options.samplers = options.samplers || [];
  60935. options.defines = options.defines || [];
  60936. _this._options = options;
  60937. return _this;
  60938. }
  60939. ShaderMaterial.prototype.getClassName = function () {
  60940. return "ShaderMaterial";
  60941. };
  60942. ShaderMaterial.prototype.needAlphaBlending = function () {
  60943. return this._options.needAlphaBlending;
  60944. };
  60945. ShaderMaterial.prototype.needAlphaTesting = function () {
  60946. return this._options.needAlphaTesting;
  60947. };
  60948. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  60949. if (this._options.uniforms.indexOf(uniformName) === -1) {
  60950. this._options.uniforms.push(uniformName);
  60951. }
  60952. };
  60953. ShaderMaterial.prototype.setTexture = function (name, texture) {
  60954. if (this._options.samplers.indexOf(name) === -1) {
  60955. this._options.samplers.push(name);
  60956. }
  60957. this._textures[name] = texture;
  60958. return this;
  60959. };
  60960. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  60961. if (this._options.samplers.indexOf(name) === -1) {
  60962. this._options.samplers.push(name);
  60963. }
  60964. this._checkUniform(name);
  60965. this._textureArrays[name] = textures;
  60966. return this;
  60967. };
  60968. ShaderMaterial.prototype.setFloat = function (name, value) {
  60969. this._checkUniform(name);
  60970. this._floats[name] = value;
  60971. return this;
  60972. };
  60973. ShaderMaterial.prototype.setInt = function (name, value) {
  60974. this._checkUniform(name);
  60975. this._ints[name] = value;
  60976. return this;
  60977. };
  60978. ShaderMaterial.prototype.setFloats = function (name, value) {
  60979. this._checkUniform(name);
  60980. this._floatsArrays[name] = value;
  60981. return this;
  60982. };
  60983. ShaderMaterial.prototype.setColor3 = function (name, value) {
  60984. this._checkUniform(name);
  60985. this._colors3[name] = value;
  60986. return this;
  60987. };
  60988. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  60989. this._checkUniform(name);
  60990. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  60991. color.toArray(arr, arr.length);
  60992. return arr;
  60993. }, []);
  60994. return this;
  60995. };
  60996. ShaderMaterial.prototype.setColor4 = function (name, value) {
  60997. this._checkUniform(name);
  60998. this._colors4[name] = value;
  60999. return this;
  61000. };
  61001. ShaderMaterial.prototype.setVector2 = function (name, value) {
  61002. this._checkUniform(name);
  61003. this._vectors2[name] = value;
  61004. return this;
  61005. };
  61006. ShaderMaterial.prototype.setVector3 = function (name, value) {
  61007. this._checkUniform(name);
  61008. this._vectors3[name] = value;
  61009. return this;
  61010. };
  61011. ShaderMaterial.prototype.setVector4 = function (name, value) {
  61012. this._checkUniform(name);
  61013. this._vectors4[name] = value;
  61014. return this;
  61015. };
  61016. ShaderMaterial.prototype.setMatrix = function (name, value) {
  61017. this._checkUniform(name);
  61018. this._matrices[name] = value;
  61019. return this;
  61020. };
  61021. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  61022. this._checkUniform(name);
  61023. this._matrices3x3[name] = value;
  61024. return this;
  61025. };
  61026. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  61027. this._checkUniform(name);
  61028. this._matrices2x2[name] = value;
  61029. return this;
  61030. };
  61031. ShaderMaterial.prototype.setArray2 = function (name, value) {
  61032. this._checkUniform(name);
  61033. this._vectors2Arrays[name] = value;
  61034. return this;
  61035. };
  61036. ShaderMaterial.prototype.setArray3 = function (name, value) {
  61037. this._checkUniform(name);
  61038. this._vectors3Arrays[name] = value;
  61039. return this;
  61040. };
  61041. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  61042. if (!mesh) {
  61043. return true;
  61044. }
  61045. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  61046. return false;
  61047. }
  61048. return false;
  61049. };
  61050. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  61051. var scene = this.getScene();
  61052. var engine = scene.getEngine();
  61053. if (!this.checkReadyOnEveryCall) {
  61054. if (this._renderId === scene.getRenderId()) {
  61055. if (this._checkCache(scene, mesh, useInstances)) {
  61056. return true;
  61057. }
  61058. }
  61059. }
  61060. // Instances
  61061. var defines = [];
  61062. var attribs = [];
  61063. var fallbacks = new BABYLON.EffectFallbacks();
  61064. for (var index = 0; index < this._options.defines.length; index++) {
  61065. defines.push(this._options.defines[index]);
  61066. }
  61067. for (var index = 0; index < this._options.attributes.length; index++) {
  61068. attribs.push(this._options.attributes[index]);
  61069. }
  61070. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  61071. attribs.push(BABYLON.VertexBuffer.ColorKind);
  61072. defines.push("#define VERTEXCOLOR");
  61073. }
  61074. if (useInstances) {
  61075. defines.push("#define INSTANCES");
  61076. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  61077. }
  61078. // Bones
  61079. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61080. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61081. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61082. if (mesh.numBoneInfluencers > 4) {
  61083. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61084. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61085. }
  61086. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61087. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61088. fallbacks.addCPUSkinningFallback(0, mesh);
  61089. if (this._options.uniforms.indexOf("mBones") === -1) {
  61090. this._options.uniforms.push("mBones");
  61091. }
  61092. }
  61093. else {
  61094. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61095. }
  61096. // Textures
  61097. for (var name in this._textures) {
  61098. if (!this._textures[name].isReady()) {
  61099. return false;
  61100. }
  61101. }
  61102. // Alpha test
  61103. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  61104. defines.push("#define ALPHATEST");
  61105. }
  61106. var previousEffect = this._effect;
  61107. var join = defines.join("\n");
  61108. this._effect = engine.createEffect(this._shaderPath, {
  61109. attributes: attribs,
  61110. uniformsNames: this._options.uniforms,
  61111. uniformBuffersNames: this._options.uniformBuffers,
  61112. samplers: this._options.samplers,
  61113. defines: join,
  61114. fallbacks: fallbacks,
  61115. onCompiled: this.onCompiled,
  61116. onError: this.onError
  61117. }, engine);
  61118. if (!this._effect.isReady()) {
  61119. return false;
  61120. }
  61121. if (previousEffect !== this._effect) {
  61122. scene.resetCachedMaterial();
  61123. }
  61124. this._renderId = scene.getRenderId();
  61125. return true;
  61126. };
  61127. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  61128. var scene = this.getScene();
  61129. if (!this._effect) {
  61130. return;
  61131. }
  61132. if (this._options.uniforms.indexOf("world") !== -1) {
  61133. this._effect.setMatrix("world", world);
  61134. }
  61135. if (this._options.uniforms.indexOf("worldView") !== -1) {
  61136. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  61137. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  61138. }
  61139. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  61140. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  61141. }
  61142. };
  61143. ShaderMaterial.prototype.bind = function (world, mesh) {
  61144. // Std values
  61145. this.bindOnlyWorldMatrix(world);
  61146. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  61147. if (this._options.uniforms.indexOf("view") !== -1) {
  61148. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  61149. }
  61150. if (this._options.uniforms.indexOf("projection") !== -1) {
  61151. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  61152. }
  61153. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  61154. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  61155. }
  61156. // Bones
  61157. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  61158. var name;
  61159. // Texture
  61160. for (name in this._textures) {
  61161. this._effect.setTexture(name, this._textures[name]);
  61162. }
  61163. // Texture arrays
  61164. for (name in this._textureArrays) {
  61165. this._effect.setTextureArray(name, this._textureArrays[name]);
  61166. }
  61167. // Int
  61168. for (name in this._ints) {
  61169. this._effect.setInt(name, this._ints[name]);
  61170. }
  61171. // Float
  61172. for (name in this._floats) {
  61173. this._effect.setFloat(name, this._floats[name]);
  61174. }
  61175. // Floats
  61176. for (name in this._floatsArrays) {
  61177. this._effect.setArray(name, this._floatsArrays[name]);
  61178. }
  61179. // Color3
  61180. for (name in this._colors3) {
  61181. this._effect.setColor3(name, this._colors3[name]);
  61182. }
  61183. for (name in this._colors3Arrays) {
  61184. this._effect.setArray3(name, this._colors3Arrays[name]);
  61185. }
  61186. // Color4
  61187. for (name in this._colors4) {
  61188. var color = this._colors4[name];
  61189. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  61190. }
  61191. // Vector2
  61192. for (name in this._vectors2) {
  61193. this._effect.setVector2(name, this._vectors2[name]);
  61194. }
  61195. // Vector3
  61196. for (name in this._vectors3) {
  61197. this._effect.setVector3(name, this._vectors3[name]);
  61198. }
  61199. // Vector4
  61200. for (name in this._vectors4) {
  61201. this._effect.setVector4(name, this._vectors4[name]);
  61202. }
  61203. // Matrix
  61204. for (name in this._matrices) {
  61205. this._effect.setMatrix(name, this._matrices[name]);
  61206. }
  61207. // Matrix 3x3
  61208. for (name in this._matrices3x3) {
  61209. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  61210. }
  61211. // Matrix 2x2
  61212. for (name in this._matrices2x2) {
  61213. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  61214. }
  61215. // Vector2Array
  61216. for (name in this._vectors2Arrays) {
  61217. this._effect.setArray2(name, this._vectors2Arrays[name]);
  61218. }
  61219. // Vector3Array
  61220. for (name in this._vectors3Arrays) {
  61221. this._effect.setArray3(name, this._vectors3Arrays[name]);
  61222. }
  61223. }
  61224. this._afterBind(mesh);
  61225. };
  61226. ShaderMaterial.prototype.getActiveTextures = function () {
  61227. var activeTextures = _super.prototype.getActiveTextures.call(this);
  61228. for (var name in this._textures) {
  61229. activeTextures.push(this._textures[name]);
  61230. }
  61231. for (var name in this._textureArrays) {
  61232. var array = this._textureArrays[name];
  61233. for (var index = 0; index < array.length; index++) {
  61234. activeTextures.push(array[index]);
  61235. }
  61236. }
  61237. return activeTextures;
  61238. };
  61239. ShaderMaterial.prototype.hasTexture = function (texture) {
  61240. if (_super.prototype.hasTexture.call(this, texture)) {
  61241. return true;
  61242. }
  61243. for (var name in this._textures) {
  61244. if (this._textures[name] === texture) {
  61245. return true;
  61246. }
  61247. }
  61248. for (var name in this._textureArrays) {
  61249. var array = this._textureArrays[name];
  61250. for (var index = 0; index < array.length; index++) {
  61251. if (array[index] === texture) {
  61252. return true;
  61253. }
  61254. }
  61255. }
  61256. return false;
  61257. };
  61258. ShaderMaterial.prototype.clone = function (name) {
  61259. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  61260. return newShaderMaterial;
  61261. };
  61262. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61263. if (forceDisposeTextures) {
  61264. var name;
  61265. for (name in this._textures) {
  61266. this._textures[name].dispose();
  61267. }
  61268. for (name in this._textureArrays) {
  61269. var array = this._textureArrays[name];
  61270. for (var index = 0; index < array.length; index++) {
  61271. array[index].dispose();
  61272. }
  61273. }
  61274. }
  61275. this._textures = {};
  61276. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61277. };
  61278. ShaderMaterial.prototype.serialize = function () {
  61279. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61280. serializationObject.customType = "BABYLON.ShaderMaterial";
  61281. serializationObject.options = this._options;
  61282. serializationObject.shaderPath = this._shaderPath;
  61283. var name;
  61284. // Texture
  61285. serializationObject.textures = {};
  61286. for (name in this._textures) {
  61287. serializationObject.textures[name] = this._textures[name].serialize();
  61288. }
  61289. // Texture arrays
  61290. serializationObject.textureArrays = {};
  61291. for (name in this._textureArrays) {
  61292. serializationObject.textureArrays[name] = [];
  61293. var array = this._textureArrays[name];
  61294. for (var index = 0; index < array.length; index++) {
  61295. serializationObject.textureArrays[name].push(array[index].serialize());
  61296. }
  61297. }
  61298. // Float
  61299. serializationObject.floats = {};
  61300. for (name in this._floats) {
  61301. serializationObject.floats[name] = this._floats[name];
  61302. }
  61303. // Float s
  61304. serializationObject.FloatArrays = {};
  61305. for (name in this._floatsArrays) {
  61306. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  61307. }
  61308. // Color3
  61309. serializationObject.colors3 = {};
  61310. for (name in this._colors3) {
  61311. serializationObject.colors3[name] = this._colors3[name].asArray();
  61312. }
  61313. // Color3 array
  61314. serializationObject.colors3Arrays = {};
  61315. for (name in this._colors3Arrays) {
  61316. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  61317. }
  61318. // Color4
  61319. serializationObject.colors4 = {};
  61320. for (name in this._colors4) {
  61321. serializationObject.colors4[name] = this._colors4[name].asArray();
  61322. }
  61323. // Vector2
  61324. serializationObject.vectors2 = {};
  61325. for (name in this._vectors2) {
  61326. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  61327. }
  61328. // Vector3
  61329. serializationObject.vectors3 = {};
  61330. for (name in this._vectors3) {
  61331. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  61332. }
  61333. // Vector4
  61334. serializationObject.vectors4 = {};
  61335. for (name in this._vectors4) {
  61336. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  61337. }
  61338. // Matrix
  61339. serializationObject.matrices = {};
  61340. for (name in this._matrices) {
  61341. serializationObject.matrices[name] = this._matrices[name].asArray();
  61342. }
  61343. // Matrix 3x3
  61344. serializationObject.matrices3x3 = {};
  61345. for (name in this._matrices3x3) {
  61346. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  61347. }
  61348. // Matrix 2x2
  61349. serializationObject.matrices2x2 = {};
  61350. for (name in this._matrices2x2) {
  61351. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  61352. }
  61353. // Vector2Array
  61354. serializationObject.vectors2Arrays = {};
  61355. for (name in this._vectors2Arrays) {
  61356. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  61357. }
  61358. // Vector3Array
  61359. serializationObject.vectors3Arrays = {};
  61360. for (name in this._vectors3Arrays) {
  61361. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  61362. }
  61363. return serializationObject;
  61364. };
  61365. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  61366. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  61367. var name;
  61368. // Texture
  61369. for (name in source.textures) {
  61370. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  61371. }
  61372. // Texture arrays
  61373. for (name in source.textureArrays) {
  61374. var array = source.textureArrays[name];
  61375. var textureArray = new Array();
  61376. for (var index = 0; index < array.length; index++) {
  61377. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  61378. }
  61379. material.setTextureArray(name, textureArray);
  61380. }
  61381. // Float
  61382. for (name in source.floats) {
  61383. material.setFloat(name, source.floats[name]);
  61384. }
  61385. // Float s
  61386. for (name in source.floatsArrays) {
  61387. material.setFloats(name, source.floatsArrays[name]);
  61388. }
  61389. // Color3
  61390. for (name in source.colors3) {
  61391. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  61392. }
  61393. // Color3 arrays
  61394. for (name in source.colors3Arrays) {
  61395. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  61396. if (i % 3 === 0) {
  61397. arr.push([num]);
  61398. }
  61399. else {
  61400. arr[arr.length - 1].push(num);
  61401. }
  61402. return arr;
  61403. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  61404. material.setColor3Array(name, colors);
  61405. }
  61406. // Color4
  61407. for (name in source.colors4) {
  61408. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  61409. }
  61410. // Vector2
  61411. for (name in source.vectors2) {
  61412. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  61413. }
  61414. // Vector3
  61415. for (name in source.vectors3) {
  61416. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  61417. }
  61418. // Vector4
  61419. for (name in source.vectors4) {
  61420. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  61421. }
  61422. // Matrix
  61423. for (name in source.matrices) {
  61424. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  61425. }
  61426. // Matrix 3x3
  61427. for (name in source.matrices3x3) {
  61428. material.setMatrix3x3(name, source.matrices3x3[name]);
  61429. }
  61430. // Matrix 2x2
  61431. for (name in source.matrices2x2) {
  61432. material.setMatrix2x2(name, source.matrices2x2[name]);
  61433. }
  61434. // Vector2Array
  61435. for (name in source.vectors2Arrays) {
  61436. material.setArray2(name, source.vectors2Arrays[name]);
  61437. }
  61438. // Vector3Array
  61439. for (name in source.vectors3Arrays) {
  61440. material.setArray3(name, source.vectors3Arrays[name]);
  61441. }
  61442. return material;
  61443. };
  61444. return ShaderMaterial;
  61445. }(BABYLON.Material));
  61446. BABYLON.ShaderMaterial = ShaderMaterial;
  61447. })(BABYLON || (BABYLON = {}));
  61448. //# sourceMappingURL=babylon.shaderMaterial.js.map
  61449. var BABYLON;
  61450. (function (BABYLON) {
  61451. var GroundMesh = /** @class */ (function (_super) {
  61452. __extends(GroundMesh, _super);
  61453. function GroundMesh(name, scene) {
  61454. var _this = _super.call(this, name, scene) || this;
  61455. _this.generateOctree = false;
  61456. return _this;
  61457. }
  61458. GroundMesh.prototype.getClassName = function () {
  61459. return "GroundMesh";
  61460. };
  61461. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  61462. get: function () {
  61463. return Math.min(this._subdivisionsX, this._subdivisionsY);
  61464. },
  61465. enumerable: true,
  61466. configurable: true
  61467. });
  61468. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  61469. get: function () {
  61470. return this._subdivisionsX;
  61471. },
  61472. enumerable: true,
  61473. configurable: true
  61474. });
  61475. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  61476. get: function () {
  61477. return this._subdivisionsY;
  61478. },
  61479. enumerable: true,
  61480. configurable: true
  61481. });
  61482. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  61483. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  61484. this._subdivisionsX = chunksCount;
  61485. this._subdivisionsY = chunksCount;
  61486. this.subdivide(chunksCount);
  61487. // Call the octree system optimization if it is defined.
  61488. var thisAsAny = this;
  61489. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  61490. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  61491. }
  61492. };
  61493. /**
  61494. * Returns a height (y) value in the Worl system :
  61495. * the ground altitude at the coordinates (x, z) expressed in the World system.
  61496. * Returns the ground y position if (x, z) are outside the ground surface.
  61497. */
  61498. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  61499. var world = this.getWorldMatrix();
  61500. var invMat = BABYLON.Tmp.Matrix[5];
  61501. world.invertToRef(invMat);
  61502. var tmpVect = BABYLON.Tmp.Vector3[8];
  61503. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  61504. x = tmpVect.x;
  61505. z = tmpVect.z;
  61506. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  61507. return this.position.y;
  61508. }
  61509. if (!this._heightQuads || this._heightQuads.length == 0) {
  61510. this._initHeightQuads();
  61511. this._computeHeightQuads();
  61512. }
  61513. var facet = this._getFacetAt(x, z);
  61514. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  61515. // return y in the World system
  61516. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  61517. return tmpVect.y;
  61518. };
  61519. /**
  61520. * Returns a normalized vector (Vector3) orthogonal to the ground
  61521. * at the ground coordinates (x, z) expressed in the World system.
  61522. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  61523. */
  61524. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  61525. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  61526. this.getNormalAtCoordinatesToRef(x, z, normal);
  61527. return normal;
  61528. };
  61529. /**
  61530. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  61531. * at the ground coordinates (x, z) expressed in the World system.
  61532. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  61533. * Returns the GroundMesh.
  61534. */
  61535. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  61536. var world = this.getWorldMatrix();
  61537. var tmpMat = BABYLON.Tmp.Matrix[5];
  61538. world.invertToRef(tmpMat);
  61539. var tmpVect = BABYLON.Tmp.Vector3[8];
  61540. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  61541. x = tmpVect.x;
  61542. z = tmpVect.z;
  61543. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  61544. return this;
  61545. }
  61546. if (!this._heightQuads || this._heightQuads.length == 0) {
  61547. this._initHeightQuads();
  61548. this._computeHeightQuads();
  61549. }
  61550. var facet = this._getFacetAt(x, z);
  61551. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  61552. return this;
  61553. };
  61554. /**
  61555. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  61556. * if the ground has been updated.
  61557. * This can be used in the render loop.
  61558. * Returns the GroundMesh.
  61559. */
  61560. GroundMesh.prototype.updateCoordinateHeights = function () {
  61561. if (!this._heightQuads || this._heightQuads.length == 0) {
  61562. this._initHeightQuads();
  61563. }
  61564. this._computeHeightQuads();
  61565. return this;
  61566. };
  61567. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  61568. GroundMesh.prototype._getFacetAt = function (x, z) {
  61569. // retrieve col and row from x, z coordinates in the ground local system
  61570. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  61571. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  61572. var quad = this._heightQuads[row * this._subdivisionsX + col];
  61573. var facet;
  61574. if (z < quad.slope.x * x + quad.slope.y) {
  61575. facet = quad.facet1;
  61576. }
  61577. else {
  61578. facet = quad.facet2;
  61579. }
  61580. return facet;
  61581. };
  61582. // Creates and populates the heightMap array with "facet" elements :
  61583. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  61584. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  61585. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  61586. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  61587. // Returns the GroundMesh.
  61588. GroundMesh.prototype._initHeightQuads = function () {
  61589. var subdivisionsX = this._subdivisionsX;
  61590. var subdivisionsY = this._subdivisionsY;
  61591. this._heightQuads = new Array();
  61592. for (var row = 0; row < subdivisionsY; row++) {
  61593. for (var col = 0; col < subdivisionsX; col++) {
  61594. 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) };
  61595. this._heightQuads[row * subdivisionsX + col] = quad;
  61596. }
  61597. }
  61598. return this;
  61599. };
  61600. // Compute each quad element values and update the the heightMap array :
  61601. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  61602. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  61603. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  61604. // Returns the GroundMesh.
  61605. GroundMesh.prototype._computeHeightQuads = function () {
  61606. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61607. if (!positions) {
  61608. return this;
  61609. }
  61610. var v1 = BABYLON.Tmp.Vector3[3];
  61611. var v2 = BABYLON.Tmp.Vector3[2];
  61612. var v3 = BABYLON.Tmp.Vector3[1];
  61613. var v4 = BABYLON.Tmp.Vector3[0];
  61614. var v1v2 = BABYLON.Tmp.Vector3[4];
  61615. var v1v3 = BABYLON.Tmp.Vector3[5];
  61616. var v1v4 = BABYLON.Tmp.Vector3[6];
  61617. var norm1 = BABYLON.Tmp.Vector3[7];
  61618. var norm2 = BABYLON.Tmp.Vector3[8];
  61619. var i = 0;
  61620. var j = 0;
  61621. var k = 0;
  61622. var cd = 0; // 2D slope coefficient : z = cd * x + h
  61623. var h = 0;
  61624. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  61625. var d2 = 0;
  61626. var subdivisionsX = this._subdivisionsX;
  61627. var subdivisionsY = this._subdivisionsY;
  61628. for (var row = 0; row < subdivisionsY; row++) {
  61629. for (var col = 0; col < subdivisionsX; col++) {
  61630. i = col * 3;
  61631. j = row * (subdivisionsX + 1) * 3;
  61632. k = (row + 1) * (subdivisionsX + 1) * 3;
  61633. v1.x = positions[j + i];
  61634. v1.y = positions[j + i + 1];
  61635. v1.z = positions[j + i + 2];
  61636. v2.x = positions[j + i + 3];
  61637. v2.y = positions[j + i + 4];
  61638. v2.z = positions[j + i + 5];
  61639. v3.x = positions[k + i];
  61640. v3.y = positions[k + i + 1];
  61641. v3.z = positions[k + i + 2];
  61642. v4.x = positions[k + i + 3];
  61643. v4.y = positions[k + i + 4];
  61644. v4.z = positions[k + i + 5];
  61645. // 2D slope V1V4
  61646. cd = (v4.z - v1.z) / (v4.x - v1.x);
  61647. h = v1.z - cd * v1.x; // v1 belongs to the slope
  61648. // facet equations :
  61649. // we compute each facet normal vector
  61650. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  61651. // we compute the value d by applying the equation to v1 which belongs to the plane
  61652. // then we store the facet equation in a Vector4
  61653. v2.subtractToRef(v1, v1v2);
  61654. v3.subtractToRef(v1, v1v3);
  61655. v4.subtractToRef(v1, v1v4);
  61656. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  61657. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  61658. norm1.normalize();
  61659. norm2.normalize();
  61660. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  61661. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  61662. var quad = this._heightQuads[row * subdivisionsX + col];
  61663. quad.slope.copyFromFloats(cd, h);
  61664. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  61665. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  61666. }
  61667. }
  61668. return this;
  61669. };
  61670. GroundMesh.prototype.serialize = function (serializationObject) {
  61671. _super.prototype.serialize.call(this, serializationObject);
  61672. serializationObject.subdivisionsX = this._subdivisionsX;
  61673. serializationObject.subdivisionsY = this._subdivisionsY;
  61674. serializationObject.minX = this._minX;
  61675. serializationObject.maxX = this._maxX;
  61676. serializationObject.minZ = this._minZ;
  61677. serializationObject.maxZ = this._maxZ;
  61678. serializationObject.width = this._width;
  61679. serializationObject.height = this._height;
  61680. };
  61681. GroundMesh.Parse = function (parsedMesh, scene) {
  61682. var result = new GroundMesh(parsedMesh.name, scene);
  61683. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  61684. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  61685. result._minX = parsedMesh.minX;
  61686. result._maxX = parsedMesh.maxX;
  61687. result._minZ = parsedMesh.minZ;
  61688. result._maxZ = parsedMesh.maxZ;
  61689. result._width = parsedMesh.width;
  61690. result._height = parsedMesh.height;
  61691. return result;
  61692. };
  61693. return GroundMesh;
  61694. }(BABYLON.Mesh));
  61695. BABYLON.GroundMesh = GroundMesh;
  61696. })(BABYLON || (BABYLON = {}));
  61697. //# sourceMappingURL=babylon.groundMesh.js.map
  61698. var BABYLON;
  61699. (function (BABYLON) {
  61700. /**
  61701. * Creates an instance based on a source mesh.
  61702. */
  61703. var InstancedMesh = /** @class */ (function (_super) {
  61704. __extends(InstancedMesh, _super);
  61705. function InstancedMesh(name, source) {
  61706. var _this = _super.call(this, name, source.getScene()) || this;
  61707. source.instances.push(_this);
  61708. _this._sourceMesh = source;
  61709. _this.position.copyFrom(source.position);
  61710. _this.rotation.copyFrom(source.rotation);
  61711. _this.scaling.copyFrom(source.scaling);
  61712. if (source.rotationQuaternion) {
  61713. _this.rotationQuaternion = source.rotationQuaternion.clone();
  61714. }
  61715. _this.infiniteDistance = source.infiniteDistance;
  61716. _this.setPivotMatrix(source.getPivotMatrix());
  61717. _this.refreshBoundingInfo();
  61718. _this._syncSubMeshes();
  61719. return _this;
  61720. }
  61721. /**
  61722. * Returns the string "InstancedMesh".
  61723. */
  61724. InstancedMesh.prototype.getClassName = function () {
  61725. return "InstancedMesh";
  61726. };
  61727. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  61728. // Methods
  61729. get: function () {
  61730. return this._sourceMesh.receiveShadows;
  61731. },
  61732. enumerable: true,
  61733. configurable: true
  61734. });
  61735. Object.defineProperty(InstancedMesh.prototype, "material", {
  61736. get: function () {
  61737. return this._sourceMesh.material;
  61738. },
  61739. enumerable: true,
  61740. configurable: true
  61741. });
  61742. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  61743. get: function () {
  61744. return this._sourceMesh.visibility;
  61745. },
  61746. enumerable: true,
  61747. configurable: true
  61748. });
  61749. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  61750. get: function () {
  61751. return this._sourceMesh.skeleton;
  61752. },
  61753. enumerable: true,
  61754. configurable: true
  61755. });
  61756. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  61757. get: function () {
  61758. return this._sourceMesh.renderingGroupId;
  61759. },
  61760. set: function (value) {
  61761. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  61762. return;
  61763. }
  61764. //no-op with warning
  61765. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  61766. },
  61767. enumerable: true,
  61768. configurable: true
  61769. });
  61770. /**
  61771. * Returns the total number of vertices (integer).
  61772. */
  61773. InstancedMesh.prototype.getTotalVertices = function () {
  61774. return this._sourceMesh.getTotalVertices();
  61775. };
  61776. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  61777. get: function () {
  61778. return this._sourceMesh;
  61779. },
  61780. enumerable: true,
  61781. configurable: true
  61782. });
  61783. /**
  61784. * Is this node ready to be used/rendered
  61785. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  61786. * @return {boolean} is it ready
  61787. */
  61788. InstancedMesh.prototype.isReady = function (completeCheck) {
  61789. if (completeCheck === void 0) { completeCheck = false; }
  61790. return this._sourceMesh.isReady(completeCheck, true);
  61791. };
  61792. /**
  61793. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  61794. */
  61795. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  61796. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  61797. };
  61798. /**
  61799. * Sets the vertex data of the mesh geometry for the requested `kind`.
  61800. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  61801. * The `data` are either a numeric array either a Float32Array.
  61802. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  61803. * 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).
  61804. * Note that a new underlying VertexBuffer object is created each call.
  61805. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  61806. *
  61807. * Possible `kind` values :
  61808. * - BABYLON.VertexBuffer.PositionKind
  61809. * - BABYLON.VertexBuffer.UVKind
  61810. * - BABYLON.VertexBuffer.UV2Kind
  61811. * - BABYLON.VertexBuffer.UV3Kind
  61812. * - BABYLON.VertexBuffer.UV4Kind
  61813. * - BABYLON.VertexBuffer.UV5Kind
  61814. * - BABYLON.VertexBuffer.UV6Kind
  61815. * - BABYLON.VertexBuffer.ColorKind
  61816. * - BABYLON.VertexBuffer.MatricesIndicesKind
  61817. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  61818. * - BABYLON.VertexBuffer.MatricesWeightsKind
  61819. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  61820. *
  61821. * Returns the Mesh.
  61822. */
  61823. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  61824. if (this.sourceMesh) {
  61825. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  61826. }
  61827. return this.sourceMesh;
  61828. };
  61829. /**
  61830. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  61831. * If the mesh has no geometry, it is simply returned as it is.
  61832. * The `data` are either a numeric array either a Float32Array.
  61833. * No new underlying VertexBuffer object is created.
  61834. * 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.
  61835. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  61836. *
  61837. * Possible `kind` values :
  61838. * - BABYLON.VertexBuffer.PositionKind
  61839. * - BABYLON.VertexBuffer.UVKind
  61840. * - BABYLON.VertexBuffer.UV2Kind
  61841. * - BABYLON.VertexBuffer.UV3Kind
  61842. * - BABYLON.VertexBuffer.UV4Kind
  61843. * - BABYLON.VertexBuffer.UV5Kind
  61844. * - BABYLON.VertexBuffer.UV6Kind
  61845. * - BABYLON.VertexBuffer.ColorKind
  61846. * - BABYLON.VertexBuffer.MatricesIndicesKind
  61847. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  61848. * - BABYLON.VertexBuffer.MatricesWeightsKind
  61849. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  61850. *
  61851. * Returns the Mesh.
  61852. */
  61853. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  61854. if (this.sourceMesh) {
  61855. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  61856. }
  61857. return this.sourceMesh;
  61858. };
  61859. /**
  61860. * Sets the mesh indices.
  61861. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  61862. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  61863. * This method creates a new index buffer each call.
  61864. * Returns the Mesh.
  61865. */
  61866. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  61867. if (totalVertices === void 0) { totalVertices = null; }
  61868. if (this.sourceMesh) {
  61869. this.sourceMesh.setIndices(indices, totalVertices);
  61870. }
  61871. return this.sourceMesh;
  61872. };
  61873. /**
  61874. * Boolean : True if the mesh owns the requested kind of data.
  61875. */
  61876. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  61877. return this._sourceMesh.isVerticesDataPresent(kind);
  61878. };
  61879. /**
  61880. * Returns an array of indices (IndicesArray).
  61881. */
  61882. InstancedMesh.prototype.getIndices = function () {
  61883. return this._sourceMesh.getIndices();
  61884. };
  61885. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  61886. get: function () {
  61887. return this._sourceMesh._positions;
  61888. },
  61889. enumerable: true,
  61890. configurable: true
  61891. });
  61892. /**
  61893. * Sets a new updated BoundingInfo to the mesh.
  61894. * Returns the mesh.
  61895. */
  61896. InstancedMesh.prototype.refreshBoundingInfo = function () {
  61897. var meshBB = this._sourceMesh.getBoundingInfo();
  61898. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  61899. this._updateBoundingInfo();
  61900. return this;
  61901. };
  61902. /** @hidden */
  61903. InstancedMesh.prototype._preActivate = function () {
  61904. if (this._currentLOD) {
  61905. this._currentLOD._preActivate();
  61906. }
  61907. return this;
  61908. };
  61909. /** @hidden */
  61910. InstancedMesh.prototype._activate = function (renderId) {
  61911. if (this._currentLOD) {
  61912. this._currentLOD._registerInstanceForRenderId(this, renderId);
  61913. }
  61914. return this;
  61915. };
  61916. /**
  61917. * Returns the current associated LOD AbstractMesh.
  61918. */
  61919. InstancedMesh.prototype.getLOD = function (camera) {
  61920. if (!camera) {
  61921. return this;
  61922. }
  61923. var boundingInfo = this.getBoundingInfo();
  61924. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  61925. if (this._currentLOD === this.sourceMesh) {
  61926. return this;
  61927. }
  61928. return this._currentLOD;
  61929. };
  61930. /** @hidden */
  61931. InstancedMesh.prototype._syncSubMeshes = function () {
  61932. this.releaseSubMeshes();
  61933. if (this._sourceMesh.subMeshes) {
  61934. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  61935. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  61936. }
  61937. }
  61938. return this;
  61939. };
  61940. /** @hidden */
  61941. InstancedMesh.prototype._generatePointsArray = function () {
  61942. return this._sourceMesh._generatePointsArray();
  61943. };
  61944. /**
  61945. * Creates a new InstancedMesh from the current mesh.
  61946. * - name (string) : the cloned mesh name
  61947. * - newParent (optional Node) : the optional Node to parent the clone to.
  61948. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  61949. *
  61950. * Returns the clone.
  61951. */
  61952. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61953. var result = this._sourceMesh.createInstance(name);
  61954. // Deep copy
  61955. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  61956. // Bounding info
  61957. this.refreshBoundingInfo();
  61958. // Parent
  61959. if (newParent) {
  61960. result.parent = newParent;
  61961. }
  61962. if (!doNotCloneChildren) {
  61963. // Children
  61964. for (var index = 0; index < this.getScene().meshes.length; index++) {
  61965. var mesh = this.getScene().meshes[index];
  61966. if (mesh.parent === this) {
  61967. mesh.clone(mesh.name, result);
  61968. }
  61969. }
  61970. }
  61971. result.computeWorldMatrix(true);
  61972. return result;
  61973. };
  61974. /**
  61975. * Disposes the InstancedMesh.
  61976. * Returns nothing.
  61977. */
  61978. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  61979. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  61980. // Remove from mesh
  61981. var index = this._sourceMesh.instances.indexOf(this);
  61982. this._sourceMesh.instances.splice(index, 1);
  61983. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  61984. };
  61985. return InstancedMesh;
  61986. }(BABYLON.AbstractMesh));
  61987. BABYLON.InstancedMesh = InstancedMesh;
  61988. })(BABYLON || (BABYLON = {}));
  61989. //# sourceMappingURL=babylon.instancedMesh.js.map
  61990. var BABYLON;
  61991. (function (BABYLON) {
  61992. var LinesMesh = /** @class */ (function (_super) {
  61993. __extends(LinesMesh, _super);
  61994. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  61995. if (scene === void 0) { scene = null; }
  61996. if (parent === void 0) { parent = null; }
  61997. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  61998. _this.useVertexColor = useVertexColor;
  61999. _this.useVertexAlpha = useVertexAlpha;
  62000. _this.color = new BABYLON.Color3(1, 1, 1);
  62001. _this.alpha = 1;
  62002. if (source) {
  62003. _this.color = source.color.clone();
  62004. _this.alpha = source.alpha;
  62005. _this.useVertexColor = source.useVertexColor;
  62006. _this.useVertexAlpha = source.useVertexAlpha;
  62007. }
  62008. _this._intersectionThreshold = 0.1;
  62009. var defines = [];
  62010. var options = {
  62011. attributes: [BABYLON.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
  62012. uniforms: ["world", "viewProjection"],
  62013. needAlphaBlending: true,
  62014. defines: defines
  62015. };
  62016. if (useVertexAlpha === false) {
  62017. options.needAlphaBlending = false;
  62018. }
  62019. if (!useVertexColor) {
  62020. options.uniforms.push("color");
  62021. }
  62022. else {
  62023. options.defines.push("#define VERTEXCOLOR");
  62024. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  62025. }
  62026. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  62027. return _this;
  62028. }
  62029. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  62030. /**
  62031. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  62032. * This margin is expressed in world space coordinates, so its value may vary.
  62033. * Default value is 0.1
  62034. * @returns the intersection Threshold value.
  62035. */
  62036. get: function () {
  62037. return this._intersectionThreshold;
  62038. },
  62039. /**
  62040. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  62041. * This margin is expressed in world space coordinates, so its value may vary.
  62042. * @param value the new threshold to apply
  62043. */
  62044. set: function (value) {
  62045. if (this._intersectionThreshold === value) {
  62046. return;
  62047. }
  62048. this._intersectionThreshold = value;
  62049. if (this.geometry) {
  62050. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  62051. }
  62052. },
  62053. enumerable: true,
  62054. configurable: true
  62055. });
  62056. /**
  62057. * Returns the string "LineMesh"
  62058. */
  62059. LinesMesh.prototype.getClassName = function () {
  62060. return "LinesMesh";
  62061. };
  62062. Object.defineProperty(LinesMesh.prototype, "material", {
  62063. /**
  62064. * @hidden
  62065. */
  62066. get: function () {
  62067. return this._colorShader;
  62068. },
  62069. /**
  62070. * @hidden
  62071. */
  62072. set: function (value) {
  62073. // Do nothing
  62074. },
  62075. enumerable: true,
  62076. configurable: true
  62077. });
  62078. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  62079. /**
  62080. * @hidden
  62081. */
  62082. get: function () {
  62083. return false;
  62084. },
  62085. enumerable: true,
  62086. configurable: true
  62087. });
  62088. /** @hidden */
  62089. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  62090. if (!this._geometry) {
  62091. return this;
  62092. }
  62093. // VBOs
  62094. this._geometry._bind(this._colorShader.getEffect());
  62095. // Color
  62096. if (!this.useVertexColor) {
  62097. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  62098. }
  62099. return this;
  62100. };
  62101. /** @hidden */
  62102. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  62103. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  62104. return this;
  62105. }
  62106. var engine = this.getScene().getEngine();
  62107. // Draw order
  62108. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  62109. return this;
  62110. };
  62111. LinesMesh.prototype.dispose = function (doNotRecurse) {
  62112. this._colorShader.dispose();
  62113. _super.prototype.dispose.call(this, doNotRecurse);
  62114. };
  62115. /**
  62116. * Returns a new LineMesh object cloned from the current one.
  62117. */
  62118. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  62119. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  62120. };
  62121. return LinesMesh;
  62122. }(BABYLON.Mesh));
  62123. BABYLON.LinesMesh = LinesMesh;
  62124. })(BABYLON || (BABYLON = {}));
  62125. //# sourceMappingURL=babylon.linesMesh.js.map
  62126. var BABYLON;
  62127. (function (BABYLON) {
  62128. /**
  62129. * This class implement a typical dictionary using a string as key and the generic type T as value.
  62130. * The underlying implementation relies on an associative array to ensure the best performances.
  62131. * The value can be anything including 'null' but except 'undefined'
  62132. */
  62133. var StringDictionary = /** @class */ (function () {
  62134. function StringDictionary() {
  62135. this._count = 0;
  62136. this._data = {};
  62137. }
  62138. /**
  62139. * This will clear this dictionary and copy the content from the 'source' one.
  62140. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  62141. * @param source the dictionary to take the content from and copy to this dictionary
  62142. */
  62143. StringDictionary.prototype.copyFrom = function (source) {
  62144. var _this = this;
  62145. this.clear();
  62146. source.forEach(function (t, v) { return _this.add(t, v); });
  62147. };
  62148. /**
  62149. * Get a value based from its key
  62150. * @param key the given key to get the matching value from
  62151. * @return the value if found, otherwise undefined is returned
  62152. */
  62153. StringDictionary.prototype.get = function (key) {
  62154. var val = this._data[key];
  62155. if (val !== undefined) {
  62156. return val;
  62157. }
  62158. return undefined;
  62159. };
  62160. /**
  62161. * Get a value from its key or add it if it doesn't exist.
  62162. * This method will ensure you that a given key/data will be present in the dictionary.
  62163. * @param key the given key to get the matching value from
  62164. * @param factory the factory that will create the value if the key is not present in the dictionary.
  62165. * The factory will only be invoked if there's no data for the given key.
  62166. * @return the value corresponding to the key.
  62167. */
  62168. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  62169. var val = this.get(key);
  62170. if (val !== undefined) {
  62171. return val;
  62172. }
  62173. val = factory(key);
  62174. if (val) {
  62175. this.add(key, val);
  62176. }
  62177. return val;
  62178. };
  62179. /**
  62180. * Get a value from its key if present in the dictionary otherwise add it
  62181. * @param key the key to get the value from
  62182. * @param val if there's no such key/value pair in the dictionary add it with this value
  62183. * @return the value corresponding to the key
  62184. */
  62185. StringDictionary.prototype.getOrAdd = function (key, val) {
  62186. var curVal = this.get(key);
  62187. if (curVal !== undefined) {
  62188. return curVal;
  62189. }
  62190. this.add(key, val);
  62191. return val;
  62192. };
  62193. /**
  62194. * Check if there's a given key in the dictionary
  62195. * @param key the key to check for
  62196. * @return true if the key is present, false otherwise
  62197. */
  62198. StringDictionary.prototype.contains = function (key) {
  62199. return this._data[key] !== undefined;
  62200. };
  62201. /**
  62202. * Add a new key and its corresponding value
  62203. * @param key the key to add
  62204. * @param value the value corresponding to the key
  62205. * @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
  62206. */
  62207. StringDictionary.prototype.add = function (key, value) {
  62208. if (this._data[key] !== undefined) {
  62209. return false;
  62210. }
  62211. this._data[key] = value;
  62212. ++this._count;
  62213. return true;
  62214. };
  62215. StringDictionary.prototype.set = function (key, value) {
  62216. if (this._data[key] === undefined) {
  62217. return false;
  62218. }
  62219. this._data[key] = value;
  62220. return true;
  62221. };
  62222. /**
  62223. * Get the element of the given key and remove it from the dictionary
  62224. * @param key
  62225. */
  62226. StringDictionary.prototype.getAndRemove = function (key) {
  62227. var val = this.get(key);
  62228. if (val !== undefined) {
  62229. delete this._data[key];
  62230. --this._count;
  62231. return val;
  62232. }
  62233. return null;
  62234. };
  62235. /**
  62236. * Remove a key/value from the dictionary.
  62237. * @param key the key to remove
  62238. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  62239. */
  62240. StringDictionary.prototype.remove = function (key) {
  62241. if (this.contains(key)) {
  62242. delete this._data[key];
  62243. --this._count;
  62244. return true;
  62245. }
  62246. return false;
  62247. };
  62248. /**
  62249. * Clear the whole content of the dictionary
  62250. */
  62251. StringDictionary.prototype.clear = function () {
  62252. this._data = {};
  62253. this._count = 0;
  62254. };
  62255. Object.defineProperty(StringDictionary.prototype, "count", {
  62256. get: function () {
  62257. return this._count;
  62258. },
  62259. enumerable: true,
  62260. configurable: true
  62261. });
  62262. /**
  62263. * Execute a callback on each key/val of the dictionary.
  62264. * Note that you can remove any element in this dictionary in the callback implementation
  62265. * @param callback the callback to execute on a given key/value pair
  62266. */
  62267. StringDictionary.prototype.forEach = function (callback) {
  62268. for (var cur in this._data) {
  62269. var val = this._data[cur];
  62270. callback(cur, val);
  62271. }
  62272. };
  62273. /**
  62274. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62275. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62276. * Note that you can remove any element in this dictionary in the callback implementation
  62277. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62278. */
  62279. StringDictionary.prototype.first = function (callback) {
  62280. for (var cur in this._data) {
  62281. var val = this._data[cur];
  62282. var res = callback(cur, val);
  62283. if (res) {
  62284. return res;
  62285. }
  62286. }
  62287. return null;
  62288. };
  62289. return StringDictionary;
  62290. }());
  62291. BABYLON.StringDictionary = StringDictionary;
  62292. })(BABYLON || (BABYLON = {}));
  62293. //# sourceMappingURL=babylon.stringDictionary.js.map
  62294. var BABYLON;
  62295. (function (BABYLON) {
  62296. var Debug;
  62297. (function (Debug) {
  62298. /**
  62299. * Class used to render a debug view of a given skeleton
  62300. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  62301. */
  62302. var SkeletonViewer = /** @class */ (function () {
  62303. /**
  62304. * Creates a new SkeletonViewer
  62305. * @param skeleton defines the skeleton to render
  62306. * @param mesh defines the mesh attached to the skeleton
  62307. * @param scene defines the hosting scene
  62308. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  62309. * @param renderingGroupId defines the rendering group id to use with the viewer
  62310. */
  62311. function SkeletonViewer(
  62312. /** defines the skeleton to render */
  62313. skeleton,
  62314. /** defines the mesh attached to the skeleton */
  62315. mesh, scene,
  62316. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  62317. autoUpdateBonesMatrices,
  62318. /** defines the rendering group id to use with the viewer */
  62319. renderingGroupId) {
  62320. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  62321. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  62322. this.skeleton = skeleton;
  62323. this.mesh = mesh;
  62324. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  62325. this.renderingGroupId = renderingGroupId;
  62326. /** Gets or sets the color used to render the skeleton */
  62327. this.color = BABYLON.Color3.White();
  62328. this._debugLines = new Array();
  62329. this._isEnabled = false;
  62330. this._scene = scene;
  62331. this.update();
  62332. this._renderFunction = this.update.bind(this);
  62333. }
  62334. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  62335. get: function () {
  62336. return this._isEnabled;
  62337. },
  62338. /** Gets or sets a boolean indicating if the viewer is enabled */
  62339. set: function (value) {
  62340. if (this._isEnabled === value) {
  62341. return;
  62342. }
  62343. this._isEnabled = value;
  62344. if (value) {
  62345. this._scene.registerBeforeRender(this._renderFunction);
  62346. }
  62347. else {
  62348. this._scene.unregisterBeforeRender(this._renderFunction);
  62349. }
  62350. },
  62351. enumerable: true,
  62352. configurable: true
  62353. });
  62354. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  62355. if (x === void 0) { x = 0; }
  62356. if (y === void 0) { y = 0; }
  62357. if (z === void 0) { z = 0; }
  62358. var tmat = BABYLON.Tmp.Matrix[0];
  62359. var parentBone = bone.getParent();
  62360. tmat.copyFrom(bone.getLocalMatrix());
  62361. if (x !== 0 || y !== 0 || z !== 0) {
  62362. var tmat2 = BABYLON.Tmp.Matrix[1];
  62363. BABYLON.Matrix.IdentityToRef(tmat2);
  62364. tmat2.m[12] = x;
  62365. tmat2.m[13] = y;
  62366. tmat2.m[14] = z;
  62367. tmat2.multiplyToRef(tmat, tmat);
  62368. }
  62369. if (parentBone) {
  62370. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  62371. }
  62372. tmat.multiplyToRef(meshMat, tmat);
  62373. position.x = tmat.m[12];
  62374. position.y = tmat.m[13];
  62375. position.z = tmat.m[14];
  62376. };
  62377. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  62378. var len = bones.length;
  62379. var meshPos = this.mesh.position;
  62380. for (var i = 0; i < len; i++) {
  62381. var bone = bones[i];
  62382. var points = this._debugLines[i];
  62383. if (!points) {
  62384. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62385. this._debugLines[i] = points;
  62386. }
  62387. this._getBonePosition(points[0], bone, meshMat);
  62388. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  62389. points[0].subtractInPlace(meshPos);
  62390. points[1].subtractInPlace(meshPos);
  62391. }
  62392. };
  62393. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  62394. var len = bones.length;
  62395. var boneNum = 0;
  62396. var meshPos = this.mesh.position;
  62397. for (var i = len - 1; i >= 0; i--) {
  62398. var childBone = bones[i];
  62399. var parentBone = childBone.getParent();
  62400. if (!parentBone) {
  62401. continue;
  62402. }
  62403. var points = this._debugLines[boneNum];
  62404. if (!points) {
  62405. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62406. this._debugLines[boneNum] = points;
  62407. }
  62408. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  62409. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  62410. points[0].subtractInPlace(meshPos);
  62411. points[1].subtractInPlace(meshPos);
  62412. boneNum++;
  62413. }
  62414. };
  62415. /** Update the viewer to sync with current skeleton state */
  62416. SkeletonViewer.prototype.update = function () {
  62417. if (this.autoUpdateBonesMatrices) {
  62418. this.skeleton.computeAbsoluteTransforms();
  62419. }
  62420. if (this.skeleton.bones[0].length === undefined) {
  62421. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  62422. }
  62423. else {
  62424. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  62425. }
  62426. if (!this._debugMesh) {
  62427. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  62428. this._debugMesh.renderingGroupId = this.renderingGroupId;
  62429. }
  62430. else {
  62431. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  62432. }
  62433. this._debugMesh.position.copyFrom(this.mesh.position);
  62434. this._debugMesh.color = this.color;
  62435. };
  62436. /** Release associated resources */
  62437. SkeletonViewer.prototype.dispose = function () {
  62438. if (this._debugMesh) {
  62439. this.isEnabled = false;
  62440. this._debugMesh.dispose();
  62441. this._debugMesh = null;
  62442. }
  62443. };
  62444. return SkeletonViewer;
  62445. }());
  62446. Debug.SkeletonViewer = SkeletonViewer;
  62447. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62448. })(BABYLON || (BABYLON = {}));
  62449. //# sourceMappingURL=babylon.skeletonViewer.js.map
  62450. /**
  62451. * Module Debug contains the (visual) components to debug a scene correctly
  62452. */
  62453. var BABYLON;
  62454. (function (BABYLON) {
  62455. var Debug;
  62456. (function (Debug) {
  62457. /**
  62458. * The Axes viewer will show 3 axes in a specific point in space
  62459. */
  62460. var AxesViewer = /** @class */ (function () {
  62461. /**
  62462. * Creates a new AxesViewer
  62463. * @param scene defines the hosting scene
  62464. * @param scaleLines defines a number used to scale line length (1 by default)
  62465. */
  62466. function AxesViewer(scene, scaleLines) {
  62467. if (scaleLines === void 0) { scaleLines = 1; }
  62468. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62469. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62470. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62471. /**
  62472. * Gets or sets a number used to scale line length
  62473. */
  62474. this.scaleLines = 1;
  62475. this.scaleLines = scaleLines;
  62476. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  62477. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  62478. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  62479. this._xmesh.renderingGroupId = 2;
  62480. this._ymesh.renderingGroupId = 2;
  62481. this._zmesh.renderingGroupId = 2;
  62482. this._xmesh.material.checkReadyOnlyOnce = true;
  62483. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  62484. this._ymesh.material.checkReadyOnlyOnce = true;
  62485. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  62486. this._zmesh.material.checkReadyOnlyOnce = true;
  62487. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  62488. this.scene = scene;
  62489. }
  62490. /**
  62491. * Force the viewer to update
  62492. * @param position defines the position of the viewer
  62493. * @param xaxis defines the x axis of the viewer
  62494. * @param yaxis defines the y axis of the viewer
  62495. * @param zaxis defines the z axis of the viewer
  62496. */
  62497. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  62498. var scaleLines = this.scaleLines;
  62499. if (this._xmesh) {
  62500. this._xmesh.position.copyFrom(position);
  62501. }
  62502. if (this._ymesh) {
  62503. this._ymesh.position.copyFrom(position);
  62504. }
  62505. if (this._zmesh) {
  62506. this._zmesh.position.copyFrom(position);
  62507. }
  62508. var point2 = this._xline[1];
  62509. point2.x = xaxis.x * scaleLines;
  62510. point2.y = xaxis.y * scaleLines;
  62511. point2.z = xaxis.z * scaleLines;
  62512. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  62513. point2 = this._yline[1];
  62514. point2.x = yaxis.x * scaleLines;
  62515. point2.y = yaxis.y * scaleLines;
  62516. point2.z = yaxis.z * scaleLines;
  62517. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  62518. point2 = this._zline[1];
  62519. point2.x = zaxis.x * scaleLines;
  62520. point2.y = zaxis.y * scaleLines;
  62521. point2.z = zaxis.z * scaleLines;
  62522. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  62523. };
  62524. /** Releases resources */
  62525. AxesViewer.prototype.dispose = function () {
  62526. if (this._xmesh) {
  62527. this._xmesh.dispose();
  62528. }
  62529. if (this._ymesh) {
  62530. this._ymesh.dispose();
  62531. }
  62532. if (this._zmesh) {
  62533. this._zmesh.dispose();
  62534. }
  62535. this._xmesh = null;
  62536. this._ymesh = null;
  62537. this._zmesh = null;
  62538. this.scene = null;
  62539. };
  62540. return AxesViewer;
  62541. }());
  62542. Debug.AxesViewer = AxesViewer;
  62543. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62544. })(BABYLON || (BABYLON = {}));
  62545. //# sourceMappingURL=babylon.axesViewer.js.map
  62546. var BABYLON;
  62547. (function (BABYLON) {
  62548. var Debug;
  62549. (function (Debug) {
  62550. /**
  62551. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  62552. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  62553. */
  62554. var BoneAxesViewer = /** @class */ (function (_super) {
  62555. __extends(BoneAxesViewer, _super);
  62556. /**
  62557. * Creates a new BoneAxesViewer
  62558. * @param scene defines the hosting scene
  62559. * @param bone defines the target bone
  62560. * @param mesh defines the target mesh
  62561. * @param scaleLines defines a scaling factor for line length (1 by default)
  62562. */
  62563. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  62564. if (scaleLines === void 0) { scaleLines = 1; }
  62565. var _this = _super.call(this, scene, scaleLines) || this;
  62566. /** Gets current position */
  62567. _this.pos = BABYLON.Vector3.Zero();
  62568. /** Gets direction of X axis */
  62569. _this.xaxis = BABYLON.Vector3.Zero();
  62570. /** Gets direction of Y axis */
  62571. _this.yaxis = BABYLON.Vector3.Zero();
  62572. /** Gets direction of Z axis */
  62573. _this.zaxis = BABYLON.Vector3.Zero();
  62574. _this.mesh = mesh;
  62575. _this.bone = bone;
  62576. return _this;
  62577. }
  62578. /**
  62579. * Force the viewer to update
  62580. */
  62581. BoneAxesViewer.prototype.update = function () {
  62582. if (!this.mesh || !this.bone) {
  62583. return;
  62584. }
  62585. var bone = this.bone;
  62586. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  62587. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  62588. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  62589. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  62590. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  62591. };
  62592. /** Releases resources */
  62593. BoneAxesViewer.prototype.dispose = function () {
  62594. if (this.mesh) {
  62595. this.mesh = null;
  62596. this.bone = null;
  62597. _super.prototype.dispose.call(this);
  62598. }
  62599. };
  62600. return BoneAxesViewer;
  62601. }(Debug.AxesViewer));
  62602. Debug.BoneAxesViewer = BoneAxesViewer;
  62603. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62604. })(BABYLON || (BABYLON = {}));
  62605. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  62606. var BABYLON;
  62607. (function (BABYLON) {
  62608. /**
  62609. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  62610. * in order to better appreciate the issue one might have.
  62611. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  62612. */
  62613. var RayHelper = /** @class */ (function () {
  62614. /**
  62615. * Instantiate a new ray helper.
  62616. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  62617. * in order to better appreciate the issue one might have.
  62618. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  62619. * @param ray Defines the ray we are currently tryin to visualize
  62620. */
  62621. function RayHelper(ray) {
  62622. this.ray = ray;
  62623. }
  62624. /**
  62625. * Helper function to create a colored helper in a scene in one line.
  62626. * @param ray Defines the ray we are currently tryin to visualize
  62627. * @param scene Defines the scene the ray is used in
  62628. * @param color Defines the color we want to see the ray in
  62629. * @returns The newly created ray helper.
  62630. */
  62631. RayHelper.CreateAndShow = function (ray, scene, color) {
  62632. var helper = new RayHelper(ray);
  62633. helper.show(scene, color);
  62634. return helper;
  62635. };
  62636. /**
  62637. * Shows the ray we are willing to debug.
  62638. * @param scene Defines the scene the ray needs to be rendered in
  62639. * @param color Defines the color the ray needs to be rendered in
  62640. */
  62641. RayHelper.prototype.show = function (scene, color) {
  62642. if (!this._renderFunction && this.ray) {
  62643. var ray = this.ray;
  62644. this._renderFunction = this._render.bind(this);
  62645. this._scene = scene;
  62646. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  62647. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  62648. if (this._renderFunction) {
  62649. this._scene.registerBeforeRender(this._renderFunction);
  62650. }
  62651. }
  62652. if (color && this._renderLine) {
  62653. this._renderLine.color.copyFrom(color);
  62654. }
  62655. };
  62656. /**
  62657. * Hides the ray we are debugging.
  62658. */
  62659. RayHelper.prototype.hide = function () {
  62660. if (this._renderFunction && this._scene) {
  62661. this._scene.unregisterBeforeRender(this._renderFunction);
  62662. this._scene = null;
  62663. this._renderFunction = null;
  62664. if (this._renderLine) {
  62665. this._renderLine.dispose();
  62666. this._renderLine = null;
  62667. }
  62668. this._renderPoints = [];
  62669. }
  62670. };
  62671. RayHelper.prototype._render = function () {
  62672. var ray = this.ray;
  62673. if (!ray) {
  62674. return;
  62675. }
  62676. var point = this._renderPoints[1];
  62677. var len = Math.min(ray.length, 1000000);
  62678. point.copyFrom(ray.direction);
  62679. point.scaleInPlace(len);
  62680. point.addInPlace(ray.origin);
  62681. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  62682. };
  62683. /**
  62684. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  62685. * @param mesh Defines the mesh we want the helper attached to
  62686. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  62687. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  62688. * @param length Defines the length of the ray
  62689. */
  62690. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  62691. this._attachedToMesh = mesh;
  62692. var ray = this.ray;
  62693. if (!ray) {
  62694. return;
  62695. }
  62696. if (!ray.direction) {
  62697. ray.direction = BABYLON.Vector3.Zero();
  62698. }
  62699. if (!ray.origin) {
  62700. ray.origin = BABYLON.Vector3.Zero();
  62701. }
  62702. if (length) {
  62703. ray.length = length;
  62704. }
  62705. if (!meshSpaceOrigin) {
  62706. meshSpaceOrigin = BABYLON.Vector3.Zero();
  62707. }
  62708. if (!meshSpaceDirection) {
  62709. // -1 so that this will work with Mesh.lookAt
  62710. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  62711. }
  62712. if (!this._meshSpaceDirection) {
  62713. this._meshSpaceDirection = meshSpaceDirection.clone();
  62714. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  62715. }
  62716. else {
  62717. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  62718. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  62719. }
  62720. if (!this._updateToMeshFunction) {
  62721. this._updateToMeshFunction = this._updateToMesh.bind(this);
  62722. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  62723. }
  62724. this._updateToMesh();
  62725. };
  62726. /**
  62727. * Detach the ray helper from the mesh it has previously been attached to.
  62728. */
  62729. RayHelper.prototype.detachFromMesh = function () {
  62730. if (this._attachedToMesh) {
  62731. if (this._updateToMeshFunction) {
  62732. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  62733. }
  62734. this._attachedToMesh = null;
  62735. this._updateToMeshFunction = null;
  62736. }
  62737. };
  62738. RayHelper.prototype._updateToMesh = function () {
  62739. var ray = this.ray;
  62740. if (!this._attachedToMesh || !ray) {
  62741. return;
  62742. }
  62743. if (this._attachedToMesh._isDisposed) {
  62744. this.detachFromMesh();
  62745. return;
  62746. }
  62747. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  62748. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  62749. };
  62750. /**
  62751. * Dispose the helper and release its associated resources.
  62752. */
  62753. RayHelper.prototype.dispose = function () {
  62754. this.hide();
  62755. this.detachFromMesh();
  62756. this.ray = null;
  62757. };
  62758. return RayHelper;
  62759. }());
  62760. BABYLON.RayHelper = RayHelper;
  62761. })(BABYLON || (BABYLON = {}));
  62762. //# sourceMappingURL=babylon.rayHelper.js.map
  62763. var BABYLON;
  62764. (function (BABYLON) {
  62765. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  62766. get: function () {
  62767. if (!this._debugLayer) {
  62768. this._debugLayer = new DebugLayer(this);
  62769. }
  62770. return this._debugLayer;
  62771. },
  62772. enumerable: true,
  62773. configurable: true
  62774. });
  62775. /**
  62776. * The debug layer (aka Inspector) is the go to tool in order to better understand
  62777. * what is happening in your scene
  62778. * @see http://doc.babylonjs.com/features/playground_debuglayer
  62779. */
  62780. var DebugLayer = /** @class */ (function () {
  62781. /**
  62782. * Instantiates a new debug layer.
  62783. * The debug layer (aka Inspector) is the go to tool in order to better understand
  62784. * what is happening in your scene
  62785. * @see http://doc.babylonjs.com/features/playground_debuglayer
  62786. * @param scene Defines the scene to inspect
  62787. */
  62788. function DebugLayer(scene) {
  62789. var _this = this;
  62790. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  62791. /**
  62792. * Observable triggered when a property is changed through the inspector.
  62793. */
  62794. this.onPropertyChangedObservable = new BABYLON.Observable();
  62795. this._scene = scene;
  62796. this._scene.onDisposeObservable.add(function () {
  62797. // Debug layer
  62798. if (_this._scene._debugLayer) {
  62799. _this._scene._debugLayer.hide();
  62800. }
  62801. });
  62802. }
  62803. /** Creates the inspector window. */
  62804. DebugLayer.prototype._createInspector = function (config) {
  62805. if (config === void 0) { config = {}; }
  62806. var popup = config.popup || false;
  62807. var initialTab = config.initialTab || 0;
  62808. var parentElement = config.parentElement || null;
  62809. if (!this._inspector) {
  62810. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  62811. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  62812. } // else nothing to do as instance is already created
  62813. };
  62814. /**
  62815. * Get if the inspector is visible or not.
  62816. * @returns true if visible otherwise, false
  62817. */
  62818. DebugLayer.prototype.isVisible = function () {
  62819. if (!this._inspector) {
  62820. return false;
  62821. }
  62822. return true;
  62823. };
  62824. /**
  62825. * Hide the inspector and close its window.
  62826. */
  62827. DebugLayer.prototype.hide = function () {
  62828. if (this._inspector) {
  62829. try {
  62830. this._inspector.dispose();
  62831. }
  62832. catch (e) {
  62833. // If the inspector has been removed directly from the inspector tool
  62834. }
  62835. this.onPropertyChangedObservable.clear();
  62836. this._inspector = null;
  62837. }
  62838. };
  62839. /**
  62840. *
  62841. * Launch the debugLayer.
  62842. *
  62843. * initialTab:
  62844. * | Value | Tab Name |
  62845. * | --- | --- |
  62846. * | 0 | Scene |
  62847. * | 1 | Console |
  62848. * | 2 | Stats |
  62849. * | 3 | Textures |
  62850. * | 4 | Mesh |
  62851. * | 5 | Light |
  62852. * | 6 | Material |
  62853. * | 7 | GLTF |
  62854. * | 8 | GUI |
  62855. * | 9 | Physics |
  62856. * | 10 | Camera |
  62857. * | 11 | Audio |
  62858. *
  62859. * @param config Define the configuration of the inspector
  62860. */
  62861. DebugLayer.prototype.show = function (config) {
  62862. if (config === void 0) { config = {}; }
  62863. if (typeof this.BJSINSPECTOR == 'undefined') {
  62864. // Load inspector and add it to the DOM
  62865. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  62866. }
  62867. else {
  62868. // Otherwise creates the inspector
  62869. this._createInspector(config);
  62870. }
  62871. };
  62872. /**
  62873. * Gets the active tab
  62874. * @return the index of the active tab or -1 if the inspector is hidden
  62875. */
  62876. DebugLayer.prototype.getActiveTab = function () {
  62877. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  62878. };
  62879. /**
  62880. * Define the url to get the inspector script from.
  62881. * By default it uses the babylonjs CDN.
  62882. * @ignoreNaming
  62883. */
  62884. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  62885. return DebugLayer;
  62886. }());
  62887. BABYLON.DebugLayer = DebugLayer;
  62888. })(BABYLON || (BABYLON = {}));
  62889. //# sourceMappingURL=babylon.debugLayer.js.map
  62890. var BABYLON;
  62891. (function (BABYLON) {
  62892. var Debug;
  62893. (function (Debug) {
  62894. /**
  62895. * Used to show the physics impostor around the specific mesh
  62896. */
  62897. var PhysicsViewer = /** @class */ (function () {
  62898. /**
  62899. * Creates a new PhysicsViewer
  62900. * @param scene defines the hosting scene
  62901. */
  62902. function PhysicsViewer(scene) {
  62903. /** @hidden */
  62904. this._impostors = [];
  62905. /** @hidden */
  62906. this._meshes = [];
  62907. /** @hidden */
  62908. this._numMeshes = 0;
  62909. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62910. var physicEngine = this._scene.getPhysicsEngine();
  62911. if (physicEngine) {
  62912. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  62913. }
  62914. }
  62915. /** @hidden */
  62916. PhysicsViewer.prototype._updateDebugMeshes = function () {
  62917. var plugin = this._physicsEnginePlugin;
  62918. for (var i = 0; i < this._numMeshes; i++) {
  62919. var impostor = this._impostors[i];
  62920. if (!impostor) {
  62921. continue;
  62922. }
  62923. if (impostor.isDisposed) {
  62924. this.hideImpostor(this._impostors[i--]);
  62925. }
  62926. else {
  62927. var mesh = this._meshes[i];
  62928. if (mesh && plugin) {
  62929. plugin.syncMeshWithImpostor(mesh, impostor);
  62930. }
  62931. }
  62932. }
  62933. };
  62934. /**
  62935. * Renders a specified physic impostor
  62936. * @param impostor defines the impostor to render
  62937. */
  62938. PhysicsViewer.prototype.showImpostor = function (impostor) {
  62939. if (!this._scene) {
  62940. return;
  62941. }
  62942. for (var i = 0; i < this._numMeshes; i++) {
  62943. if (this._impostors[i] == impostor) {
  62944. return;
  62945. }
  62946. }
  62947. var debugMesh = this._getDebugMesh(impostor, this._scene);
  62948. if (debugMesh) {
  62949. this._impostors[this._numMeshes] = impostor;
  62950. this._meshes[this._numMeshes] = debugMesh;
  62951. if (this._numMeshes === 0) {
  62952. this._renderFunction = this._updateDebugMeshes.bind(this);
  62953. this._scene.registerBeforeRender(this._renderFunction);
  62954. }
  62955. this._numMeshes++;
  62956. }
  62957. };
  62958. /**
  62959. * Hides a specified physic impostor
  62960. * @param impostor defines the impostor to hide
  62961. */
  62962. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  62963. if (!impostor || !this._scene) {
  62964. return;
  62965. }
  62966. var removed = false;
  62967. for (var i = 0; i < this._numMeshes; i++) {
  62968. if (this._impostors[i] == impostor) {
  62969. var mesh = this._meshes[i];
  62970. if (!mesh) {
  62971. continue;
  62972. }
  62973. this._scene.removeMesh(mesh);
  62974. mesh.dispose();
  62975. this._numMeshes--;
  62976. if (this._numMeshes > 0) {
  62977. this._meshes[i] = this._meshes[this._numMeshes];
  62978. this._impostors[i] = this._impostors[this._numMeshes];
  62979. this._meshes[this._numMeshes] = null;
  62980. this._impostors[this._numMeshes] = null;
  62981. }
  62982. else {
  62983. this._meshes[0] = null;
  62984. this._impostors[0] = null;
  62985. }
  62986. removed = true;
  62987. break;
  62988. }
  62989. }
  62990. if (removed && this._numMeshes === 0) {
  62991. this._scene.unregisterBeforeRender(this._renderFunction);
  62992. }
  62993. };
  62994. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  62995. if (!this._debugMaterial) {
  62996. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  62997. this._debugMaterial.wireframe = true;
  62998. }
  62999. return this._debugMaterial;
  63000. };
  63001. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  63002. if (!this._debugBoxMesh) {
  63003. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  63004. this._debugBoxMesh.renderingGroupId = 1;
  63005. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63006. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  63007. scene.removeMesh(this._debugBoxMesh);
  63008. }
  63009. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  63010. };
  63011. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  63012. if (!this._debugSphereMesh) {
  63013. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  63014. this._debugSphereMesh.renderingGroupId = 1;
  63015. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63016. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  63017. scene.removeMesh(this._debugSphereMesh);
  63018. }
  63019. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  63020. };
  63021. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  63022. var mesh = null;
  63023. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  63024. mesh = this._getDebugBoxMesh(scene);
  63025. impostor.getBoxSizeToRef(mesh.scaling);
  63026. }
  63027. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  63028. mesh = this._getDebugSphereMesh(scene);
  63029. var radius = impostor.getRadius();
  63030. mesh.scaling.x = radius * 2;
  63031. mesh.scaling.y = radius * 2;
  63032. mesh.scaling.z = radius * 2;
  63033. }
  63034. return mesh;
  63035. };
  63036. /** Releases all resources */
  63037. PhysicsViewer.prototype.dispose = function () {
  63038. for (var i = 0; i < this._numMeshes; i++) {
  63039. this.hideImpostor(this._impostors[i]);
  63040. }
  63041. if (this._debugBoxMesh) {
  63042. this._debugBoxMesh.dispose();
  63043. }
  63044. if (this._debugSphereMesh) {
  63045. this._debugSphereMesh.dispose();
  63046. }
  63047. if (this._debugMaterial) {
  63048. this._debugMaterial.dispose();
  63049. }
  63050. this._impostors.length = 0;
  63051. this._scene = null;
  63052. this._physicsEnginePlugin = null;
  63053. };
  63054. return PhysicsViewer;
  63055. }());
  63056. Debug.PhysicsViewer = PhysicsViewer;
  63057. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63058. })(BABYLON || (BABYLON = {}));
  63059. //# sourceMappingURL=babylon.physicsViewer.js.map
  63060. var BABYLON;
  63061. (function (BABYLON) {
  63062. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  63063. get: function () {
  63064. return this._forceShowBoundingBoxes || false;
  63065. },
  63066. set: function (value) {
  63067. this._forceShowBoundingBoxes = value;
  63068. // Lazyly creates a BB renderer if needed.
  63069. if (value) {
  63070. this.getBoundingBoxRenderer();
  63071. }
  63072. },
  63073. enumerable: true,
  63074. configurable: true
  63075. });
  63076. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  63077. if (!this._boundingBoxRenderer) {
  63078. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  63079. }
  63080. return this._boundingBoxRenderer;
  63081. };
  63082. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  63083. get: function () {
  63084. return this._showBoundingBox || false;
  63085. },
  63086. set: function (value) {
  63087. this._showBoundingBox = value;
  63088. // Lazyly creates a BB renderer if needed.
  63089. if (value) {
  63090. this.getScene().getBoundingBoxRenderer();
  63091. }
  63092. },
  63093. enumerable: true,
  63094. configurable: true
  63095. });
  63096. /**
  63097. * Component responsible of rendering the bounding box of the meshes in a scene.
  63098. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  63099. */
  63100. var BoundingBoxRenderer = /** @class */ (function () {
  63101. /**
  63102. * Instantiates a new bounding box renderer in a scene.
  63103. * @param scene the scene the renderer renders in
  63104. */
  63105. function BoundingBoxRenderer(scene) {
  63106. /**
  63107. * The component name helpfull to identify the component in the list of scene components.
  63108. */
  63109. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  63110. /**
  63111. * Color of the bounding box lines placed in front of an object
  63112. */
  63113. this.frontColor = new BABYLON.Color3(1, 1, 1);
  63114. /**
  63115. * Color of the bounding box lines placed behind an object
  63116. */
  63117. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  63118. /**
  63119. * Defines if the renderer should show the back lines or not
  63120. */
  63121. this.showBackLines = true;
  63122. /**
  63123. * @hidden
  63124. */
  63125. this.renderList = new BABYLON.SmartArray(32);
  63126. this._vertexBuffers = {};
  63127. this.scene = scene;
  63128. scene._addComponent(this);
  63129. }
  63130. /**
  63131. * Registers the component in a given scene
  63132. */
  63133. BoundingBoxRenderer.prototype.register = function () {
  63134. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  63135. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  63136. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  63137. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  63138. };
  63139. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  63140. if (mesh.showSubMeshesBoundingBox) {
  63141. var boundingInfo = subMesh.getBoundingInfo();
  63142. if (boundingInfo !== null && boundingInfo !== undefined) {
  63143. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  63144. this.renderList.push(boundingInfo.boundingBox);
  63145. }
  63146. }
  63147. };
  63148. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  63149. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  63150. var boundingInfo = sourceMesh.getBoundingInfo();
  63151. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  63152. this.renderList.push(boundingInfo.boundingBox);
  63153. }
  63154. };
  63155. BoundingBoxRenderer.prototype._prepareRessources = function () {
  63156. if (this._colorShader) {
  63157. return;
  63158. }
  63159. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  63160. attributes: [BABYLON.VertexBuffer.PositionKind],
  63161. uniforms: ["world", "viewProjection", "color"]
  63162. });
  63163. var engine = this.scene.getEngine();
  63164. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  63165. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  63166. this._createIndexBuffer();
  63167. };
  63168. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  63169. var engine = this.scene.getEngine();
  63170. 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]);
  63171. };
  63172. /**
  63173. * Rebuilds the elements related to this component in case of
  63174. * context lost for instance.
  63175. */
  63176. BoundingBoxRenderer.prototype.rebuild = function () {
  63177. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63178. if (vb) {
  63179. vb._rebuild();
  63180. }
  63181. this._createIndexBuffer();
  63182. };
  63183. /**
  63184. * @hidden
  63185. */
  63186. BoundingBoxRenderer.prototype.reset = function () {
  63187. this.renderList.reset();
  63188. };
  63189. /**
  63190. * Render the bounding boxes of a specific rendering group
  63191. * @param renderingGroupId defines the rendering group to render
  63192. */
  63193. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  63194. if (this.renderList.length === 0) {
  63195. return;
  63196. }
  63197. this._prepareRessources();
  63198. if (!this._colorShader.isReady()) {
  63199. return;
  63200. }
  63201. var engine = this.scene.getEngine();
  63202. engine.setDepthWrite(false);
  63203. this._colorShader._preBind();
  63204. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  63205. var boundingBox = this.renderList.data[boundingBoxIndex];
  63206. if (boundingBox._tag !== renderingGroupId) {
  63207. continue;
  63208. }
  63209. var min = boundingBox.minimum;
  63210. var max = boundingBox.maximum;
  63211. var diff = max.subtract(min);
  63212. var median = min.add(diff.scale(0.5));
  63213. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  63214. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  63215. .multiply(boundingBox.getWorldMatrix());
  63216. // VBOs
  63217. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  63218. if (this.showBackLines) {
  63219. // Back
  63220. engine.setDepthFunctionToGreaterOrEqual();
  63221. this.scene.resetCachedMaterial();
  63222. this._colorShader.setColor4("color", this.backColor.toColor4());
  63223. this._colorShader.bind(worldMatrix);
  63224. // Draw order
  63225. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  63226. }
  63227. // Front
  63228. engine.setDepthFunctionToLess();
  63229. this.scene.resetCachedMaterial();
  63230. this._colorShader.setColor4("color", this.frontColor.toColor4());
  63231. this._colorShader.bind(worldMatrix);
  63232. // Draw order
  63233. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  63234. }
  63235. this._colorShader.unbind();
  63236. engine.setDepthFunctionToLessOrEqual();
  63237. engine.setDepthWrite(true);
  63238. };
  63239. /**
  63240. * In case of occlusion queries, we can render the occlusion bounding box through this method
  63241. * @param mesh Define the mesh to render the occlusion bounding box for
  63242. */
  63243. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  63244. this._prepareRessources();
  63245. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  63246. return;
  63247. }
  63248. var engine = this.scene.getEngine();
  63249. engine.setDepthWrite(false);
  63250. engine.setColorWrite(false);
  63251. this._colorShader._preBind();
  63252. var boundingBox = mesh._boundingInfo.boundingBox;
  63253. var min = boundingBox.minimum;
  63254. var max = boundingBox.maximum;
  63255. var diff = max.subtract(min);
  63256. var median = min.add(diff.scale(0.5));
  63257. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  63258. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  63259. .multiply(boundingBox.getWorldMatrix());
  63260. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  63261. engine.setDepthFunctionToLess();
  63262. this.scene.resetCachedMaterial();
  63263. this._colorShader.bind(worldMatrix);
  63264. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  63265. this._colorShader.unbind();
  63266. engine.setDepthFunctionToLessOrEqual();
  63267. engine.setDepthWrite(true);
  63268. engine.setColorWrite(true);
  63269. };
  63270. /**
  63271. * Dispose and release the resources attached to this renderer.
  63272. */
  63273. BoundingBoxRenderer.prototype.dispose = function () {
  63274. if (!this._colorShader) {
  63275. return;
  63276. }
  63277. this.renderList.dispose();
  63278. this._colorShader.dispose();
  63279. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63280. if (buffer) {
  63281. buffer.dispose();
  63282. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63283. }
  63284. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  63285. };
  63286. return BoundingBoxRenderer;
  63287. }());
  63288. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  63289. })(BABYLON || (BABYLON = {}));
  63290. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  63291. var BABYLON;
  63292. (function (BABYLON) {
  63293. BABYLON.Engine.prototype.createTransformFeedback = function () {
  63294. return this._gl.createTransformFeedback();
  63295. };
  63296. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  63297. this._gl.deleteTransformFeedback(value);
  63298. };
  63299. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  63300. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  63301. };
  63302. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  63303. if (usePoints === void 0) { usePoints = true; }
  63304. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  63305. };
  63306. BABYLON.Engine.prototype.endTransformFeedback = function () {
  63307. this._gl.endTransformFeedback();
  63308. };
  63309. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  63310. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  63311. };
  63312. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  63313. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  63314. };
  63315. })(BABYLON || (BABYLON = {}));
  63316. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  63317. var BABYLON;
  63318. (function (BABYLON) {
  63319. /**
  63320. * This represents a GPU particle system in Babylon
  63321. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  63322. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  63323. */
  63324. var GPUParticleSystem = /** @class */ (function (_super) {
  63325. __extends(GPUParticleSystem, _super);
  63326. /**
  63327. * Instantiates a GPU particle system.
  63328. * 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.
  63329. * @param name The name of the particle system
  63330. * @param options The options used to create the system
  63331. * @param scene The scene the particle system belongs to
  63332. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  63333. */
  63334. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  63335. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  63336. var _this = _super.call(this, name) || this;
  63337. /**
  63338. * The layer mask we are rendering the particles through.
  63339. */
  63340. _this.layerMask = 0x0FFFFFFF;
  63341. _this._accumulatedCount = 0;
  63342. _this._targetIndex = 0;
  63343. _this._currentRenderId = -1;
  63344. _this._started = false;
  63345. _this._stopped = false;
  63346. _this._timeDelta = 0;
  63347. _this._attributesStrideSize = 21;
  63348. _this._actualFrame = 0;
  63349. _this._rawTextureWidth = 256;
  63350. /**
  63351. * An event triggered when the system is disposed.
  63352. */
  63353. _this.onDisposeObservable = new BABYLON.Observable();
  63354. /**
  63355. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  63356. * to override the particles.
  63357. */
  63358. _this.forceDepthWrite = false;
  63359. _this._preWarmDone = false;
  63360. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63361. // Setup the default processing configuration to the scene.
  63362. _this._attachImageProcessingConfiguration(null);
  63363. _this._engine = _this._scene.getEngine();
  63364. if (!options.randomTextureSize) {
  63365. delete options.randomTextureSize;
  63366. }
  63367. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  63368. var optionsAsNumber = options;
  63369. if (isFinite(optionsAsNumber)) {
  63370. fullOptions.capacity = optionsAsNumber;
  63371. }
  63372. _this._capacity = fullOptions.capacity;
  63373. _this._activeCount = fullOptions.capacity;
  63374. _this._currentActiveCount = 0;
  63375. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  63376. _this._scene.particleSystems.push(_this);
  63377. _this._updateEffectOptions = {
  63378. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  63379. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  63380. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  63381. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  63382. uniformBuffersNames: [],
  63383. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  63384. defines: "",
  63385. fallbacks: null,
  63386. onCompiled: null,
  63387. onError: null,
  63388. indexParameters: null,
  63389. maxSimultaneousLights: 0,
  63390. transformFeedbackVaryings: []
  63391. };
  63392. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  63393. // Random data
  63394. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  63395. var d = [];
  63396. for (var i = 0; i < maxTextureSize; ++i) {
  63397. d.push(Math.random());
  63398. d.push(Math.random());
  63399. d.push(Math.random());
  63400. d.push(Math.random());
  63401. }
  63402. _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);
  63403. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63404. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63405. d = [];
  63406. for (var i = 0; i < maxTextureSize; ++i) {
  63407. d.push(Math.random());
  63408. d.push(Math.random());
  63409. d.push(Math.random());
  63410. d.push(Math.random());
  63411. }
  63412. _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);
  63413. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63414. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63415. _this._randomTextureSize = maxTextureSize;
  63416. return _this;
  63417. }
  63418. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  63419. /**
  63420. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  63421. */
  63422. get: function () {
  63423. if (!BABYLON.Engine.LastCreatedEngine) {
  63424. return false;
  63425. }
  63426. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  63427. },
  63428. enumerable: true,
  63429. configurable: true
  63430. });
  63431. /**
  63432. * Gets the maximum number of particles active at the same time.
  63433. * @returns The max number of active particles.
  63434. */
  63435. GPUParticleSystem.prototype.getCapacity = function () {
  63436. return this._capacity;
  63437. };
  63438. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  63439. /**
  63440. * Gets or set the number of active particles
  63441. */
  63442. get: function () {
  63443. return this._activeCount;
  63444. },
  63445. set: function (value) {
  63446. this._activeCount = Math.min(value, this._capacity);
  63447. },
  63448. enumerable: true,
  63449. configurable: true
  63450. });
  63451. /**
  63452. * Is this system ready to be used/rendered
  63453. * @return true if the system is ready
  63454. */
  63455. GPUParticleSystem.prototype.isReady = function () {
  63456. if (!this._updateEffect) {
  63457. this._recreateUpdateEffect();
  63458. this._recreateRenderEffect();
  63459. return false;
  63460. }
  63461. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  63462. return false;
  63463. }
  63464. return true;
  63465. };
  63466. /**
  63467. * Gets if the system has been started. (Note: this will still be true after stop is called)
  63468. * @returns True if it has been started, otherwise false.
  63469. */
  63470. GPUParticleSystem.prototype.isStarted = function () {
  63471. return this._started;
  63472. };
  63473. /**
  63474. * Starts the particle system and begins to emit
  63475. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  63476. */
  63477. GPUParticleSystem.prototype.start = function (delay) {
  63478. var _this = this;
  63479. if (delay === void 0) { delay = this.startDelay; }
  63480. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  63481. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  63482. }
  63483. if (delay) {
  63484. setTimeout(function () {
  63485. _this.start(0);
  63486. }, delay);
  63487. return;
  63488. }
  63489. this._started = true;
  63490. this._stopped = false;
  63491. this._preWarmDone = false;
  63492. // Animations
  63493. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  63494. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  63495. }
  63496. };
  63497. /**
  63498. * Stops the particle system.
  63499. */
  63500. GPUParticleSystem.prototype.stop = function () {
  63501. this._stopped = true;
  63502. };
  63503. /**
  63504. * Remove all active particles
  63505. */
  63506. GPUParticleSystem.prototype.reset = function () {
  63507. this._releaseBuffers();
  63508. this._releaseVAOs();
  63509. this._currentActiveCount = 0;
  63510. this._targetIndex = 0;
  63511. };
  63512. /**
  63513. * Returns the string "GPUParticleSystem"
  63514. * @returns a string containing the class name
  63515. */
  63516. GPUParticleSystem.prototype.getClassName = function () {
  63517. return "GPUParticleSystem";
  63518. };
  63519. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  63520. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  63521. this._releaseBuffers();
  63522. return this;
  63523. };
  63524. /**
  63525. * Adds a new color gradient
  63526. * @param gradient defines the gradient to use (between 0 and 1)
  63527. * @param color1 defines the color to affect to the specified gradient
  63528. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  63529. * @returns the current particle system
  63530. */
  63531. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  63532. if (!this._colorGradients) {
  63533. this._colorGradients = [];
  63534. }
  63535. var colorGradient = new BABYLON.ColorGradient();
  63536. colorGradient.gradient = gradient;
  63537. colorGradient.color1 = color1;
  63538. this._colorGradients.push(colorGradient);
  63539. this._colorGradients.sort(function (a, b) {
  63540. if (a.gradient < b.gradient) {
  63541. return -1;
  63542. }
  63543. else if (a.gradient > b.gradient) {
  63544. return 1;
  63545. }
  63546. return 0;
  63547. });
  63548. if (this._colorGradientsTexture) {
  63549. this._colorGradientsTexture.dispose();
  63550. this._colorGradientsTexture = null;
  63551. }
  63552. this._releaseBuffers();
  63553. return this;
  63554. };
  63555. /**
  63556. * Remove a specific color gradient
  63557. * @param gradient defines the gradient to remove
  63558. * @returns the current particle system
  63559. */
  63560. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  63561. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  63562. this._colorGradientsTexture = null;
  63563. return this;
  63564. };
  63565. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  63566. var valueGradient = new BABYLON.FactorGradient();
  63567. valueGradient.gradient = gradient;
  63568. valueGradient.factor1 = factor;
  63569. factorGradients.push(valueGradient);
  63570. factorGradients.sort(function (a, b) {
  63571. if (a.gradient < b.gradient) {
  63572. return -1;
  63573. }
  63574. else if (a.gradient > b.gradient) {
  63575. return 1;
  63576. }
  63577. return 0;
  63578. });
  63579. this._releaseBuffers();
  63580. };
  63581. /**
  63582. * Adds a new size gradient
  63583. * @param gradient defines the gradient to use (between 0 and 1)
  63584. * @param factor defines the size factor to affect to the specified gradient
  63585. * @returns the current particle system
  63586. */
  63587. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  63588. if (!this._sizeGradients) {
  63589. this._sizeGradients = [];
  63590. }
  63591. this._addFactorGradient(this._sizeGradients, gradient, factor);
  63592. if (this._sizeGradientsTexture) {
  63593. this._sizeGradientsTexture.dispose();
  63594. this._sizeGradientsTexture = null;
  63595. }
  63596. this._releaseBuffers();
  63597. return this;
  63598. };
  63599. /**
  63600. * Remove a specific size gradient
  63601. * @param gradient defines the gradient to remove
  63602. * @returns the current particle system
  63603. */
  63604. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  63605. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  63606. this._sizeGradientsTexture = null;
  63607. return this;
  63608. };
  63609. /**
  63610. * Adds a new angular speed gradient
  63611. * @param gradient defines the gradient to use (between 0 and 1)
  63612. * @param factor defines the angular speed to affect to the specified gradient
  63613. * @returns the current particle system
  63614. */
  63615. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  63616. if (!this._angularSpeedGradients) {
  63617. this._angularSpeedGradients = [];
  63618. }
  63619. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  63620. if (this._angularSpeedGradientsTexture) {
  63621. this._angularSpeedGradientsTexture.dispose();
  63622. this._angularSpeedGradientsTexture = null;
  63623. }
  63624. this._releaseBuffers();
  63625. return this;
  63626. };
  63627. /**
  63628. * Remove a specific angular speed gradient
  63629. * @param gradient defines the gradient to remove
  63630. * @returns the current particle system
  63631. */
  63632. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  63633. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  63634. this._angularSpeedGradientsTexture = null;
  63635. return this;
  63636. };
  63637. /**
  63638. * Adds a new velocity gradient
  63639. * @param gradient defines the gradient to use (between 0 and 1)
  63640. * @param factor defines the velocity to affect to the specified gradient
  63641. * @returns the current particle system
  63642. */
  63643. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  63644. if (!this._velocityGradients) {
  63645. this._velocityGradients = [];
  63646. }
  63647. this._addFactorGradient(this._velocityGradients, gradient, factor);
  63648. if (this._velocityGradientsTexture) {
  63649. this._velocityGradientsTexture.dispose();
  63650. this._velocityGradientsTexture = null;
  63651. }
  63652. this._releaseBuffers();
  63653. return this;
  63654. };
  63655. /**
  63656. * Remove a specific velocity gradient
  63657. * @param gradient defines the gradient to remove
  63658. * @returns the current particle system
  63659. */
  63660. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  63661. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  63662. this._velocityGradientsTexture = null;
  63663. return this;
  63664. };
  63665. /**
  63666. * Adds a new limit velocity gradient
  63667. * @param gradient defines the gradient to use (between 0 and 1)
  63668. * @param factor defines the limit velocity value to affect to the specified gradient
  63669. * @returns the current particle system
  63670. */
  63671. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  63672. if (!this._limitVelocityGradients) {
  63673. this._limitVelocityGradients = [];
  63674. }
  63675. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  63676. if (this._limitVelocityGradientsTexture) {
  63677. this._limitVelocityGradientsTexture.dispose();
  63678. this._limitVelocityGradientsTexture = null;
  63679. }
  63680. this._releaseBuffers();
  63681. return this;
  63682. };
  63683. /**
  63684. * Remove a specific limit velocity gradient
  63685. * @param gradient defines the gradient to remove
  63686. * @returns the current particle system
  63687. */
  63688. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  63689. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  63690. this._limitVelocityGradientsTexture = null;
  63691. return this;
  63692. };
  63693. /**
  63694. * Adds a new drag gradient
  63695. * @param gradient defines the gradient to use (between 0 and 1)
  63696. * @param factor defines the drag value to affect to the specified gradient
  63697. * @returns the current particle system
  63698. */
  63699. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  63700. if (!this._dragGradients) {
  63701. this._dragGradients = [];
  63702. }
  63703. this._addFactorGradient(this._dragGradients, gradient, factor);
  63704. if (this._dragGradientsTexture) {
  63705. this._dragGradientsTexture.dispose();
  63706. this._dragGradientsTexture = null;
  63707. }
  63708. this._releaseBuffers();
  63709. return this;
  63710. };
  63711. /**
  63712. * Remove a specific drag gradient
  63713. * @param gradient defines the gradient to remove
  63714. * @returns the current particle system
  63715. */
  63716. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  63717. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  63718. this._dragGradientsTexture = null;
  63719. return this;
  63720. };
  63721. /**
  63722. * Not supported by GPUParticleSystem
  63723. * @param gradient defines the gradient to use (between 0 and 1)
  63724. * @param factor defines the emit rate value to affect to the specified gradient
  63725. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63726. * @returns the current particle system
  63727. */
  63728. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  63729. // Do nothing as emit rate is not supported by GPUParticleSystem
  63730. return this;
  63731. };
  63732. /**
  63733. * Not supported by GPUParticleSystem
  63734. * @param gradient defines the gradient to remove
  63735. * @returns the current particle system
  63736. */
  63737. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  63738. // Do nothing as emit rate is not supported by GPUParticleSystem
  63739. return this;
  63740. };
  63741. /**
  63742. * Not supported by GPUParticleSystem
  63743. * @param gradient defines the gradient to use (between 0 and 1)
  63744. * @param factor defines the start size value to affect to the specified gradient
  63745. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63746. * @returns the current particle system
  63747. */
  63748. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  63749. // Do nothing as start size is not supported by GPUParticleSystem
  63750. return this;
  63751. };
  63752. /**
  63753. * Not supported by GPUParticleSystem
  63754. * @param gradient defines the gradient to remove
  63755. * @returns the current particle system
  63756. */
  63757. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  63758. // Do nothing as start size is not supported by GPUParticleSystem
  63759. return this;
  63760. };
  63761. /**
  63762. * Not supported by GPUParticleSystem
  63763. * @param gradient defines the gradient to use (between 0 and 1)
  63764. * @param min defines the color remap minimal range
  63765. * @param max defines the color remap maximal range
  63766. * @returns the current particle system
  63767. */
  63768. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  63769. // Do nothing as start size is not supported by GPUParticleSystem
  63770. return this;
  63771. };
  63772. /**
  63773. * Not supported by GPUParticleSystem
  63774. * @param gradient defines the gradient to remove
  63775. * @returns the current particle system
  63776. */
  63777. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  63778. // Do nothing as start size is not supported by GPUParticleSystem
  63779. return this;
  63780. };
  63781. /**
  63782. * Not supported by GPUParticleSystem
  63783. * @param gradient defines the gradient to use (between 0 and 1)
  63784. * @param min defines the alpha remap minimal range
  63785. * @param max defines the alpha remap maximal range
  63786. * @returns the current particle system
  63787. */
  63788. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  63789. // Do nothing as start size is not supported by GPUParticleSystem
  63790. return this;
  63791. };
  63792. /**
  63793. * Not supported by GPUParticleSystem
  63794. * @param gradient defines the gradient to remove
  63795. * @returns the current particle system
  63796. */
  63797. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  63798. // Do nothing as start size is not supported by GPUParticleSystem
  63799. return this;
  63800. };
  63801. /**
  63802. * Not supported by GPUParticleSystem
  63803. * @param gradient defines the gradient to use (between 0 and 1)
  63804. * @param color defines the color to affect to the specified gradient
  63805. * @returns the current particle system
  63806. */
  63807. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  63808. //Not supported by GPUParticleSystem
  63809. return this;
  63810. };
  63811. /**
  63812. * Not supported by GPUParticleSystem
  63813. * @param gradient defines the gradient to remove
  63814. * @returns the current particle system
  63815. */
  63816. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  63817. //Not supported by GPUParticleSystem
  63818. return this;
  63819. };
  63820. /**
  63821. * Not supported by GPUParticleSystem
  63822. * @returns the list of ramp gradients
  63823. */
  63824. GPUParticleSystem.prototype.getRampGradients = function () {
  63825. return null;
  63826. };
  63827. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  63828. /**
  63829. * Not supported by GPUParticleSystem
  63830. * Gets or sets a boolean indicating that ramp gradients must be used
  63831. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  63832. */
  63833. get: function () {
  63834. //Not supported by GPUParticleSystem
  63835. return false;
  63836. },
  63837. set: function (value) {
  63838. //Not supported by GPUParticleSystem
  63839. },
  63840. enumerable: true,
  63841. configurable: true
  63842. });
  63843. /**
  63844. * Not supported by GPUParticleSystem
  63845. * @param gradient defines the gradient to use (between 0 and 1)
  63846. * @param factor defines the life time factor to affect to the specified gradient
  63847. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63848. * @returns the current particle system
  63849. */
  63850. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  63851. //Not supported by GPUParticleSystem
  63852. return this;
  63853. };
  63854. /**
  63855. * Not supported by GPUParticleSystem
  63856. * @param gradient defines the gradient to remove
  63857. * @returns the current particle system
  63858. */
  63859. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  63860. //Not supported by GPUParticleSystem
  63861. return this;
  63862. };
  63863. GPUParticleSystem.prototype._reset = function () {
  63864. this._releaseBuffers();
  63865. };
  63866. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  63867. var updateVertexBuffers = {};
  63868. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  63869. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  63870. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  63871. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  63872. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  63873. var offset = 12;
  63874. if (!this._colorGradientsTexture) {
  63875. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  63876. offset += 4;
  63877. }
  63878. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  63879. offset += 3;
  63880. if (!this._isBillboardBased) {
  63881. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  63882. offset += 3;
  63883. }
  63884. if (this._angularSpeedGradientsTexture) {
  63885. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  63886. offset += 1;
  63887. }
  63888. else {
  63889. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  63890. offset += 2;
  63891. }
  63892. if (this._isAnimationSheetEnabled) {
  63893. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  63894. offset += 1;
  63895. if (this.spriteRandomStartCell) {
  63896. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  63897. offset += 1;
  63898. }
  63899. }
  63900. if (this.noiseTexture) {
  63901. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  63902. offset += 3;
  63903. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  63904. offset += 3;
  63905. }
  63906. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  63907. this._engine.bindArrayBuffer(null);
  63908. return vao;
  63909. };
  63910. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  63911. var renderVertexBuffers = {};
  63912. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  63913. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  63914. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  63915. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  63916. var offset = 12;
  63917. if (!this._colorGradientsTexture) {
  63918. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  63919. offset += 4;
  63920. }
  63921. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  63922. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  63923. }
  63924. offset += 3; // Direction
  63925. if (!this._isBillboardBased) {
  63926. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  63927. offset += 3;
  63928. }
  63929. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  63930. if (this._angularSpeedGradientsTexture) {
  63931. offset++;
  63932. }
  63933. else {
  63934. offset += 2;
  63935. }
  63936. if (this._isAnimationSheetEnabled) {
  63937. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  63938. offset += 1;
  63939. if (this.spriteRandomStartCell) {
  63940. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  63941. offset += 1;
  63942. }
  63943. }
  63944. if (this.noiseTexture) {
  63945. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  63946. offset += 3;
  63947. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  63948. offset += 3;
  63949. }
  63950. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  63951. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  63952. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  63953. this._engine.bindArrayBuffer(null);
  63954. return vao;
  63955. };
  63956. GPUParticleSystem.prototype._initialize = function (force) {
  63957. if (force === void 0) { force = false; }
  63958. if (this._buffer0 && !force) {
  63959. return;
  63960. }
  63961. var engine = this._scene.getEngine();
  63962. var data = new Array();
  63963. if (!this.isBillboardBased) {
  63964. this._attributesStrideSize += 3;
  63965. }
  63966. if (this._colorGradientsTexture) {
  63967. this._attributesStrideSize -= 4;
  63968. }
  63969. if (this._angularSpeedGradientsTexture) {
  63970. this._attributesStrideSize -= 1;
  63971. }
  63972. if (this._isAnimationSheetEnabled) {
  63973. this._attributesStrideSize += 1;
  63974. if (this.spriteRandomStartCell) {
  63975. this._attributesStrideSize += 1;
  63976. }
  63977. }
  63978. if (this.noiseTexture) {
  63979. this._attributesStrideSize += 6;
  63980. }
  63981. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  63982. // position
  63983. data.push(0.0);
  63984. data.push(0.0);
  63985. data.push(0.0);
  63986. // Age and life
  63987. data.push(0.0); // create the particle as a dead one to create a new one at start
  63988. data.push(0.0);
  63989. // Seed
  63990. data.push(Math.random());
  63991. data.push(Math.random());
  63992. data.push(Math.random());
  63993. data.push(Math.random());
  63994. // Size
  63995. data.push(0.0);
  63996. data.push(0.0);
  63997. data.push(0.0);
  63998. if (!this._colorGradientsTexture) {
  63999. // color
  64000. data.push(0.0);
  64001. data.push(0.0);
  64002. data.push(0.0);
  64003. data.push(0.0);
  64004. }
  64005. // direction
  64006. data.push(0.0);
  64007. data.push(0.0);
  64008. data.push(0.0);
  64009. if (!this.isBillboardBased) {
  64010. // initialDirection
  64011. data.push(0.0);
  64012. data.push(0.0);
  64013. data.push(0.0);
  64014. }
  64015. // angle
  64016. data.push(0.0);
  64017. if (!this._angularSpeedGradientsTexture) {
  64018. data.push(0.0);
  64019. }
  64020. if (this._isAnimationSheetEnabled) {
  64021. data.push(0.0);
  64022. if (this.spriteRandomStartCell) {
  64023. data.push(0.0);
  64024. }
  64025. }
  64026. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  64027. data.push(Math.random());
  64028. data.push(Math.random());
  64029. data.push(Math.random());
  64030. data.push(Math.random());
  64031. data.push(Math.random());
  64032. data.push(Math.random());
  64033. }
  64034. }
  64035. // Sprite data
  64036. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  64037. -0.5, 0.5, 0, 1,
  64038. -0.5, -0.5, 0, 0,
  64039. 0.5, -0.5, 1, 0]);
  64040. // Buffers
  64041. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  64042. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  64043. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  64044. // Update VAO
  64045. this._updateVAO = [];
  64046. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  64047. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  64048. // Render VAO
  64049. this._renderVAO = [];
  64050. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  64051. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  64052. // Links
  64053. this._sourceBuffer = this._buffer0;
  64054. this._targetBuffer = this._buffer1;
  64055. };
  64056. /** @hidden */
  64057. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  64058. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  64059. if (this._isBillboardBased) {
  64060. defines += "\n#define BILLBOARD";
  64061. }
  64062. if (this._colorGradientsTexture) {
  64063. defines += "\n#define COLORGRADIENTS";
  64064. }
  64065. if (this._sizeGradientsTexture) {
  64066. defines += "\n#define SIZEGRADIENTS";
  64067. }
  64068. if (this._angularSpeedGradientsTexture) {
  64069. defines += "\n#define ANGULARSPEEDGRADIENTS";
  64070. }
  64071. if (this._velocityGradientsTexture) {
  64072. defines += "\n#define VELOCITYGRADIENTS";
  64073. }
  64074. if (this._limitVelocityGradientsTexture) {
  64075. defines += "\n#define LIMITVELOCITYGRADIENTS";
  64076. }
  64077. if (this._dragGradientsTexture) {
  64078. defines += "\n#define DRAGGRADIENTS";
  64079. }
  64080. if (this.isAnimationSheetEnabled) {
  64081. defines += "\n#define ANIMATESHEET";
  64082. if (this.spriteRandomStartCell) {
  64083. defines += "\n#define ANIMATESHEETRANDOMSTART";
  64084. }
  64085. }
  64086. if (this.noiseTexture) {
  64087. defines += "\n#define NOISE";
  64088. }
  64089. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  64090. return;
  64091. }
  64092. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  64093. if (!this._colorGradientsTexture) {
  64094. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  64095. }
  64096. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  64097. if (!this._isBillboardBased) {
  64098. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  64099. }
  64100. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  64101. if (this.isAnimationSheetEnabled) {
  64102. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  64103. if (this.spriteRandomStartCell) {
  64104. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  64105. }
  64106. }
  64107. if (this.noiseTexture) {
  64108. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  64109. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  64110. }
  64111. this._updateEffectOptions.defines = defines;
  64112. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  64113. };
  64114. /** @hidden */
  64115. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  64116. var defines = "";
  64117. if (this._scene.clipPlane) {
  64118. defines = "\n#define CLIPPLANE";
  64119. }
  64120. if (this._scene.clipPlane2) {
  64121. defines = "\n#define CLIPPLANE2";
  64122. }
  64123. if (this._scene.clipPlane3) {
  64124. defines = "\n#define CLIPPLANE3";
  64125. }
  64126. if (this._scene.clipPlane4) {
  64127. defines = "\n#define CLIPPLANE4";
  64128. }
  64129. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  64130. defines = "\n#define BLENDMULTIPLYMODE";
  64131. }
  64132. if (this._isBillboardBased) {
  64133. defines += "\n#define BILLBOARD";
  64134. switch (this.billboardMode) {
  64135. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  64136. defines += "\n#define BILLBOARDY";
  64137. break;
  64138. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  64139. defines += "\n#define BILLBOARDSTRETCHED";
  64140. break;
  64141. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  64142. default:
  64143. break;
  64144. }
  64145. }
  64146. if (this._colorGradientsTexture) {
  64147. defines += "\n#define COLORGRADIENTS";
  64148. }
  64149. if (this.isAnimationSheetEnabled) {
  64150. defines += "\n#define ANIMATESHEET";
  64151. }
  64152. if (this._imageProcessingConfiguration) {
  64153. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  64154. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  64155. }
  64156. if (this._renderEffect && this._renderEffect.defines === defines) {
  64157. return;
  64158. }
  64159. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  64160. var samplers = ["textureSampler", "colorGradientSampler"];
  64161. if (BABYLON.ImageProcessingConfiguration) {
  64162. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  64163. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  64164. }
  64165. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  64166. };
  64167. /**
  64168. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  64169. * @param preWarm defines if we are in the pre-warmimg phase
  64170. */
  64171. GPUParticleSystem.prototype.animate = function (preWarm) {
  64172. if (preWarm === void 0) { preWarm = false; }
  64173. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  64174. this._actualFrame += this._timeDelta;
  64175. if (!this._stopped) {
  64176. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  64177. this.stop();
  64178. }
  64179. }
  64180. };
  64181. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  64182. var texture = this[textureName];
  64183. if (!factorGradients || !factorGradients.length || texture) {
  64184. return;
  64185. }
  64186. var data = new Float32Array(this._rawTextureWidth);
  64187. for (var x = 0; x < this._rawTextureWidth; x++) {
  64188. var ratio = x / this._rawTextureWidth;
  64189. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  64190. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  64191. });
  64192. }
  64193. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  64194. };
  64195. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  64196. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  64197. };
  64198. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  64199. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  64200. };
  64201. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  64202. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  64203. };
  64204. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  64205. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  64206. };
  64207. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  64208. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  64209. };
  64210. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  64211. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  64212. return;
  64213. }
  64214. var data = new Uint8Array(this._rawTextureWidth * 4);
  64215. var tmpColor = BABYLON.Tmp.Color4[0];
  64216. for (var x = 0; x < this._rawTextureWidth; x++) {
  64217. var ratio = x / this._rawTextureWidth;
  64218. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  64219. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  64220. data[x * 4] = tmpColor.r * 255;
  64221. data[x * 4 + 1] = tmpColor.g * 255;
  64222. data[x * 4 + 2] = tmpColor.b * 255;
  64223. data[x * 4 + 3] = tmpColor.a * 255;
  64224. });
  64225. }
  64226. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  64227. };
  64228. /**
  64229. * Renders the particle system in its current state
  64230. * @param preWarm defines if the system should only update the particles but not render them
  64231. * @returns the current number of particles
  64232. */
  64233. GPUParticleSystem.prototype.render = function (preWarm) {
  64234. if (preWarm === void 0) { preWarm = false; }
  64235. if (!this._started) {
  64236. return 0;
  64237. }
  64238. this._createColorGradientTexture();
  64239. this._createSizeGradientTexture();
  64240. this._createAngularSpeedGradientTexture();
  64241. this._createVelocityGradientTexture();
  64242. this._createLimitVelocityGradientTexture();
  64243. this._createDragGradientTexture();
  64244. this._recreateUpdateEffect();
  64245. this._recreateRenderEffect();
  64246. if (!this.isReady()) {
  64247. return 0;
  64248. }
  64249. if (!preWarm) {
  64250. if (!this._preWarmDone && this.preWarmCycles) {
  64251. for (var index = 0; index < this.preWarmCycles; index++) {
  64252. this.animate(true);
  64253. this.render(true);
  64254. }
  64255. this._preWarmDone = true;
  64256. }
  64257. if (this._currentRenderId === this._scene.getRenderId()) {
  64258. return 0;
  64259. }
  64260. this._currentRenderId = this._scene.getRenderId();
  64261. }
  64262. // Get everything ready to render
  64263. this._initialize();
  64264. this._accumulatedCount += this.emitRate * this._timeDelta;
  64265. if (this._accumulatedCount > 1) {
  64266. var intPart = this._accumulatedCount | 0;
  64267. this._accumulatedCount -= intPart;
  64268. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  64269. }
  64270. if (!this._currentActiveCount) {
  64271. return 0;
  64272. }
  64273. // Enable update effect
  64274. this._engine.enableEffect(this._updateEffect);
  64275. this._engine.setState(false);
  64276. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  64277. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  64278. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  64279. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  64280. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  64281. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  64282. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  64283. if (!this._colorGradientsTexture) {
  64284. this._updateEffect.setDirectColor4("color1", this.color1);
  64285. this._updateEffect.setDirectColor4("color2", this.color2);
  64286. }
  64287. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  64288. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  64289. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  64290. this._updateEffect.setVector3("gravity", this.gravity);
  64291. if (this._sizeGradientsTexture) {
  64292. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  64293. }
  64294. if (this._angularSpeedGradientsTexture) {
  64295. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  64296. }
  64297. if (this._velocityGradientsTexture) {
  64298. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  64299. }
  64300. if (this._limitVelocityGradientsTexture) {
  64301. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  64302. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  64303. }
  64304. if (this._dragGradientsTexture) {
  64305. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  64306. }
  64307. if (this.particleEmitterType) {
  64308. this.particleEmitterType.applyToShader(this._updateEffect);
  64309. }
  64310. if (this._isAnimationSheetEnabled) {
  64311. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  64312. }
  64313. if (this.noiseTexture) {
  64314. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  64315. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  64316. }
  64317. var emitterWM;
  64318. if (this.emitter.position) {
  64319. var emitterMesh = this.emitter;
  64320. emitterWM = emitterMesh.getWorldMatrix();
  64321. }
  64322. else {
  64323. var emitterPosition = this.emitter;
  64324. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  64325. }
  64326. this._updateEffect.setMatrix("emitterWM", emitterWM);
  64327. // Bind source VAO
  64328. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  64329. // Update
  64330. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  64331. this._engine.setRasterizerState(false);
  64332. this._engine.beginTransformFeedback(true);
  64333. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  64334. this._engine.endTransformFeedback();
  64335. this._engine.setRasterizerState(true);
  64336. this._engine.bindTransformFeedbackBuffer(null);
  64337. if (!preWarm) {
  64338. // Enable render effect
  64339. this._engine.enableEffect(this._renderEffect);
  64340. var viewMatrix = this._scene.getViewMatrix();
  64341. this._renderEffect.setMatrix("view", viewMatrix);
  64342. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  64343. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  64344. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  64345. if (this._colorGradientsTexture) {
  64346. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  64347. }
  64348. else {
  64349. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  64350. }
  64351. if (this._isAnimationSheetEnabled && this.particleTexture) {
  64352. var baseSize = this.particleTexture.getBaseSize();
  64353. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  64354. }
  64355. if (this._isBillboardBased) {
  64356. var camera = this._scene.activeCamera;
  64357. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  64358. }
  64359. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  64360. var invView = viewMatrix.clone();
  64361. invView.invert();
  64362. this._renderEffect.setMatrix("invView", invView);
  64363. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  64364. }
  64365. // image processing
  64366. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  64367. this._imageProcessingConfiguration.bind(this._renderEffect);
  64368. }
  64369. // Draw order
  64370. switch (this.blendMode) {
  64371. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  64372. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  64373. break;
  64374. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  64375. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  64376. break;
  64377. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  64378. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  64379. break;
  64380. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  64381. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  64382. break;
  64383. }
  64384. if (this.forceDepthWrite) {
  64385. this._engine.setDepthWrite(true);
  64386. }
  64387. // Bind source VAO
  64388. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  64389. // Render
  64390. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  64391. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64392. }
  64393. // Switch VAOs
  64394. this._targetIndex++;
  64395. if (this._targetIndex === 2) {
  64396. this._targetIndex = 0;
  64397. }
  64398. // Switch buffers
  64399. var tmpBuffer = this._sourceBuffer;
  64400. this._sourceBuffer = this._targetBuffer;
  64401. this._targetBuffer = tmpBuffer;
  64402. return this._currentActiveCount;
  64403. };
  64404. /**
  64405. * Rebuilds the particle system
  64406. */
  64407. GPUParticleSystem.prototype.rebuild = function () {
  64408. this._initialize(true);
  64409. };
  64410. GPUParticleSystem.prototype._releaseBuffers = function () {
  64411. if (this._buffer0) {
  64412. this._buffer0.dispose();
  64413. this._buffer0 = null;
  64414. }
  64415. if (this._buffer1) {
  64416. this._buffer1.dispose();
  64417. this._buffer1 = null;
  64418. }
  64419. if (this._spriteBuffer) {
  64420. this._spriteBuffer.dispose();
  64421. this._spriteBuffer = null;
  64422. }
  64423. };
  64424. GPUParticleSystem.prototype._releaseVAOs = function () {
  64425. if (!this._updateVAO) {
  64426. return;
  64427. }
  64428. for (var index = 0; index < this._updateVAO.length; index++) {
  64429. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  64430. }
  64431. this._updateVAO = [];
  64432. for (var index = 0; index < this._renderVAO.length; index++) {
  64433. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  64434. }
  64435. this._renderVAO = [];
  64436. };
  64437. /**
  64438. * Disposes the particle system and free the associated resources
  64439. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  64440. */
  64441. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  64442. if (disposeTexture === void 0) { disposeTexture = true; }
  64443. var index = this._scene.particleSystems.indexOf(this);
  64444. if (index > -1) {
  64445. this._scene.particleSystems.splice(index, 1);
  64446. }
  64447. this._releaseBuffers();
  64448. this._releaseVAOs();
  64449. if (this._colorGradientsTexture) {
  64450. this._colorGradientsTexture.dispose();
  64451. this._colorGradientsTexture = null;
  64452. }
  64453. if (this._sizeGradientsTexture) {
  64454. this._sizeGradientsTexture.dispose();
  64455. this._sizeGradientsTexture = null;
  64456. }
  64457. if (this._angularSpeedGradientsTexture) {
  64458. this._angularSpeedGradientsTexture.dispose();
  64459. this._angularSpeedGradientsTexture = null;
  64460. }
  64461. if (this._velocityGradientsTexture) {
  64462. this._velocityGradientsTexture.dispose();
  64463. this._velocityGradientsTexture = null;
  64464. }
  64465. if (this._limitVelocityGradientsTexture) {
  64466. this._limitVelocityGradientsTexture.dispose();
  64467. this._limitVelocityGradientsTexture = null;
  64468. }
  64469. if (this._dragGradientsTexture) {
  64470. this._dragGradientsTexture.dispose();
  64471. this._dragGradientsTexture = null;
  64472. }
  64473. if (this._randomTexture) {
  64474. this._randomTexture.dispose();
  64475. this._randomTexture = null;
  64476. }
  64477. if (this._randomTexture2) {
  64478. this._randomTexture2.dispose();
  64479. this._randomTexture2 = null;
  64480. }
  64481. if (disposeTexture && this.particleTexture) {
  64482. this.particleTexture.dispose();
  64483. this.particleTexture = null;
  64484. }
  64485. if (disposeTexture && this.noiseTexture) {
  64486. this.noiseTexture.dispose();
  64487. this.noiseTexture = null;
  64488. }
  64489. // Callback
  64490. this.onDisposeObservable.notifyObservers(this);
  64491. this.onDisposeObservable.clear();
  64492. };
  64493. /**
  64494. * Clones the particle system.
  64495. * @param name The name of the cloned object
  64496. * @param newEmitter The new emitter to use
  64497. * @returns the cloned particle system
  64498. */
  64499. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  64500. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  64501. BABYLON.Tools.DeepCopy(this, result);
  64502. if (newEmitter === undefined) {
  64503. newEmitter = this.emitter;
  64504. }
  64505. result.emitter = newEmitter;
  64506. if (this.particleTexture) {
  64507. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  64508. }
  64509. return result;
  64510. };
  64511. /**
  64512. * Serializes the particle system to a JSON object.
  64513. * @returns the JSON object
  64514. */
  64515. GPUParticleSystem.prototype.serialize = function () {
  64516. var serializationObject = {};
  64517. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  64518. serializationObject.activeParticleCount = this.activeParticleCount;
  64519. return serializationObject;
  64520. };
  64521. /**
  64522. * Parses a JSON object to create a GPU particle system.
  64523. * @param parsedParticleSystem The JSON object to parse
  64524. * @param scene The scene to create the particle system in
  64525. * @param rootUrl The root url to use to load external dependencies like texture
  64526. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  64527. * @returns the parsed GPU particle system
  64528. */
  64529. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  64530. if (doNotStart === void 0) { doNotStart = false; }
  64531. var name = parsedParticleSystem.name;
  64532. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  64533. if (parsedParticleSystem.activeParticleCount) {
  64534. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  64535. }
  64536. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  64537. // Auto start
  64538. if (parsedParticleSystem.preventAutoStart) {
  64539. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  64540. }
  64541. if (!doNotStart && !particleSystem.preventAutoStart) {
  64542. particleSystem.start();
  64543. }
  64544. return particleSystem;
  64545. };
  64546. return GPUParticleSystem;
  64547. }(BABYLON.BaseParticleSystem));
  64548. BABYLON.GPUParticleSystem = GPUParticleSystem;
  64549. })(BABYLON || (BABYLON = {}));
  64550. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  64551. var BABYLON;
  64552. (function (BABYLON) {
  64553. /**
  64554. * Represents one particle of a solid particle system.
  64555. */
  64556. var SolidParticle = /** @class */ (function () {
  64557. /**
  64558. * Creates a Solid Particle object.
  64559. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  64560. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  64561. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  64562. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  64563. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  64564. * @param shapeId (integer) is the model shape identifier in the SPS.
  64565. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  64566. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  64567. */
  64568. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  64569. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  64570. /**
  64571. * particle global index
  64572. */
  64573. this.idx = 0;
  64574. /**
  64575. * The color of the particle
  64576. */
  64577. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  64578. /**
  64579. * The world space position of the particle.
  64580. */
  64581. this.position = BABYLON.Vector3.Zero();
  64582. /**
  64583. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  64584. */
  64585. this.rotation = BABYLON.Vector3.Zero();
  64586. /**
  64587. * The scaling of the particle.
  64588. */
  64589. this.scaling = BABYLON.Vector3.One();
  64590. /**
  64591. * The uvs of the particle.
  64592. */
  64593. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  64594. /**
  64595. * The current speed of the particle.
  64596. */
  64597. this.velocity = BABYLON.Vector3.Zero();
  64598. /**
  64599. * The pivot point in the particle local space.
  64600. */
  64601. this.pivot = BABYLON.Vector3.Zero();
  64602. /**
  64603. * Must the particle be translated from its pivot point in its local space ?
  64604. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  64605. * Default : false
  64606. */
  64607. this.translateFromPivot = false;
  64608. /**
  64609. * Is the particle active or not ?
  64610. */
  64611. this.alive = true;
  64612. /**
  64613. * Is the particle visible or not ?
  64614. */
  64615. this.isVisible = true;
  64616. /**
  64617. * Index of this particle in the global "positions" array (Internal use)
  64618. * @hidden
  64619. */
  64620. this._pos = 0;
  64621. /**
  64622. * @hidden Index of this particle in the global "indices" array (Internal use)
  64623. */
  64624. this._ind = 0;
  64625. /**
  64626. * ModelShape id of this particle
  64627. */
  64628. this.shapeId = 0;
  64629. /**
  64630. * Index of the particle in its shape id (Internal use)
  64631. */
  64632. this.idxInShape = 0;
  64633. /**
  64634. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  64635. */
  64636. this._stillInvisible = false;
  64637. /**
  64638. * @hidden Last computed particle rotation matrix
  64639. */
  64640. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  64641. /**
  64642. * Parent particle Id, if any.
  64643. * Default null.
  64644. */
  64645. this.parentId = null;
  64646. /**
  64647. * @hidden Internal global position in the SPS.
  64648. */
  64649. this._globalPosition = BABYLON.Vector3.Zero();
  64650. this.idx = particleIndex;
  64651. this._pos = positionIndex;
  64652. this._ind = indiceIndex;
  64653. this._model = model;
  64654. this.shapeId = shapeId;
  64655. this.idxInShape = idxInShape;
  64656. this._sps = sps;
  64657. if (modelBoundingInfo) {
  64658. this._modelBoundingInfo = modelBoundingInfo;
  64659. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  64660. }
  64661. }
  64662. Object.defineProperty(SolidParticle.prototype, "scale", {
  64663. /**
  64664. * Legacy support, changed scale to scaling
  64665. */
  64666. get: function () {
  64667. return this.scaling;
  64668. },
  64669. /**
  64670. * Legacy support, changed scale to scaling
  64671. */
  64672. set: function (scale) {
  64673. this.scaling = scale;
  64674. },
  64675. enumerable: true,
  64676. configurable: true
  64677. });
  64678. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  64679. /**
  64680. * Legacy support, changed quaternion to rotationQuaternion
  64681. */
  64682. get: function () {
  64683. return this.rotationQuaternion;
  64684. },
  64685. /**
  64686. * Legacy support, changed quaternion to rotationQuaternion
  64687. */
  64688. set: function (q) {
  64689. this.rotationQuaternion = q;
  64690. },
  64691. enumerable: true,
  64692. configurable: true
  64693. });
  64694. /**
  64695. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  64696. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  64697. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  64698. * @returns true if it intersects
  64699. */
  64700. SolidParticle.prototype.intersectsMesh = function (target) {
  64701. if (!this._boundingInfo || !target._boundingInfo) {
  64702. return false;
  64703. }
  64704. if (this._sps._bSphereOnly) {
  64705. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  64706. }
  64707. return this._boundingInfo.intersects(target._boundingInfo, false);
  64708. };
  64709. return SolidParticle;
  64710. }());
  64711. BABYLON.SolidParticle = SolidParticle;
  64712. /**
  64713. * Represents the shape of the model used by one particle of a solid particle system.
  64714. * SPS internal tool, don't use it manually.
  64715. */
  64716. var ModelShape = /** @class */ (function () {
  64717. /**
  64718. * 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.
  64719. * SPS internal tool, don't use it manually.
  64720. * @hidden
  64721. */
  64722. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  64723. /**
  64724. * length of the shape in the model indices array (internal use)
  64725. * @hidden
  64726. */
  64727. this._indicesLength = 0;
  64728. this.shapeID = id;
  64729. this._shape = shape;
  64730. this._indicesLength = indicesLength;
  64731. this._shapeUV = shapeUV;
  64732. this._positionFunction = posFunction;
  64733. this._vertexFunction = vtxFunction;
  64734. }
  64735. return ModelShape;
  64736. }());
  64737. BABYLON.ModelShape = ModelShape;
  64738. /**
  64739. * Represents a Depth Sorted Particle in the solid particle system.
  64740. */
  64741. var DepthSortedParticle = /** @class */ (function () {
  64742. function DepthSortedParticle() {
  64743. /**
  64744. * Index of the particle in the "indices" array
  64745. */
  64746. this.ind = 0;
  64747. /**
  64748. * Length of the particle shape in the "indices" array
  64749. */
  64750. this.indicesLength = 0;
  64751. /**
  64752. * Squared distance from the particle to the camera
  64753. */
  64754. this.sqDistance = 0.0;
  64755. }
  64756. return DepthSortedParticle;
  64757. }());
  64758. BABYLON.DepthSortedParticle = DepthSortedParticle;
  64759. })(BABYLON || (BABYLON = {}));
  64760. //# sourceMappingURL=babylon.solidParticle.js.map
  64761. var BABYLON;
  64762. (function (BABYLON) {
  64763. /**
  64764. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  64765. *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.
  64766. * The SPS is also a particle system. It provides some methods to manage the particles.
  64767. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  64768. *
  64769. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  64770. */
  64771. var SolidParticleSystem = /** @class */ (function () {
  64772. /**
  64773. * Creates a SPS (Solid Particle System) object.
  64774. * @param name (String) is the SPS name, this will be the underlying mesh name.
  64775. * @param scene (Scene) is the scene in which the SPS is added.
  64776. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  64777. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  64778. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  64779. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  64780. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  64781. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  64782. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  64783. */
  64784. function SolidParticleSystem(name, scene, options) {
  64785. /**
  64786. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  64787. * Example : var p = SPS.particles[i];
  64788. */
  64789. this.particles = new Array();
  64790. /**
  64791. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  64792. */
  64793. this.nbParticles = 0;
  64794. /**
  64795. * If the particles must ever face the camera (default false). Useful for planar particles.
  64796. */
  64797. this.billboard = false;
  64798. /**
  64799. * Recompute normals when adding a shape
  64800. */
  64801. this.recomputeNormals = true;
  64802. /**
  64803. * This a counter ofr your own usage. It's not set by any SPS functions.
  64804. */
  64805. this.counter = 0;
  64806. /**
  64807. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  64808. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  64809. */
  64810. this.vars = {};
  64811. /**
  64812. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  64813. * @hidden
  64814. */
  64815. this._bSphereOnly = false;
  64816. /**
  64817. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  64818. * @hidden
  64819. */
  64820. this._bSphereRadiusFactor = 1.0;
  64821. this._positions = new Array();
  64822. this._indices = new Array();
  64823. this._normals = new Array();
  64824. this._colors = new Array();
  64825. this._uvs = new Array();
  64826. this._index = 0; // indices index
  64827. this._updatable = true;
  64828. this._pickable = false;
  64829. this._isVisibilityBoxLocked = false;
  64830. this._alwaysVisible = false;
  64831. this._depthSort = false;
  64832. this._shapeCounter = 0;
  64833. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  64834. this._color = new BABYLON.Color4(0, 0, 0, 0);
  64835. this._computeParticleColor = true;
  64836. this._computeParticleTexture = true;
  64837. this._computeParticleRotation = true;
  64838. this._computeParticleVertex = false;
  64839. this._computeBoundingBox = false;
  64840. this._depthSortParticles = true;
  64841. this._cam_axisZ = BABYLON.Vector3.Zero();
  64842. this._cam_axisY = BABYLON.Vector3.Zero();
  64843. this._cam_axisX = BABYLON.Vector3.Zero();
  64844. this._axisZ = BABYLON.Axis.Z;
  64845. this._camDir = BABYLON.Vector3.Zero();
  64846. this._camInvertedPosition = BABYLON.Vector3.Zero();
  64847. this._rotMatrix = new BABYLON.Matrix();
  64848. this._invertMatrix = new BABYLON.Matrix();
  64849. this._rotated = BABYLON.Vector3.Zero();
  64850. this._quaternion = new BABYLON.Quaternion();
  64851. this._vertex = BABYLON.Vector3.Zero();
  64852. this._normal = BABYLON.Vector3.Zero();
  64853. this._yaw = 0.0;
  64854. this._pitch = 0.0;
  64855. this._roll = 0.0;
  64856. this._halfroll = 0.0;
  64857. this._halfpitch = 0.0;
  64858. this._halfyaw = 0.0;
  64859. this._sinRoll = 0.0;
  64860. this._cosRoll = 0.0;
  64861. this._sinPitch = 0.0;
  64862. this._cosPitch = 0.0;
  64863. this._sinYaw = 0.0;
  64864. this._cosYaw = 0.0;
  64865. this._mustUnrotateFixedNormals = false;
  64866. this._minimum = BABYLON.Vector3.Zero();
  64867. this._maximum = BABYLON.Vector3.Zero();
  64868. this._minBbox = BABYLON.Vector3.Zero();
  64869. this._maxBbox = BABYLON.Vector3.Zero();
  64870. this._particlesIntersect = false;
  64871. this._depthSortFunction = function (p1, p2) {
  64872. return (p2.sqDistance - p1.sqDistance);
  64873. };
  64874. this._needs32Bits = false;
  64875. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  64876. this._scaledPivot = BABYLON.Vector3.Zero();
  64877. this._particleHasParent = false;
  64878. this.name = name;
  64879. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64880. this._camera = scene.activeCamera;
  64881. this._pickable = options ? options.isPickable : false;
  64882. this._depthSort = options ? options.enableDepthSort : false;
  64883. this._particlesIntersect = options ? options.particleIntersection : false;
  64884. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  64885. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  64886. if (options && options.updatable !== undefined) {
  64887. this._updatable = options.updatable;
  64888. }
  64889. else {
  64890. this._updatable = true;
  64891. }
  64892. if (this._pickable) {
  64893. this.pickedParticles = [];
  64894. }
  64895. if (this._depthSort) {
  64896. this.depthSortedParticles = [];
  64897. }
  64898. }
  64899. /**
  64900. * Builds the SPS underlying mesh. Returns a standard Mesh.
  64901. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  64902. * @returns the created mesh
  64903. */
  64904. SolidParticleSystem.prototype.buildMesh = function () {
  64905. if (this.nbParticles === 0) {
  64906. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  64907. this.addShape(triangle, 1);
  64908. triangle.dispose();
  64909. }
  64910. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  64911. this._positions32 = new Float32Array(this._positions);
  64912. this._uvs32 = new Float32Array(this._uvs);
  64913. this._colors32 = new Float32Array(this._colors);
  64914. if (this.recomputeNormals) {
  64915. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  64916. }
  64917. this._normals32 = new Float32Array(this._normals);
  64918. this._fixedNormal32 = new Float32Array(this._normals);
  64919. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  64920. this._unrotateFixedNormals();
  64921. }
  64922. var vertexData = new BABYLON.VertexData();
  64923. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  64924. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  64925. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  64926. if (this._uvs32.length > 0) {
  64927. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  64928. }
  64929. if (this._colors32.length > 0) {
  64930. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  64931. }
  64932. var mesh = new BABYLON.Mesh(this.name, this._scene);
  64933. vertexData.applyToMesh(mesh, this._updatable);
  64934. this.mesh = mesh;
  64935. this.mesh.isPickable = this._pickable;
  64936. // free memory
  64937. if (!this._depthSort) {
  64938. this._indices = null;
  64939. }
  64940. this._positions = null;
  64941. this._normals = null;
  64942. this._uvs = null;
  64943. this._colors = null;
  64944. if (!this._updatable) {
  64945. this.particles.length = 0;
  64946. }
  64947. return mesh;
  64948. };
  64949. /**
  64950. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  64951. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  64952. * Thus the particles generated from `digest()` have their property `position` set yet.
  64953. * @param mesh ( Mesh ) is the mesh to be digested
  64954. * @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
  64955. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  64956. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  64957. * @returns the current SPS
  64958. */
  64959. SolidParticleSystem.prototype.digest = function (mesh, options) {
  64960. var size = (options && options.facetNb) || 1;
  64961. var number = (options && options.number) || 0;
  64962. var delta = (options && options.delta) || 0;
  64963. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64964. var meshInd = mesh.getIndices();
  64965. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64966. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64967. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64968. var f = 0; // facet counter
  64969. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  64970. // compute size from number
  64971. if (number) {
  64972. number = (number > totalFacets) ? totalFacets : number;
  64973. size = Math.round(totalFacets / number);
  64974. delta = 0;
  64975. }
  64976. else {
  64977. size = (size > totalFacets) ? totalFacets : size;
  64978. }
  64979. var facetPos = []; // submesh positions
  64980. var facetInd = []; // submesh indices
  64981. var facetUV = []; // submesh UV
  64982. var facetCol = []; // submesh colors
  64983. var barycenter = BABYLON.Vector3.Zero();
  64984. var sizeO = size;
  64985. while (f < totalFacets) {
  64986. size = sizeO + Math.floor((1 + delta) * Math.random());
  64987. if (f > totalFacets - size) {
  64988. size = totalFacets - f;
  64989. }
  64990. // reset temp arrays
  64991. facetPos.length = 0;
  64992. facetInd.length = 0;
  64993. facetUV.length = 0;
  64994. facetCol.length = 0;
  64995. // iterate over "size" facets
  64996. var fi = 0;
  64997. for (var j = f * 3; j < (f + size) * 3; j++) {
  64998. facetInd.push(fi);
  64999. var i = meshInd[j];
  65000. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  65001. if (meshUV) {
  65002. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  65003. }
  65004. if (meshCol) {
  65005. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  65006. }
  65007. fi++;
  65008. }
  65009. // create a model shape for each single particle
  65010. var idx = this.nbParticles;
  65011. var shape = this._posToShape(facetPos);
  65012. var shapeUV = this._uvsToShapeUV(facetUV);
  65013. // compute the barycenter of the shape
  65014. var v;
  65015. for (v = 0; v < shape.length; v++) {
  65016. barycenter.addInPlace(shape[v]);
  65017. }
  65018. barycenter.scaleInPlace(1 / shape.length);
  65019. // shift the shape from its barycenter to the origin
  65020. for (v = 0; v < shape.length; v++) {
  65021. shape[v].subtractInPlace(barycenter);
  65022. }
  65023. var bInfo;
  65024. if (this._particlesIntersect) {
  65025. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  65026. }
  65027. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  65028. // add the particle in the SPS
  65029. var currentPos = this._positions.length;
  65030. var currentInd = this._indices.length;
  65031. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  65032. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  65033. // initialize the particle position
  65034. this.particles[this.nbParticles].position.addInPlace(barycenter);
  65035. this._index += shape.length;
  65036. idx++;
  65037. this.nbParticles++;
  65038. this._shapeCounter++;
  65039. f += size;
  65040. }
  65041. return this;
  65042. };
  65043. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  65044. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  65045. var index = 0;
  65046. var idx = 0;
  65047. for (var p = 0; p < this.particles.length; p++) {
  65048. this._particle = this.particles[p];
  65049. this._shape = this._particle._model._shape;
  65050. if (this._particle.rotationQuaternion) {
  65051. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  65052. }
  65053. else {
  65054. this._yaw = this._particle.rotation.y;
  65055. this._pitch = this._particle.rotation.x;
  65056. this._roll = this._particle.rotation.z;
  65057. this._quaternionRotationYPR();
  65058. }
  65059. this._quaternionToRotationMatrix();
  65060. this._rotMatrix.invertToRef(this._invertMatrix);
  65061. for (var pt = 0; pt < this._shape.length; pt++) {
  65062. idx = index + pt * 3;
  65063. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  65064. this._fixedNormal32[idx] = this._normal.x;
  65065. this._fixedNormal32[idx + 1] = this._normal.y;
  65066. this._fixedNormal32[idx + 2] = this._normal.z;
  65067. }
  65068. index = idx + 3;
  65069. }
  65070. };
  65071. //reset copy
  65072. SolidParticleSystem.prototype._resetCopy = function () {
  65073. this._copy.position.x = 0;
  65074. this._copy.position.y = 0;
  65075. this._copy.position.z = 0;
  65076. this._copy.rotation.x = 0;
  65077. this._copy.rotation.y = 0;
  65078. this._copy.rotation.z = 0;
  65079. this._copy.rotationQuaternion = null;
  65080. this._copy.scaling.x = 1.0;
  65081. this._copy.scaling.y = 1.0;
  65082. this._copy.scaling.z = 1.0;
  65083. this._copy.uvs.x = 0;
  65084. this._copy.uvs.y = 0;
  65085. this._copy.uvs.z = 1.0;
  65086. this._copy.uvs.w = 1.0;
  65087. this._copy.color = null;
  65088. this._copy.translateFromPivot = false;
  65089. };
  65090. // _meshBuilder : inserts the shape model in the global SPS mesh
  65091. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  65092. var i;
  65093. var u = 0;
  65094. var c = 0;
  65095. var n = 0;
  65096. this._resetCopy();
  65097. if (options && options.positionFunction) { // call to custom positionFunction
  65098. options.positionFunction(this._copy, idx, idxInShape);
  65099. this._mustUnrotateFixedNormals = true;
  65100. }
  65101. if (this._copy.rotationQuaternion) {
  65102. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  65103. }
  65104. else {
  65105. this._yaw = this._copy.rotation.y;
  65106. this._pitch = this._copy.rotation.x;
  65107. this._roll = this._copy.rotation.z;
  65108. this._quaternionRotationYPR();
  65109. }
  65110. this._quaternionToRotationMatrix();
  65111. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  65112. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  65113. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  65114. if (this._copy.translateFromPivot) {
  65115. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  65116. }
  65117. else {
  65118. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  65119. }
  65120. for (i = 0; i < shape.length; i++) {
  65121. this._vertex.x = shape[i].x;
  65122. this._vertex.y = shape[i].y;
  65123. this._vertex.z = shape[i].z;
  65124. if (options && options.vertexFunction) {
  65125. options.vertexFunction(this._copy, this._vertex, i);
  65126. }
  65127. this._vertex.x *= this._copy.scaling.x;
  65128. this._vertex.y *= this._copy.scaling.y;
  65129. this._vertex.z *= this._copy.scaling.z;
  65130. this._vertex.x -= this._scaledPivot.x;
  65131. this._vertex.y -= this._scaledPivot.y;
  65132. this._vertex.z -= this._scaledPivot.z;
  65133. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  65134. this._rotated.addInPlace(this._pivotBackTranslation);
  65135. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  65136. if (meshUV) {
  65137. uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
  65138. u += 2;
  65139. }
  65140. if (this._copy.color) {
  65141. this._color = this._copy.color;
  65142. }
  65143. else if (meshCol && meshCol[c] !== undefined) {
  65144. this._color.r = meshCol[c];
  65145. this._color.g = meshCol[c + 1];
  65146. this._color.b = meshCol[c + 2];
  65147. this._color.a = meshCol[c + 3];
  65148. }
  65149. else {
  65150. this._color.r = 1.0;
  65151. this._color.g = 1.0;
  65152. this._color.b = 1.0;
  65153. this._color.a = 1.0;
  65154. }
  65155. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  65156. c += 4;
  65157. if (!this.recomputeNormals && meshNor) {
  65158. this._normal.x = meshNor[n];
  65159. this._normal.y = meshNor[n + 1];
  65160. this._normal.z = meshNor[n + 2];
  65161. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  65162. normals.push(this._normal.x, this._normal.y, this._normal.z);
  65163. n += 3;
  65164. }
  65165. }
  65166. for (i = 0; i < meshInd.length; i++) {
  65167. var current_ind = p + meshInd[i];
  65168. indices.push(current_ind);
  65169. if (current_ind > 65535) {
  65170. this._needs32Bits = true;
  65171. }
  65172. }
  65173. if (this._pickable) {
  65174. var nbfaces = meshInd.length / 3;
  65175. for (i = 0; i < nbfaces; i++) {
  65176. this.pickedParticles.push({ idx: idx, faceId: i });
  65177. }
  65178. }
  65179. if (this._depthSort) {
  65180. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  65181. }
  65182. return this._copy;
  65183. };
  65184. // returns a shape array from positions array
  65185. SolidParticleSystem.prototype._posToShape = function (positions) {
  65186. var shape = [];
  65187. for (var i = 0; i < positions.length; i += 3) {
  65188. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  65189. }
  65190. return shape;
  65191. };
  65192. // returns a shapeUV array from a Vector4 uvs
  65193. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  65194. var shapeUV = [];
  65195. if (uvs) {
  65196. for (var i = 0; i < uvs.length; i++)
  65197. shapeUV.push(uvs[i]);
  65198. }
  65199. return shapeUV;
  65200. };
  65201. // adds a new particle object in the particles array
  65202. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  65203. if (bInfo === void 0) { bInfo = null; }
  65204. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  65205. this.particles.push(sp);
  65206. return sp;
  65207. };
  65208. /**
  65209. * Adds some particles to the SPS from the model shape. Returns the shape id.
  65210. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  65211. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  65212. * @param nb (positive integer) the number of particles to be created from this model
  65213. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  65214. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  65215. * @returns the number of shapes in the system
  65216. */
  65217. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  65218. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65219. var meshInd = mesh.getIndices();
  65220. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65221. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65222. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65223. var bbInfo;
  65224. if (this._particlesIntersect) {
  65225. bbInfo = mesh.getBoundingInfo();
  65226. }
  65227. var shape = this._posToShape(meshPos);
  65228. var shapeUV = this._uvsToShapeUV(meshUV);
  65229. var posfunc = options ? options.positionFunction : null;
  65230. var vtxfunc = options ? options.vertexFunction : null;
  65231. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  65232. // particles
  65233. var sp;
  65234. var currentCopy;
  65235. var idx = this.nbParticles;
  65236. for (var i = 0; i < nb; i++) {
  65237. var currentPos = this._positions.length;
  65238. var currentInd = this._indices.length;
  65239. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  65240. if (this._updatable) {
  65241. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  65242. sp.position.copyFrom(currentCopy.position);
  65243. sp.rotation.copyFrom(currentCopy.rotation);
  65244. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  65245. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  65246. }
  65247. if (currentCopy.color && sp.color) {
  65248. sp.color.copyFrom(currentCopy.color);
  65249. }
  65250. sp.scaling.copyFrom(currentCopy.scaling);
  65251. sp.uvs.copyFrom(currentCopy.uvs);
  65252. }
  65253. this._index += shape.length;
  65254. idx++;
  65255. }
  65256. this.nbParticles += nb;
  65257. this._shapeCounter++;
  65258. return this._shapeCounter - 1;
  65259. };
  65260. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  65261. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  65262. this._resetCopy();
  65263. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  65264. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  65265. }
  65266. if (this._copy.rotationQuaternion) {
  65267. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  65268. }
  65269. else {
  65270. this._yaw = this._copy.rotation.y;
  65271. this._pitch = this._copy.rotation.x;
  65272. this._roll = this._copy.rotation.z;
  65273. this._quaternionRotationYPR();
  65274. }
  65275. this._quaternionToRotationMatrix();
  65276. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  65277. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  65278. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  65279. if (this._copy.translateFromPivot) {
  65280. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  65281. }
  65282. else {
  65283. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  65284. }
  65285. this._shape = particle._model._shape;
  65286. for (var pt = 0; pt < this._shape.length; pt++) {
  65287. this._vertex.x = this._shape[pt].x;
  65288. this._vertex.y = this._shape[pt].y;
  65289. this._vertex.z = this._shape[pt].z;
  65290. if (particle._model._vertexFunction) {
  65291. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  65292. }
  65293. this._vertex.x *= this._copy.scaling.x;
  65294. this._vertex.y *= this._copy.scaling.y;
  65295. this._vertex.z *= this._copy.scaling.z;
  65296. this._vertex.x -= this._scaledPivot.x;
  65297. this._vertex.y -= this._scaledPivot.y;
  65298. this._vertex.z -= this._scaledPivot.z;
  65299. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  65300. this._rotated.addInPlace(this._pivotBackTranslation);
  65301. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  65302. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  65303. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  65304. }
  65305. particle.position.x = 0.0;
  65306. particle.position.y = 0.0;
  65307. particle.position.z = 0.0;
  65308. particle.rotation.x = 0.0;
  65309. particle.rotation.y = 0.0;
  65310. particle.rotation.z = 0.0;
  65311. particle.rotationQuaternion = null;
  65312. particle.scaling.x = 1.0;
  65313. particle.scaling.y = 1.0;
  65314. particle.scaling.z = 1.0;
  65315. particle.uvs.x = 0.0;
  65316. particle.uvs.y = 0.0;
  65317. particle.uvs.z = 1.0;
  65318. particle.uvs.w = 1.0;
  65319. particle.pivot.x = 0.0;
  65320. particle.pivot.y = 0.0;
  65321. particle.pivot.z = 0.0;
  65322. particle.translateFromPivot = false;
  65323. particle.parentId = null;
  65324. };
  65325. /**
  65326. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  65327. * @returns the SPS.
  65328. */
  65329. SolidParticleSystem.prototype.rebuildMesh = function () {
  65330. for (var p = 0; p < this.particles.length; p++) {
  65331. this._rebuildParticle(this.particles[p]);
  65332. }
  65333. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  65334. return this;
  65335. };
  65336. /**
  65337. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  65338. * This method calls `updateParticle()` for each particle of the SPS.
  65339. * For an animated SPS, it is usually called within the render loop.
  65340. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  65341. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  65342. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  65343. * @returns the SPS.
  65344. */
  65345. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  65346. if (start === void 0) { start = 0; }
  65347. if (end === void 0) { end = this.nbParticles - 1; }
  65348. if (update === void 0) { update = true; }
  65349. if (!this._updatable) {
  65350. return this;
  65351. }
  65352. // custom beforeUpdate
  65353. this.beforeUpdateParticles(start, end, update);
  65354. this._cam_axisX.x = 1.0;
  65355. this._cam_axisX.y = 0.0;
  65356. this._cam_axisX.z = 0.0;
  65357. this._cam_axisY.x = 0.0;
  65358. this._cam_axisY.y = 1.0;
  65359. this._cam_axisY.z = 0.0;
  65360. this._cam_axisZ.x = 0.0;
  65361. this._cam_axisZ.y = 0.0;
  65362. this._cam_axisZ.z = 1.0;
  65363. // cases when the World Matrix is to be computed first
  65364. if (this.billboard || this._depthSort) {
  65365. this.mesh.computeWorldMatrix(true);
  65366. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  65367. }
  65368. // if the particles will always face the camera
  65369. if (this.billboard) {
  65370. // compute the camera position and un-rotate it by the current mesh rotation
  65371. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  65372. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  65373. this._cam_axisZ.normalize();
  65374. // same for camera up vector extracted from the cam view matrix
  65375. var view = this._camera.getViewMatrix(true);
  65376. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  65377. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  65378. this._cam_axisY.normalize();
  65379. this._cam_axisX.normalize();
  65380. }
  65381. // if depthSort, compute the camera global position in the mesh local system
  65382. if (this._depthSort) {
  65383. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  65384. }
  65385. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  65386. var idx = 0; // current position index in the global array positions32
  65387. var index = 0; // position start index in the global array positions32 of the current particle
  65388. var colidx = 0; // current color index in the global array colors32
  65389. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  65390. var uvidx = 0; // current uv index in the global array uvs32
  65391. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  65392. var pt = 0; // current index in the particle model shape
  65393. if (this.mesh.isFacetDataEnabled) {
  65394. this._computeBoundingBox = true;
  65395. }
  65396. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  65397. if (this._computeBoundingBox) {
  65398. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  65399. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  65400. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  65401. }
  65402. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  65403. if (this.mesh._boundingInfo) {
  65404. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  65405. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  65406. }
  65407. }
  65408. }
  65409. // particle loop
  65410. index = this.particles[start]._pos;
  65411. var vpos = (index / 3) | 0;
  65412. colorIndex = vpos * 4;
  65413. uvIndex = vpos * 2;
  65414. for (var p = start; p <= end; p++) {
  65415. this._particle = this.particles[p];
  65416. this._shape = this._particle._model._shape;
  65417. this._shapeUV = this._particle._model._shapeUV;
  65418. // call to custom user function to update the particle properties
  65419. this.updateParticle(this._particle);
  65420. // camera-particle distance for depth sorting
  65421. if (this._depthSort && this._depthSortParticles) {
  65422. var dsp = this.depthSortedParticles[p];
  65423. dsp.ind = this._particle._ind;
  65424. dsp.indicesLength = this._particle._model._indicesLength;
  65425. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  65426. }
  65427. // skip the computations for inactive or already invisible particles
  65428. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  65429. // increment indexes for the next particle
  65430. pt = this._shape.length;
  65431. index += pt * 3;
  65432. colorIndex += pt * 4;
  65433. uvIndex += pt * 2;
  65434. continue;
  65435. }
  65436. if (this._particle.isVisible) {
  65437. this._particle._stillInvisible = false; // un-mark permanent invisibility
  65438. this._particleHasParent = (this._particle.parentId !== null);
  65439. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  65440. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  65441. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  65442. // particle rotation matrix
  65443. if (this.billboard) {
  65444. this._particle.rotation.x = 0.0;
  65445. this._particle.rotation.y = 0.0;
  65446. }
  65447. if (this._computeParticleRotation || this.billboard) {
  65448. if (this._particle.rotationQuaternion) {
  65449. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  65450. }
  65451. else {
  65452. this._yaw = this._particle.rotation.y;
  65453. this._pitch = this._particle.rotation.x;
  65454. this._roll = this._particle.rotation.z;
  65455. this._quaternionRotationYPR();
  65456. }
  65457. this._quaternionToRotationMatrix();
  65458. }
  65459. if (this._particleHasParent) {
  65460. this._parent = this.particles[this._particle.parentId];
  65461. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  65462. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  65463. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  65464. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  65465. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  65466. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  65467. if (this._computeParticleRotation || this.billboard) {
  65468. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  65469. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  65470. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  65471. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  65472. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  65473. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  65474. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  65475. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  65476. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  65477. }
  65478. }
  65479. else {
  65480. this._particle._globalPosition.x = this._particle.position.x;
  65481. this._particle._globalPosition.y = this._particle.position.y;
  65482. this._particle._globalPosition.z = this._particle.position.z;
  65483. if (this._computeParticleRotation || this.billboard) {
  65484. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  65485. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  65486. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  65487. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  65488. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  65489. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  65490. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  65491. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  65492. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  65493. }
  65494. }
  65495. if (this._particle.translateFromPivot) {
  65496. this._pivotBackTranslation.x = 0.0;
  65497. this._pivotBackTranslation.y = 0.0;
  65498. this._pivotBackTranslation.z = 0.0;
  65499. }
  65500. else {
  65501. this._pivotBackTranslation.x = this._scaledPivot.x;
  65502. this._pivotBackTranslation.y = this._scaledPivot.y;
  65503. this._pivotBackTranslation.z = this._scaledPivot.z;
  65504. }
  65505. // particle vertex loop
  65506. for (pt = 0; pt < this._shape.length; pt++) {
  65507. idx = index + pt * 3;
  65508. colidx = colorIndex + pt * 4;
  65509. uvidx = uvIndex + pt * 2;
  65510. this._vertex.x = this._shape[pt].x;
  65511. this._vertex.y = this._shape[pt].y;
  65512. this._vertex.z = this._shape[pt].z;
  65513. if (this._computeParticleVertex) {
  65514. this.updateParticleVertex(this._particle, this._vertex, pt);
  65515. }
  65516. // positions
  65517. this._vertex.x *= this._particle.scaling.x;
  65518. this._vertex.y *= this._particle.scaling.y;
  65519. this._vertex.z *= this._particle.scaling.z;
  65520. this._vertex.x -= this._scaledPivot.x;
  65521. this._vertex.y -= this._scaledPivot.y;
  65522. this._vertex.z -= this._scaledPivot.z;
  65523. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  65524. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  65525. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  65526. this._rotated.x += this._pivotBackTranslation.x;
  65527. this._rotated.y += this._pivotBackTranslation.y;
  65528. this._rotated.z += this._pivotBackTranslation.z;
  65529. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  65530. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  65531. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  65532. if (this._computeBoundingBox) {
  65533. if (this._positions32[idx] < this._minimum.x) {
  65534. this._minimum.x = this._positions32[idx];
  65535. }
  65536. if (this._positions32[idx] > this._maximum.x) {
  65537. this._maximum.x = this._positions32[idx];
  65538. }
  65539. if (this._positions32[idx + 1] < this._minimum.y) {
  65540. this._minimum.y = this._positions32[idx + 1];
  65541. }
  65542. if (this._positions32[idx + 1] > this._maximum.y) {
  65543. this._maximum.y = this._positions32[idx + 1];
  65544. }
  65545. if (this._positions32[idx + 2] < this._minimum.z) {
  65546. this._minimum.z = this._positions32[idx + 2];
  65547. }
  65548. if (this._positions32[idx + 2] > this._maximum.z) {
  65549. this._maximum.z = this._positions32[idx + 2];
  65550. }
  65551. }
  65552. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  65553. if (!this._computeParticleVertex) {
  65554. this._normal.x = this._fixedNormal32[idx];
  65555. this._normal.y = this._fixedNormal32[idx + 1];
  65556. this._normal.z = this._fixedNormal32[idx + 2];
  65557. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  65558. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  65559. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  65560. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  65561. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  65562. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  65563. }
  65564. if (this._computeParticleColor && this._particle.color) {
  65565. this._colors32[colidx] = this._particle.color.r;
  65566. this._colors32[colidx + 1] = this._particle.color.g;
  65567. this._colors32[colidx + 2] = this._particle.color.b;
  65568. this._colors32[colidx + 3] = this._particle.color.a;
  65569. }
  65570. if (this._computeParticleTexture) {
  65571. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  65572. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  65573. }
  65574. }
  65575. }
  65576. // particle just set invisible : scaled to zero and positioned at the origin
  65577. else {
  65578. this._particle._stillInvisible = true; // mark the particle as invisible
  65579. for (pt = 0; pt < this._shape.length; pt++) {
  65580. idx = index + pt * 3;
  65581. colidx = colorIndex + pt * 4;
  65582. uvidx = uvIndex + pt * 2;
  65583. this._positions32[idx] = 0.0;
  65584. this._positions32[idx + 1] = 0.0;
  65585. this._positions32[idx + 2] = 0.0;
  65586. this._normals32[idx] = 0.0;
  65587. this._normals32[idx + 1] = 0.0;
  65588. this._normals32[idx + 2] = 0.0;
  65589. if (this._computeParticleColor && this._particle.color) {
  65590. this._colors32[colidx] = this._particle.color.r;
  65591. this._colors32[colidx + 1] = this._particle.color.g;
  65592. this._colors32[colidx + 2] = this._particle.color.b;
  65593. this._colors32[colidx + 3] = this._particle.color.a;
  65594. }
  65595. if (this._computeParticleTexture) {
  65596. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  65597. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  65598. }
  65599. }
  65600. }
  65601. // if the particle intersections must be computed : update the bbInfo
  65602. if (this._particlesIntersect) {
  65603. var bInfo = this._particle._boundingInfo;
  65604. var bBox = bInfo.boundingBox;
  65605. var bSphere = bInfo.boundingSphere;
  65606. if (!this._bSphereOnly) {
  65607. // place, scale and rotate the particle bbox within the SPS local system, then update it
  65608. for (var b = 0; b < bBox.vectors.length; b++) {
  65609. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  65610. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  65611. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  65612. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  65613. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  65614. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  65615. bBox.vectors[b].x = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  65616. bBox.vectors[b].y = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  65617. bBox.vectors[b].z = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  65618. }
  65619. bBox._update(this.mesh._worldMatrix);
  65620. }
  65621. // place and scale the particle bouding sphere in the SPS local system, then update it
  65622. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  65623. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  65624. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  65625. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  65626. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  65627. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  65628. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  65629. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  65630. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  65631. bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));
  65632. bSphere._update(this.mesh._worldMatrix);
  65633. }
  65634. // increment indexes for the next particle
  65635. index = idx + 3;
  65636. colorIndex = colidx + 4;
  65637. uvIndex = uvidx + 2;
  65638. }
  65639. // if the VBO must be updated
  65640. if (update) {
  65641. if (this._computeParticleColor) {
  65642. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  65643. }
  65644. if (this._computeParticleTexture) {
  65645. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  65646. }
  65647. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  65648. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  65649. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  65650. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  65651. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  65652. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  65653. for (var i = 0; i < this._normals32.length; i++) {
  65654. this._fixedNormal32[i] = this._normals32[i];
  65655. }
  65656. }
  65657. if (!this.mesh.areNormalsFrozen) {
  65658. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  65659. }
  65660. }
  65661. if (this._depthSort && this._depthSortParticles) {
  65662. this.depthSortedParticles.sort(this._depthSortFunction);
  65663. var dspl = this.depthSortedParticles.length;
  65664. var sorted = 0;
  65665. var lind = 0;
  65666. var sind = 0;
  65667. var sid = 0;
  65668. for (sorted = 0; sorted < dspl; sorted++) {
  65669. lind = this.depthSortedParticles[sorted].indicesLength;
  65670. sind = this.depthSortedParticles[sorted].ind;
  65671. for (var i = 0; i < lind; i++) {
  65672. this._indices32[sid] = this._indices[sind + i];
  65673. sid++;
  65674. }
  65675. }
  65676. this.mesh.updateIndices(this._indices32);
  65677. }
  65678. }
  65679. if (this._computeBoundingBox) {
  65680. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  65681. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  65682. }
  65683. this.afterUpdateParticles(start, end, update);
  65684. return this;
  65685. };
  65686. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  65687. this._halfroll = this._roll * 0.5;
  65688. this._halfpitch = this._pitch * 0.5;
  65689. this._halfyaw = this._yaw * 0.5;
  65690. this._sinRoll = Math.sin(this._halfroll);
  65691. this._cosRoll = Math.cos(this._halfroll);
  65692. this._sinPitch = Math.sin(this._halfpitch);
  65693. this._cosPitch = Math.cos(this._halfpitch);
  65694. this._sinYaw = Math.sin(this._halfyaw);
  65695. this._cosYaw = Math.cos(this._halfyaw);
  65696. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  65697. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  65698. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  65699. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  65700. };
  65701. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  65702. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  65703. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  65704. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  65705. this._rotMatrix.m[3] = 0;
  65706. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  65707. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  65708. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  65709. this._rotMatrix.m[7] = 0;
  65710. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  65711. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  65712. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  65713. this._rotMatrix.m[11] = 0;
  65714. this._rotMatrix.m[12] = 0;
  65715. this._rotMatrix.m[13] = 0;
  65716. this._rotMatrix.m[14] = 0;
  65717. this._rotMatrix.m[15] = 1.0;
  65718. };
  65719. /**
  65720. * Disposes the SPS.
  65721. */
  65722. SolidParticleSystem.prototype.dispose = function () {
  65723. this.mesh.dispose();
  65724. this.vars = null;
  65725. // drop references to internal big arrays for the GC
  65726. this._positions = null;
  65727. this._indices = null;
  65728. this._normals = null;
  65729. this._uvs = null;
  65730. this._colors = null;
  65731. this._indices32 = null;
  65732. this._positions32 = null;
  65733. this._normals32 = null;
  65734. this._fixedNormal32 = null;
  65735. this._uvs32 = null;
  65736. this._colors32 = null;
  65737. this.pickedParticles = null;
  65738. };
  65739. /**
  65740. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  65741. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65742. * @returns the SPS.
  65743. */
  65744. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  65745. if (!this._isVisibilityBoxLocked) {
  65746. this.mesh.refreshBoundingInfo();
  65747. }
  65748. return this;
  65749. };
  65750. /**
  65751. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  65752. * @param size the size (float) of the visibility box
  65753. * note : this doesn't lock the SPS mesh bounding box.
  65754. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65755. */
  65756. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  65757. var vis = size / 2;
  65758. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  65759. };
  65760. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  65761. /**
  65762. * Gets whether the SPS as always visible or not
  65763. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65764. */
  65765. get: function () {
  65766. return this._alwaysVisible;
  65767. },
  65768. /**
  65769. * Sets the SPS as always visible or not
  65770. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65771. */
  65772. set: function (val) {
  65773. this._alwaysVisible = val;
  65774. this.mesh.alwaysSelectAsActiveMesh = val;
  65775. },
  65776. enumerable: true,
  65777. configurable: true
  65778. });
  65779. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  65780. /**
  65781. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  65782. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65783. */
  65784. get: function () {
  65785. return this._isVisibilityBoxLocked;
  65786. },
  65787. /**
  65788. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  65789. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65790. */
  65791. set: function (val) {
  65792. this._isVisibilityBoxLocked = val;
  65793. var boundingInfo = this.mesh.getBoundingInfo();
  65794. boundingInfo.isLocked = val;
  65795. },
  65796. enumerable: true,
  65797. configurable: true
  65798. });
  65799. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  65800. /**
  65801. * Gets if `setParticles()` computes the particle rotations or not.
  65802. * Default value : true. The SPS is faster when it's set to false.
  65803. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  65804. */
  65805. get: function () {
  65806. return this._computeParticleRotation;
  65807. },
  65808. /**
  65809. * Tells to `setParticles()` to compute the particle rotations or not.
  65810. * Default value : true. The SPS is faster when it's set to false.
  65811. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  65812. */
  65813. set: function (val) {
  65814. this._computeParticleRotation = val;
  65815. },
  65816. enumerable: true,
  65817. configurable: true
  65818. });
  65819. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  65820. /**
  65821. * Gets if `setParticles()` computes the particle colors or not.
  65822. * Default value : true. The SPS is faster when it's set to false.
  65823. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  65824. */
  65825. get: function () {
  65826. return this._computeParticleColor;
  65827. },
  65828. /**
  65829. * Tells to `setParticles()` to compute the particle colors or not.
  65830. * Default value : true. The SPS is faster when it's set to false.
  65831. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  65832. */
  65833. set: function (val) {
  65834. this._computeParticleColor = val;
  65835. },
  65836. enumerable: true,
  65837. configurable: true
  65838. });
  65839. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  65840. /**
  65841. * Gets if `setParticles()` computes the particle textures or not.
  65842. * Default value : true. The SPS is faster when it's set to false.
  65843. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  65844. */
  65845. get: function () {
  65846. return this._computeParticleTexture;
  65847. },
  65848. set: function (val) {
  65849. this._computeParticleTexture = val;
  65850. },
  65851. enumerable: true,
  65852. configurable: true
  65853. });
  65854. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  65855. /**
  65856. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  65857. * Default value : false. The SPS is faster when it's set to false.
  65858. * Note : the particle custom vertex positions aren't stored values.
  65859. */
  65860. get: function () {
  65861. return this._computeParticleVertex;
  65862. },
  65863. /**
  65864. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  65865. * Default value : false. The SPS is faster when it's set to false.
  65866. * Note : the particle custom vertex positions aren't stored values.
  65867. */
  65868. set: function (val) {
  65869. this._computeParticleVertex = val;
  65870. },
  65871. enumerable: true,
  65872. configurable: true
  65873. });
  65874. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  65875. /**
  65876. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  65877. */
  65878. get: function () {
  65879. return this._computeBoundingBox;
  65880. },
  65881. /**
  65882. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  65883. */
  65884. set: function (val) {
  65885. this._computeBoundingBox = val;
  65886. },
  65887. enumerable: true,
  65888. configurable: true
  65889. });
  65890. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  65891. /**
  65892. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  65893. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  65894. * Default : `true`
  65895. */
  65896. get: function () {
  65897. return this._depthSortParticles;
  65898. },
  65899. /**
  65900. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  65901. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  65902. * Default : `true`
  65903. */
  65904. set: function (val) {
  65905. this._depthSortParticles = val;
  65906. },
  65907. enumerable: true,
  65908. configurable: true
  65909. });
  65910. // =======================================================================
  65911. // Particle behavior logic
  65912. // these following methods may be overwritten by the user to fit his needs
  65913. /**
  65914. * This function does nothing. It may be overwritten to set all the particle first values.
  65915. * The SPS doesn't call this function, you may have to call it by your own.
  65916. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65917. */
  65918. SolidParticleSystem.prototype.initParticles = function () {
  65919. };
  65920. /**
  65921. * This function does nothing. It may be overwritten to recycle a particle.
  65922. * The SPS doesn't call this function, you may have to call it by your own.
  65923. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65924. * @param particle The particle to recycle
  65925. * @returns the recycled particle
  65926. */
  65927. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  65928. return particle;
  65929. };
  65930. /**
  65931. * Updates a particle : this function should be overwritten by the user.
  65932. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  65933. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65934. * @example : just set a particle position or velocity and recycle conditions
  65935. * @param particle The particle to update
  65936. * @returns the updated particle
  65937. */
  65938. SolidParticleSystem.prototype.updateParticle = function (particle) {
  65939. return particle;
  65940. };
  65941. /**
  65942. * Updates a vertex of a particle : it can be overwritten by the user.
  65943. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  65944. * @param particle the current particle
  65945. * @param vertex the current index of the current particle
  65946. * @param pt the index of the current vertex in the particle shape
  65947. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  65948. * @example : just set a vertex particle position
  65949. * @returns the updated vertex
  65950. */
  65951. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  65952. return vertex;
  65953. };
  65954. /**
  65955. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  65956. * This does nothing and may be overwritten by the user.
  65957. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65958. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65959. * @param update the boolean update value actually passed to setParticles()
  65960. */
  65961. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  65962. };
  65963. /**
  65964. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  65965. * This will be passed three parameters.
  65966. * This does nothing and may be overwritten by the user.
  65967. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65968. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65969. * @param update the boolean update value actually passed to setParticles()
  65970. */
  65971. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  65972. };
  65973. return SolidParticleSystem;
  65974. }());
  65975. BABYLON.SolidParticleSystem = SolidParticleSystem;
  65976. })(BABYLON || (BABYLON = {}));
  65977. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  65978. var BABYLON;
  65979. (function (BABYLON) {
  65980. /**
  65981. * Class containing static functions to help procedurally build meshes
  65982. */
  65983. var MeshBuilder = /** @class */ (function () {
  65984. function MeshBuilder() {
  65985. }
  65986. MeshBuilder.updateSideOrientation = function (orientation) {
  65987. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  65988. return BABYLON.Mesh.DOUBLESIDE;
  65989. }
  65990. if (orientation === undefined || orientation === null) {
  65991. return BABYLON.Mesh.FRONTSIDE;
  65992. }
  65993. return orientation;
  65994. };
  65995. /**
  65996. * Creates a box mesh
  65997. * * The parameter `size` sets the size (float) of each box side (default 1)
  65998. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  65999. * * 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)
  66000. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  66001. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66002. * * 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
  66003. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66004. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  66005. * @param name defines the name of the mesh
  66006. * @param options defines the options used to create the mesh
  66007. * @param scene defines the hosting scene
  66008. * @returns the box mesh
  66009. */
  66010. MeshBuilder.CreateBox = function (name, options, scene) {
  66011. if (scene === void 0) { scene = null; }
  66012. var box = new BABYLON.Mesh(name, scene);
  66013. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66014. box._originalBuilderSideOrientation = options.sideOrientation;
  66015. var vertexData = BABYLON.VertexData.CreateBox(options);
  66016. vertexData.applyToMesh(box, options.updatable);
  66017. return box;
  66018. };
  66019. /**
  66020. * Creates a sphere mesh
  66021. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  66022. * * 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`)
  66023. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  66024. * * 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
  66025. * * 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)
  66026. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66027. * * 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
  66028. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66029. * @param name defines the name of the mesh
  66030. * @param options defines the options used to create the mesh
  66031. * @param scene defines the hosting scene
  66032. * @returns the sphere mesh
  66033. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  66034. */
  66035. MeshBuilder.CreateSphere = function (name, options, scene) {
  66036. var sphere = new BABYLON.Mesh(name, scene);
  66037. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66038. sphere._originalBuilderSideOrientation = options.sideOrientation;
  66039. var vertexData = BABYLON.VertexData.CreateSphere(options);
  66040. vertexData.applyToMesh(sphere, options.updatable);
  66041. return sphere;
  66042. };
  66043. /**
  66044. * Creates a plane polygonal mesh. By default, this is a disc
  66045. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  66046. * * 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
  66047. * * 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
  66048. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66049. * * 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
  66050. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66051. * @param name defines the name of the mesh
  66052. * @param options defines the options used to create the mesh
  66053. * @param scene defines the hosting scene
  66054. * @returns the plane polygonal mesh
  66055. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  66056. */
  66057. MeshBuilder.CreateDisc = function (name, options, scene) {
  66058. if (scene === void 0) { scene = null; }
  66059. var disc = new BABYLON.Mesh(name, scene);
  66060. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66061. disc._originalBuilderSideOrientation = options.sideOrientation;
  66062. var vertexData = BABYLON.VertexData.CreateDisc(options);
  66063. vertexData.applyToMesh(disc, options.updatable);
  66064. return disc;
  66065. };
  66066. /**
  66067. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  66068. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  66069. * * 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`)
  66070. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  66071. * * 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
  66072. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66073. * * 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
  66074. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66075. * @param name defines the name of the mesh
  66076. * @param options defines the options used to create the mesh
  66077. * @param scene defines the hosting scene
  66078. * @returns the icosahedron mesh
  66079. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  66080. */
  66081. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  66082. var sphere = new BABYLON.Mesh(name, scene);
  66083. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66084. sphere._originalBuilderSideOrientation = options.sideOrientation;
  66085. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  66086. vertexData.applyToMesh(sphere, options.updatable);
  66087. return sphere;
  66088. };
  66089. ;
  66090. /**
  66091. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  66092. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  66093. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  66094. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  66095. * * 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
  66096. * * 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
  66097. * * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  66098. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66099. * * 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
  66100. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66101. * * 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
  66102. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  66103. * * 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
  66104. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  66105. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66106. * @param name defines the name of the mesh
  66107. * @param options defines the options used to create the mesh
  66108. * @param scene defines the hosting scene
  66109. * @returns the ribbon mesh
  66110. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  66111. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66112. */
  66113. MeshBuilder.CreateRibbon = function (name, options, scene) {
  66114. if (scene === void 0) { scene = null; }
  66115. var pathArray = options.pathArray;
  66116. var closeArray = options.closeArray;
  66117. var closePath = options.closePath;
  66118. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66119. var instance = options.instance;
  66120. var updatable = options.updatable;
  66121. if (instance) { // existing ribbon instance update
  66122. // positionFunction : ribbon case
  66123. // only pathArray and sideOrientation parameters are taken into account for positions update
  66124. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  66125. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  66126. var positionFunction = function (positions) {
  66127. var minlg = pathArray[0].length;
  66128. var i = 0;
  66129. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  66130. for (var si = 1; si <= ns; si++) {
  66131. for (var p = 0; p < pathArray.length; p++) {
  66132. var path = pathArray[p];
  66133. var l = path.length;
  66134. minlg = (minlg < l) ? minlg : l;
  66135. var j = 0;
  66136. while (j < minlg) {
  66137. positions[i] = path[j].x;
  66138. positions[i + 1] = path[j].y;
  66139. positions[i + 2] = path[j].z;
  66140. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  66141. BABYLON.Tmp.Vector3[0].x = path[j].x;
  66142. }
  66143. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  66144. BABYLON.Tmp.Vector3[1].x = path[j].x;
  66145. }
  66146. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  66147. BABYLON.Tmp.Vector3[0].y = path[j].y;
  66148. }
  66149. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  66150. BABYLON.Tmp.Vector3[1].y = path[j].y;
  66151. }
  66152. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  66153. BABYLON.Tmp.Vector3[0].z = path[j].z;
  66154. }
  66155. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  66156. BABYLON.Tmp.Vector3[1].z = path[j].z;
  66157. }
  66158. j++;
  66159. i += 3;
  66160. }
  66161. if (instance._closePath) {
  66162. positions[i] = path[0].x;
  66163. positions[i + 1] = path[0].y;
  66164. positions[i + 2] = path[0].z;
  66165. i += 3;
  66166. }
  66167. }
  66168. }
  66169. };
  66170. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66171. positionFunction(positions);
  66172. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  66173. instance._boundingInfo.update(instance._worldMatrix);
  66174. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  66175. if (options.colors) {
  66176. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66177. for (var c = 0; c < options.colors.length; c++) {
  66178. colors[c * 4] = options.colors[c].r;
  66179. colors[c * 4 + 1] = options.colors[c].g;
  66180. colors[c * 4 + 2] = options.colors[c].b;
  66181. colors[c * 4 + 3] = options.colors[c].a;
  66182. }
  66183. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  66184. }
  66185. if (options.uvs) {
  66186. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66187. for (var i = 0; i < options.uvs.length; i++) {
  66188. uvs[i * 2] = options.uvs[i].x;
  66189. uvs[i * 2 + 1] = options.uvs[i].y;
  66190. }
  66191. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  66192. }
  66193. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  66194. var indices = instance.getIndices();
  66195. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66196. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  66197. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  66198. if (instance._closePath) {
  66199. var indexFirst = 0;
  66200. var indexLast = 0;
  66201. for (var p = 0; p < pathArray.length; p++) {
  66202. indexFirst = instance._idx[p] * 3;
  66203. if (p + 1 < pathArray.length) {
  66204. indexLast = (instance._idx[p + 1] - 1) * 3;
  66205. }
  66206. else {
  66207. indexLast = normals.length - 3;
  66208. }
  66209. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  66210. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  66211. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  66212. normals[indexLast] = normals[indexFirst];
  66213. normals[indexLast + 1] = normals[indexFirst + 1];
  66214. normals[indexLast + 2] = normals[indexFirst + 2];
  66215. }
  66216. }
  66217. if (!(instance.areNormalsFrozen)) {
  66218. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  66219. }
  66220. }
  66221. return instance;
  66222. }
  66223. else { // new ribbon creation
  66224. var ribbon = new BABYLON.Mesh(name, scene);
  66225. ribbon._originalBuilderSideOrientation = sideOrientation;
  66226. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  66227. if (closePath) {
  66228. ribbon._idx = vertexData._idx;
  66229. }
  66230. ribbon._closePath = closePath;
  66231. ribbon._closeArray = closeArray;
  66232. vertexData.applyToMesh(ribbon, updatable);
  66233. return ribbon;
  66234. }
  66235. };
  66236. /**
  66237. * Creates a cylinder or a cone mesh
  66238. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  66239. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  66240. * * 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.
  66241. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  66242. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  66243. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  66244. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  66245. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  66246. * * 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).
  66247. * * 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
  66248. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  66249. * * 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
  66250. * * 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.
  66251. * * If `enclose` is false, a ring surface is one element.
  66252. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  66253. * * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379
  66254. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66255. * * 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
  66256. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66257. * @param name defines the name of the mesh
  66258. * @param options defines the options used to create the mesh
  66259. * @param scene defines the hosting scene
  66260. * @returns the cylinder mesh
  66261. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  66262. */
  66263. MeshBuilder.CreateCylinder = function (name, options, scene) {
  66264. var cylinder = new BABYLON.Mesh(name, scene);
  66265. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66266. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  66267. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  66268. vertexData.applyToMesh(cylinder, options.updatable);
  66269. return cylinder;
  66270. };
  66271. /**
  66272. * Creates a torus mesh
  66273. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  66274. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  66275. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  66276. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66277. * * 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
  66278. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66279. * @param name defines the name of the mesh
  66280. * @param options defines the options used to create the mesh
  66281. * @param scene defines the hosting scene
  66282. * @returns the torus mesh
  66283. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  66284. */
  66285. MeshBuilder.CreateTorus = function (name, options, scene) {
  66286. var torus = new BABYLON.Mesh(name, scene);
  66287. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66288. torus._originalBuilderSideOrientation = options.sideOrientation;
  66289. var vertexData = BABYLON.VertexData.CreateTorus(options);
  66290. vertexData.applyToMesh(torus, options.updatable);
  66291. return torus;
  66292. };
  66293. /**
  66294. * Creates a torus knot mesh
  66295. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  66296. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  66297. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  66298. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  66299. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66300. * * 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
  66301. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66302. * @param name defines the name of the mesh
  66303. * @param options defines the options used to create the mesh
  66304. * @param scene defines the hosting scene
  66305. * @returns the torus knot mesh
  66306. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  66307. */
  66308. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  66309. var torusKnot = new BABYLON.Mesh(name, scene);
  66310. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66311. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  66312. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  66313. vertexData.applyToMesh(torusKnot, options.updatable);
  66314. return torusKnot;
  66315. };
  66316. /**
  66317. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  66318. * * 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
  66319. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  66320. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  66321. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  66322. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  66323. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  66324. * * Updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  66325. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  66326. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66327. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  66328. * @param name defines the name of the new line system
  66329. * @param options defines the options used to create the line system
  66330. * @param scene defines the hosting scene
  66331. * @returns a new line system mesh
  66332. */
  66333. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  66334. var instance = options.instance;
  66335. var lines = options.lines;
  66336. var colors = options.colors;
  66337. if (instance) { // lines update
  66338. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66339. var vertexColor;
  66340. var lineColors;
  66341. if (colors) {
  66342. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66343. }
  66344. var i = 0;
  66345. var c = 0;
  66346. for (var l = 0; l < lines.length; l++) {
  66347. var points = lines[l];
  66348. for (var p = 0; p < points.length; p++) {
  66349. positions[i] = points[p].x;
  66350. positions[i + 1] = points[p].y;
  66351. positions[i + 2] = points[p].z;
  66352. if (colors && vertexColor) {
  66353. lineColors = colors[l];
  66354. vertexColor[c] = lineColors[p].r;
  66355. vertexColor[c + 1] = lineColors[p].g;
  66356. vertexColor[c + 2] = lineColors[p].b;
  66357. vertexColor[c + 3] = lineColors[p].a;
  66358. c += 4;
  66359. }
  66360. i += 3;
  66361. }
  66362. }
  66363. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  66364. if (colors && vertexColor) {
  66365. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  66366. }
  66367. return instance;
  66368. }
  66369. // line system creation
  66370. var useVertexColor = (colors) ? true : false;
  66371. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  66372. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  66373. vertexData.applyToMesh(lineSystem, options.updatable);
  66374. return lineSystem;
  66375. };
  66376. /**
  66377. * Creates a line mesh
  66378. * 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
  66379. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  66380. * * The parameter `points` is an array successive Vector3
  66381. * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  66382. * * The optional parameter `colors` is an array of successive Color4, one per line point
  66383. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  66384. * * When updating an instance, remember that only point positions can change, not the number of points
  66385. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66386. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  66387. * @param name defines the name of the new line system
  66388. * @param options defines the options used to create the line system
  66389. * @param scene defines the hosting scene
  66390. * @returns a new line mesh
  66391. */
  66392. MeshBuilder.CreateLines = function (name, options, scene) {
  66393. if (scene === void 0) { scene = null; }
  66394. var colors = (options.colors) ? [options.colors] : null;
  66395. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  66396. return lines;
  66397. };
  66398. /**
  66399. * Creates a dashed line mesh
  66400. * * 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
  66401. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  66402. * * The parameter `points` is an array successive Vector3
  66403. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  66404. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  66405. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  66406. * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  66407. * * When updating an instance, remember that only point positions can change, not the number of points
  66408. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66409. * @param name defines the name of the mesh
  66410. * @param options defines the options used to create the mesh
  66411. * @param scene defines the hosting scene
  66412. * @returns the dashed line mesh
  66413. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  66414. */
  66415. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  66416. if (scene === void 0) { scene = null; }
  66417. var points = options.points;
  66418. var instance = options.instance;
  66419. var gapSize = options.gapSize || 1;
  66420. var dashSize = options.dashSize || 3;
  66421. if (instance) { // dashed lines update
  66422. var positionFunction = function (positions) {
  66423. var curvect = BABYLON.Vector3.Zero();
  66424. var nbSeg = positions.length / 6;
  66425. var lg = 0;
  66426. var nb = 0;
  66427. var shft = 0;
  66428. var dashshft = 0;
  66429. var curshft = 0;
  66430. var p = 0;
  66431. var i = 0;
  66432. var j = 0;
  66433. for (i = 0; i < points.length - 1; i++) {
  66434. points[i + 1].subtractToRef(points[i], curvect);
  66435. lg += curvect.length();
  66436. }
  66437. shft = lg / nbSeg;
  66438. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  66439. for (i = 0; i < points.length - 1; i++) {
  66440. points[i + 1].subtractToRef(points[i], curvect);
  66441. nb = Math.floor(curvect.length() / shft);
  66442. curvect.normalize();
  66443. j = 0;
  66444. while (j < nb && p < positions.length) {
  66445. curshft = shft * j;
  66446. positions[p] = points[i].x + curshft * curvect.x;
  66447. positions[p + 1] = points[i].y + curshft * curvect.y;
  66448. positions[p + 2] = points[i].z + curshft * curvect.z;
  66449. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  66450. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  66451. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  66452. p += 6;
  66453. j++;
  66454. }
  66455. }
  66456. while (p < positions.length) {
  66457. positions[p] = points[i].x;
  66458. positions[p + 1] = points[i].y;
  66459. positions[p + 2] = points[i].z;
  66460. p += 3;
  66461. }
  66462. };
  66463. instance.updateMeshPositions(positionFunction, false);
  66464. return instance;
  66465. }
  66466. // dashed lines creation
  66467. var dashedLines = new BABYLON.LinesMesh(name, scene);
  66468. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  66469. vertexData.applyToMesh(dashedLines, options.updatable);
  66470. dashedLines.dashSize = dashSize;
  66471. dashedLines.gapSize = gapSize;
  66472. return dashedLines;
  66473. };
  66474. /**
  66475. * 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.
  66476. * * 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.
  66477. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  66478. * * 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.
  66479. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  66480. * * 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
  66481. * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  66482. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  66483. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66484. * * 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
  66485. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  66486. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66487. * @param name defines the name of the mesh
  66488. * @param options defines the options used to create the mesh
  66489. * @param scene defines the hosting scene
  66490. * @returns the extruded shape mesh
  66491. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66492. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  66493. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  66494. */
  66495. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  66496. if (scene === void 0) { scene = null; }
  66497. var path = options.path;
  66498. var shape = options.shape;
  66499. var scale = options.scale || 1;
  66500. var rotation = options.rotation || 0;
  66501. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  66502. var updatable = options.updatable;
  66503. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66504. var instance = options.instance || null;
  66505. var invertUV = options.invertUV || false;
  66506. 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);
  66507. };
  66508. /**
  66509. * Creates an custom extruded shape mesh.
  66510. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  66511. * * 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.
  66512. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  66513. * * 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
  66514. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  66515. * * 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
  66516. * * It must returns a float value that will be the scale value applied to the shape on each path point
  66517. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  66518. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  66519. * * 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
  66520. * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  66521. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  66522. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66523. * * 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
  66524. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66525. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66526. * @param name defines the name of the mesh
  66527. * @param options defines the options used to create the mesh
  66528. * @param scene defines the hosting scene
  66529. * @returns the custom extruded shape mesh
  66530. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  66531. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66532. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  66533. */
  66534. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  66535. var path = options.path;
  66536. var shape = options.shape;
  66537. var scaleFunction = options.scaleFunction || (function () { return 1; });
  66538. var rotationFunction = options.rotationFunction || (function () { return 0; });
  66539. var ribbonCloseArray = options.ribbonCloseArray || false;
  66540. var ribbonClosePath = options.ribbonClosePath || false;
  66541. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  66542. var updatable = options.updatable;
  66543. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66544. var instance = options.instance;
  66545. var invertUV = options.invertUV || false;
  66546. 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);
  66547. };
  66548. /**
  66549. * Creates lathe mesh.
  66550. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  66551. * * 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
  66552. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  66553. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  66554. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  66555. * * 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
  66556. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  66557. * * 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
  66558. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66559. * * 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
  66560. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66561. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66562. * @param name defines the name of the mesh
  66563. * @param options defines the options used to create the mesh
  66564. * @param scene defines the hosting scene
  66565. * @returns the lathe mesh
  66566. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  66567. */
  66568. MeshBuilder.CreateLathe = function (name, options, scene) {
  66569. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  66570. var closed = (options.closed === undefined) ? true : options.closed;
  66571. var shape = options.shape;
  66572. var radius = options.radius || 1;
  66573. var tessellation = options.tessellation || 64;
  66574. var clip = options.clip || 0;
  66575. var updatable = options.updatable;
  66576. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66577. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  66578. var pi2 = Math.PI * 2;
  66579. var paths = new Array();
  66580. var invertUV = options.invertUV || false;
  66581. var i = 0;
  66582. var p = 0;
  66583. var step = pi2 / tessellation * arc;
  66584. var rotated;
  66585. var path = new Array();
  66586. for (i = 0; i <= tessellation - clip; i++) {
  66587. var path = [];
  66588. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  66589. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  66590. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  66591. }
  66592. for (p = 0; p < shape.length; p++) {
  66593. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  66594. path.push(rotated);
  66595. }
  66596. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  66597. 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));
  66598. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  66599. }
  66600. paths.push(path);
  66601. }
  66602. // lathe ribbon
  66603. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  66604. return lathe;
  66605. };
  66606. /**
  66607. * Creates a plane mesh
  66608. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  66609. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  66610. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  66611. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66612. * * 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
  66613. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66614. * @param name defines the name of the mesh
  66615. * @param options defines the options used to create the mesh
  66616. * @param scene defines the hosting scene
  66617. * @returns the plane mesh
  66618. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  66619. */
  66620. MeshBuilder.CreatePlane = function (name, options, scene) {
  66621. var plane = new BABYLON.Mesh(name, scene);
  66622. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66623. plane._originalBuilderSideOrientation = options.sideOrientation;
  66624. var vertexData = BABYLON.VertexData.CreatePlane(options);
  66625. vertexData.applyToMesh(plane, options.updatable);
  66626. if (options.sourcePlane) {
  66627. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  66628. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  66629. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  66630. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  66631. plane.rotate(vectorProduct, product);
  66632. }
  66633. }
  66634. return plane;
  66635. };
  66636. /**
  66637. * Creates a ground mesh
  66638. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  66639. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  66640. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66641. * @param name defines the name of the mesh
  66642. * @param options defines the options used to create the mesh
  66643. * @param scene defines the hosting scene
  66644. * @returns the ground mesh
  66645. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  66646. */
  66647. MeshBuilder.CreateGround = function (name, options, scene) {
  66648. var ground = new BABYLON.GroundMesh(name, scene);
  66649. ground._setReady(false);
  66650. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  66651. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  66652. ground._width = options.width || 1;
  66653. ground._height = options.height || 1;
  66654. ground._maxX = ground._width / 2;
  66655. ground._maxZ = ground._height / 2;
  66656. ground._minX = -ground._maxX;
  66657. ground._minZ = -ground._maxZ;
  66658. var vertexData = BABYLON.VertexData.CreateGround(options);
  66659. vertexData.applyToMesh(ground, options.updatable);
  66660. ground._setReady(true);
  66661. return ground;
  66662. };
  66663. /**
  66664. * Creates a tiled ground mesh
  66665. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  66666. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  66667. * * 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
  66668. * * 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
  66669. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66670. * @param name defines the name of the mesh
  66671. * @param options defines the options used to create the mesh
  66672. * @param scene defines the hosting scene
  66673. * @returns the tiled ground mesh
  66674. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  66675. */
  66676. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  66677. var tiledGround = new BABYLON.Mesh(name, scene);
  66678. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  66679. vertexData.applyToMesh(tiledGround, options.updatable);
  66680. return tiledGround;
  66681. };
  66682. /**
  66683. * Creates a ground mesh from a height map
  66684. * * The parameter `url` sets the URL of the height map image resource.
  66685. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  66686. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  66687. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  66688. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  66689. * * 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.
  66690. * * 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).
  66691. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  66692. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66693. * @param name defines the name of the mesh
  66694. * @param url defines the url to the height map
  66695. * @param options defines the options used to create the mesh
  66696. * @param scene defines the hosting scene
  66697. * @returns the ground mesh
  66698. * @see http://doc.babylonjs.com/babylon101/height_map
  66699. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  66700. */
  66701. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  66702. var width = options.width || 10.0;
  66703. var height = options.height || 10.0;
  66704. var subdivisions = options.subdivisions || 1 | 0;
  66705. var minHeight = options.minHeight || 0.0;
  66706. var maxHeight = options.maxHeight || 1.0;
  66707. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  66708. var alphaFilter = options.alphaFilter || 0.0;
  66709. var updatable = options.updatable;
  66710. var onReady = options.onReady;
  66711. var ground = new BABYLON.GroundMesh(name, scene);
  66712. ground._subdivisionsX = subdivisions;
  66713. ground._subdivisionsY = subdivisions;
  66714. ground._width = width;
  66715. ground._height = height;
  66716. ground._maxX = ground._width / 2.0;
  66717. ground._maxZ = ground._height / 2.0;
  66718. ground._minX = -ground._maxX;
  66719. ground._minZ = -ground._maxZ;
  66720. ground._setReady(false);
  66721. var onload = function (img) {
  66722. // Getting height map data
  66723. var canvas = document.createElement("canvas");
  66724. var context = canvas.getContext("2d");
  66725. if (!context) {
  66726. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  66727. }
  66728. if (scene.isDisposed) {
  66729. return;
  66730. }
  66731. var bufferWidth = img.width;
  66732. var bufferHeight = img.height;
  66733. canvas.width = bufferWidth;
  66734. canvas.height = bufferHeight;
  66735. context.drawImage(img, 0, 0);
  66736. // Create VertexData from map data
  66737. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  66738. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  66739. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  66740. width: width, height: height,
  66741. subdivisions: subdivisions,
  66742. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  66743. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  66744. alphaFilter: alphaFilter
  66745. });
  66746. vertexData.applyToMesh(ground, updatable);
  66747. //execute ready callback, if set
  66748. if (onReady) {
  66749. onReady(ground);
  66750. }
  66751. ground._setReady(true);
  66752. };
  66753. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  66754. return ground;
  66755. };
  66756. /**
  66757. * Creates a polygon mesh
  66758. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  66759. * * 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
  66760. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66761. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66762. * * 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)
  66763. * * Remember you can only change the shape positions, not their number when updating a polygon
  66764. * @param name defines the name of the mesh
  66765. * @param options defines the options used to create the mesh
  66766. * @param scene defines the hosting scene
  66767. * @returns the polygon mesh
  66768. */
  66769. MeshBuilder.CreatePolygon = function (name, options, scene) {
  66770. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66771. var shape = options.shape;
  66772. var holes = options.holes || [];
  66773. var depth = options.depth || 0;
  66774. var contours = [];
  66775. var hole = [];
  66776. for (var i = 0; i < shape.length; i++) {
  66777. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  66778. }
  66779. var epsilon = 0.00000001;
  66780. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  66781. contours.pop();
  66782. }
  66783. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  66784. for (var hNb = 0; hNb < holes.length; hNb++) {
  66785. hole = [];
  66786. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  66787. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  66788. }
  66789. polygonTriangulation.addHole(hole);
  66790. }
  66791. var polygon = polygonTriangulation.build(options.updatable, depth);
  66792. polygon._originalBuilderSideOrientation = options.sideOrientation;
  66793. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  66794. vertexData.applyToMesh(polygon, options.updatable);
  66795. return polygon;
  66796. };
  66797. ;
  66798. /**
  66799. * Creates an extruded polygon mesh, with depth in the Y direction.
  66800. * * 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)
  66801. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  66802. * @param name defines the name of the mesh
  66803. * @param options defines the options used to create the mesh
  66804. * @param scene defines the hosting scene
  66805. * @returns the polygon mesh
  66806. */
  66807. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  66808. return MeshBuilder.CreatePolygon(name, options, scene);
  66809. };
  66810. ;
  66811. /**
  66812. * Creates a tube mesh.
  66813. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  66814. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  66815. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  66816. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  66817. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  66818. * * 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)
  66819. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  66820. * * 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
  66821. * * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  66822. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66823. * * 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
  66824. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66825. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66826. * @param name defines the name of the mesh
  66827. * @param options defines the options used to create the mesh
  66828. * @param scene defines the hosting scene
  66829. * @returns the tube mesh
  66830. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66831. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  66832. */
  66833. MeshBuilder.CreateTube = function (name, options, scene) {
  66834. var path = options.path;
  66835. var instance = options.instance;
  66836. var radius = 1.0;
  66837. if (instance) {
  66838. radius = instance.radius;
  66839. }
  66840. if (options.radius !== undefined) {
  66841. radius = options.radius;
  66842. }
  66843. ;
  66844. var tessellation = options.tessellation || 64 | 0;
  66845. var radiusFunction = options.radiusFunction || null;
  66846. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  66847. var invertUV = options.invertUV || false;
  66848. var updatable = options.updatable;
  66849. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66850. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  66851. // tube geometry
  66852. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  66853. var tangents = path3D.getTangents();
  66854. var normals = path3D.getNormals();
  66855. var distances = path3D.getDistances();
  66856. var pi2 = Math.PI * 2;
  66857. var step = pi2 / tessellation * arc;
  66858. var returnRadius = function () { return radius; };
  66859. var radiusFunctionFinal = radiusFunction || returnRadius;
  66860. var circlePath;
  66861. var rad;
  66862. var normal;
  66863. var rotated;
  66864. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  66865. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  66866. for (var i = 0; i < path.length; i++) {
  66867. rad = radiusFunctionFinal(i, distances[i]); // current radius
  66868. circlePath = Array(); // current circle array
  66869. normal = normals[i]; // current normal
  66870. for (var t = 0; t < tessellation; t++) {
  66871. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  66872. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  66873. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  66874. rotated.scaleInPlace(rad).addInPlace(path[i]);
  66875. circlePath[t] = rotated;
  66876. }
  66877. circlePaths[index] = circlePath;
  66878. index++;
  66879. }
  66880. // cap
  66881. var capPath = function (nbPoints, pathIndex) {
  66882. var pointCap = Array();
  66883. for (var i = 0; i < nbPoints; i++) {
  66884. pointCap.push(path[pathIndex]);
  66885. }
  66886. return pointCap;
  66887. };
  66888. switch (cap) {
  66889. case BABYLON.Mesh.NO_CAP:
  66890. break;
  66891. case BABYLON.Mesh.CAP_START:
  66892. circlePaths[0] = capPath(tessellation, 0);
  66893. circlePaths[1] = circlePaths[2].slice(0);
  66894. break;
  66895. case BABYLON.Mesh.CAP_END:
  66896. circlePaths[index] = circlePaths[index - 1].slice(0);
  66897. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  66898. break;
  66899. case BABYLON.Mesh.CAP_ALL:
  66900. circlePaths[0] = capPath(tessellation, 0);
  66901. circlePaths[1] = circlePaths[2].slice(0);
  66902. circlePaths[index] = circlePaths[index - 1].slice(0);
  66903. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  66904. break;
  66905. default:
  66906. break;
  66907. }
  66908. return circlePaths;
  66909. };
  66910. var path3D;
  66911. var pathArray;
  66912. if (instance) { // tube update
  66913. var arc = options.arc || instance.arc;
  66914. path3D = (instance.path3D).update(path);
  66915. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  66916. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  66917. instance.path3D = path3D;
  66918. instance.pathArray = pathArray;
  66919. instance.arc = arc;
  66920. instance.radius = radius;
  66921. return instance;
  66922. }
  66923. // tube creation
  66924. path3D = new BABYLON.Path3D(path);
  66925. var newPathArray = new Array();
  66926. cap = (cap < 0 || cap > 3) ? 0 : cap;
  66927. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  66928. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  66929. tube.pathArray = pathArray;
  66930. tube.path3D = path3D;
  66931. tube.tessellation = tessellation;
  66932. tube.cap = cap;
  66933. tube.arc = options.arc;
  66934. tube.radius = radius;
  66935. return tube;
  66936. };
  66937. /**
  66938. * Creates a polyhedron mesh
  66939. * * 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
  66940. * * The parameter `size` (positive float, default 1) sets the polygon size
  66941. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  66942. * * 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`
  66943. * * 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
  66944. * * 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)`)
  66945. * * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  66946. * * 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
  66947. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66948. * * 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
  66949. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66950. * @param name defines the name of the mesh
  66951. * @param options defines the options used to create the mesh
  66952. * @param scene defines the hosting scene
  66953. * @returns the polyhedron mesh
  66954. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  66955. */
  66956. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  66957. var polyhedron = new BABYLON.Mesh(name, scene);
  66958. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66959. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  66960. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  66961. vertexData.applyToMesh(polyhedron, options.updatable);
  66962. return polyhedron;
  66963. };
  66964. /**
  66965. * Creates a decal mesh.
  66966. * 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
  66967. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  66968. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  66969. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  66970. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  66971. * @param name defines the name of the mesh
  66972. * @param sourceMesh defines the mesh where the decal must be applied
  66973. * @param options defines the options used to create the mesh
  66974. * @param scene defines the hosting scene
  66975. * @returns the decal mesh
  66976. * @see http://doc.babylonjs.com/how_to/decals
  66977. */
  66978. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  66979. var indices = sourceMesh.getIndices();
  66980. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66981. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66982. var position = options.position || BABYLON.Vector3.Zero();
  66983. var normal = options.normal || BABYLON.Vector3.Up();
  66984. var size = options.size || BABYLON.Vector3.One();
  66985. var angle = options.angle || 0;
  66986. // Getting correct rotation
  66987. if (!normal) {
  66988. var target = new BABYLON.Vector3(0, 0, 1);
  66989. var camera = sourceMesh.getScene().activeCamera;
  66990. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  66991. normal = camera.globalPosition.subtract(cameraWorldTarget);
  66992. }
  66993. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  66994. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  66995. var pitch = Math.atan2(normal.y, len);
  66996. // Matrix
  66997. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  66998. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  66999. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  67000. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  67001. var vertexData = new BABYLON.VertexData();
  67002. vertexData.indices = [];
  67003. vertexData.positions = [];
  67004. vertexData.normals = [];
  67005. vertexData.uvs = [];
  67006. var currentVertexDataIndex = 0;
  67007. var extractDecalVector3 = function (indexId) {
  67008. var result = new BABYLON.PositionNormalVertex();
  67009. if (!indices || !positions || !normals) {
  67010. return result;
  67011. }
  67012. var vertexId = indices[indexId];
  67013. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  67014. // Send vector to decal local world
  67015. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  67016. // Get normal
  67017. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  67018. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  67019. return result;
  67020. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  67021. var clip = function (vertices, axis) {
  67022. if (vertices.length === 0) {
  67023. return vertices;
  67024. }
  67025. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  67026. var clipVertices = function (v0, v1) {
  67027. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  67028. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  67029. };
  67030. var result = new Array();
  67031. for (var index = 0; index < vertices.length; index += 3) {
  67032. var v1Out;
  67033. var v2Out;
  67034. var v3Out;
  67035. var total = 0;
  67036. var nV1 = null;
  67037. var nV2 = null;
  67038. var nV3 = null;
  67039. var nV4 = null;
  67040. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  67041. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  67042. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  67043. v1Out = d1 > 0;
  67044. v2Out = d2 > 0;
  67045. v3Out = d3 > 0;
  67046. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  67047. switch (total) {
  67048. case 0:
  67049. result.push(vertices[index]);
  67050. result.push(vertices[index + 1]);
  67051. result.push(vertices[index + 2]);
  67052. break;
  67053. case 1:
  67054. if (v1Out) {
  67055. nV1 = vertices[index + 1];
  67056. nV2 = vertices[index + 2];
  67057. nV3 = clipVertices(vertices[index], nV1);
  67058. nV4 = clipVertices(vertices[index], nV2);
  67059. }
  67060. if (v2Out) {
  67061. nV1 = vertices[index];
  67062. nV2 = vertices[index + 2];
  67063. nV3 = clipVertices(vertices[index + 1], nV1);
  67064. nV4 = clipVertices(vertices[index + 1], nV2);
  67065. result.push(nV3);
  67066. result.push(nV2.clone());
  67067. result.push(nV1.clone());
  67068. result.push(nV2.clone());
  67069. result.push(nV3.clone());
  67070. result.push(nV4);
  67071. break;
  67072. }
  67073. if (v3Out) {
  67074. nV1 = vertices[index];
  67075. nV2 = vertices[index + 1];
  67076. nV3 = clipVertices(vertices[index + 2], nV1);
  67077. nV4 = clipVertices(vertices[index + 2], nV2);
  67078. }
  67079. if (nV1 && nV2 && nV3 && nV4) {
  67080. result.push(nV1.clone());
  67081. result.push(nV2.clone());
  67082. result.push(nV3);
  67083. result.push(nV4);
  67084. result.push(nV3.clone());
  67085. result.push(nV2.clone());
  67086. }
  67087. break;
  67088. case 2:
  67089. if (!v1Out) {
  67090. nV1 = vertices[index].clone();
  67091. nV2 = clipVertices(nV1, vertices[index + 1]);
  67092. nV3 = clipVertices(nV1, vertices[index + 2]);
  67093. result.push(nV1);
  67094. result.push(nV2);
  67095. result.push(nV3);
  67096. }
  67097. if (!v2Out) {
  67098. nV1 = vertices[index + 1].clone();
  67099. nV2 = clipVertices(nV1, vertices[index + 2]);
  67100. nV3 = clipVertices(nV1, vertices[index]);
  67101. result.push(nV1);
  67102. result.push(nV2);
  67103. result.push(nV3);
  67104. }
  67105. if (!v3Out) {
  67106. nV1 = vertices[index + 2].clone();
  67107. nV2 = clipVertices(nV1, vertices[index]);
  67108. nV3 = clipVertices(nV1, vertices[index + 1]);
  67109. result.push(nV1);
  67110. result.push(nV2);
  67111. result.push(nV3);
  67112. }
  67113. break;
  67114. case 3:
  67115. break;
  67116. }
  67117. }
  67118. return result;
  67119. };
  67120. for (var index = 0; index < indices.length; index += 3) {
  67121. var faceVertices = new Array();
  67122. faceVertices.push(extractDecalVector3(index));
  67123. faceVertices.push(extractDecalVector3(index + 1));
  67124. faceVertices.push(extractDecalVector3(index + 2));
  67125. // Clip
  67126. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  67127. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  67128. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  67129. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  67130. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  67131. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  67132. if (faceVertices.length === 0) {
  67133. continue;
  67134. }
  67135. // Add UVs and get back to world
  67136. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  67137. var vertex = faceVertices[vIndex];
  67138. //TODO check for Int32Array | Uint32Array | Uint16Array
  67139. vertexData.indices.push(currentVertexDataIndex);
  67140. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  67141. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  67142. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  67143. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  67144. currentVertexDataIndex++;
  67145. }
  67146. }
  67147. // Return mesh
  67148. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  67149. vertexData.applyToMesh(decal);
  67150. decal.position = position.clone();
  67151. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  67152. return decal;
  67153. };
  67154. // Privates
  67155. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  67156. // extrusion geometry
  67157. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  67158. var tangents = path3D.getTangents();
  67159. var normals = path3D.getNormals();
  67160. var binormals = path3D.getBinormals();
  67161. var distances = path3D.getDistances();
  67162. var angle = 0;
  67163. var returnScale = function () { return scale !== null ? scale : 1; };
  67164. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  67165. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  67166. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  67167. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  67168. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  67169. for (var i = 0; i < curve.length; i++) {
  67170. var shapePath = new Array();
  67171. var angleStep = rotate(i, distances[i]);
  67172. var scaleRatio = scl(i, distances[i]);
  67173. for (var p = 0; p < shape.length; p++) {
  67174. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  67175. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  67176. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  67177. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  67178. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  67179. shapePath[p] = rotated;
  67180. }
  67181. shapePaths[index] = shapePath;
  67182. angle += angleStep;
  67183. index++;
  67184. }
  67185. // cap
  67186. var capPath = function (shapePath) {
  67187. var pointCap = Array();
  67188. var barycenter = BABYLON.Vector3.Zero();
  67189. var i;
  67190. for (i = 0; i < shapePath.length; i++) {
  67191. barycenter.addInPlace(shapePath[i]);
  67192. }
  67193. barycenter.scaleInPlace(1.0 / shapePath.length);
  67194. for (i = 0; i < shapePath.length; i++) {
  67195. pointCap.push(barycenter);
  67196. }
  67197. return pointCap;
  67198. };
  67199. switch (cap) {
  67200. case BABYLON.Mesh.NO_CAP:
  67201. break;
  67202. case BABYLON.Mesh.CAP_START:
  67203. shapePaths[0] = capPath(shapePaths[2]);
  67204. shapePaths[1] = shapePaths[2];
  67205. break;
  67206. case BABYLON.Mesh.CAP_END:
  67207. shapePaths[index] = shapePaths[index - 1];
  67208. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  67209. break;
  67210. case BABYLON.Mesh.CAP_ALL:
  67211. shapePaths[0] = capPath(shapePaths[2]);
  67212. shapePaths[1] = shapePaths[2];
  67213. shapePaths[index] = shapePaths[index - 1];
  67214. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  67215. break;
  67216. default:
  67217. break;
  67218. }
  67219. return shapePaths;
  67220. };
  67221. var path3D;
  67222. var pathArray;
  67223. if (instance) { // instance update
  67224. path3D = (instance.path3D).update(curve);
  67225. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  67226. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  67227. return instance;
  67228. }
  67229. // extruded shape creation
  67230. path3D = new BABYLON.Path3D(curve);
  67231. var newShapePaths = new Array();
  67232. cap = (cap < 0 || cap > 3) ? 0 : cap;
  67233. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  67234. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  67235. extrudedGeneric.pathArray = pathArray;
  67236. extrudedGeneric.path3D = path3D;
  67237. extrudedGeneric.cap = cap;
  67238. return extrudedGeneric;
  67239. };
  67240. return MeshBuilder;
  67241. }());
  67242. BABYLON.MeshBuilder = MeshBuilder;
  67243. })(BABYLON || (BABYLON = {}));
  67244. //# sourceMappingURL=babylon.meshBuilder.js.map
  67245. var BABYLON;
  67246. (function (BABYLON) {
  67247. /**
  67248. * Draco compression (https://google.github.io/draco/)
  67249. *
  67250. * This class wraps the Draco module.
  67251. *
  67252. * **Encoder**
  67253. *
  67254. * The encoder is not currently implemented.
  67255. *
  67256. * **Decoder**
  67257. *
  67258. * 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.
  67259. *
  67260. * To update the configuration, use the following code:
  67261. * ```javascript
  67262. * BABYLON.DracoCompression.Configuration = {
  67263. * decoder: {
  67264. * wasmUrl: "<url to the WebAssembly library>",
  67265. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  67266. * fallbackUrl: "<url to the fallback JavaScript library>",
  67267. * }
  67268. * };
  67269. * ```
  67270. *
  67271. * 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.
  67272. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  67273. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  67274. *
  67275. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  67276. * ```javascript
  67277. * var dracoCompression = new BABYLON.DracoCompression();
  67278. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  67279. * [BABYLON.VertexBuffer.PositionKind]: 0
  67280. * });
  67281. * ```
  67282. *
  67283. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  67284. */
  67285. var DracoCompression = /** @class */ (function () {
  67286. /**
  67287. * Constructor
  67288. */
  67289. function DracoCompression() {
  67290. }
  67291. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  67292. /**
  67293. * Returns true if the decoder is available.
  67294. */
  67295. get: function () {
  67296. if (typeof DracoDecoderModule !== "undefined") {
  67297. return true;
  67298. }
  67299. var decoder = DracoCompression.Configuration.decoder;
  67300. if (decoder) {
  67301. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  67302. return true;
  67303. }
  67304. if (decoder.fallbackUrl) {
  67305. return true;
  67306. }
  67307. }
  67308. return false;
  67309. },
  67310. enumerable: true,
  67311. configurable: true
  67312. });
  67313. /**
  67314. * Stop all async operations and release resources.
  67315. */
  67316. DracoCompression.prototype.dispose = function () {
  67317. };
  67318. /**
  67319. * Decode Draco compressed mesh data to vertex data.
  67320. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  67321. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  67322. * @returns A promise that resolves with the decoded vertex data
  67323. */
  67324. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  67325. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  67326. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  67327. var module = wrappedModule.module;
  67328. var vertexData = new BABYLON.VertexData();
  67329. var buffer = new module.DecoderBuffer();
  67330. buffer.Init(dataView, dataView.byteLength);
  67331. var decoder = new module.Decoder();
  67332. var geometry;
  67333. var status;
  67334. try {
  67335. var type = decoder.GetEncodedGeometryType(buffer);
  67336. switch (type) {
  67337. case module.TRIANGULAR_MESH:
  67338. geometry = new module.Mesh();
  67339. status = decoder.DecodeBufferToMesh(buffer, geometry);
  67340. break;
  67341. case module.POINT_CLOUD:
  67342. geometry = new module.PointCloud();
  67343. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  67344. break;
  67345. default:
  67346. throw new Error("Invalid geometry type " + type);
  67347. }
  67348. if (!status.ok() || !geometry.ptr) {
  67349. throw new Error(status.error_msg());
  67350. }
  67351. var numPoints = geometry.num_points();
  67352. if (type === module.TRIANGULAR_MESH) {
  67353. var numFaces = geometry.num_faces();
  67354. var faceIndices = new module.DracoInt32Array();
  67355. try {
  67356. var indices = new Uint32Array(numFaces * 3);
  67357. for (var i = 0; i < numFaces; i++) {
  67358. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  67359. var offset = i * 3;
  67360. indices[offset + 0] = faceIndices.GetValue(0);
  67361. indices[offset + 1] = faceIndices.GetValue(1);
  67362. indices[offset + 2] = faceIndices.GetValue(2);
  67363. }
  67364. vertexData.indices = indices;
  67365. }
  67366. finally {
  67367. module.destroy(faceIndices);
  67368. }
  67369. }
  67370. for (var kind in attributes) {
  67371. var uniqueId = attributes[kind];
  67372. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  67373. var dracoData = new module.DracoFloat32Array();
  67374. try {
  67375. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  67376. var babylonData = new Float32Array(numPoints * attribute.num_components());
  67377. for (var i = 0; i < babylonData.length; i++) {
  67378. babylonData[i] = dracoData.GetValue(i);
  67379. }
  67380. vertexData.set(babylonData, kind);
  67381. }
  67382. finally {
  67383. module.destroy(dracoData);
  67384. }
  67385. }
  67386. }
  67387. finally {
  67388. if (geometry) {
  67389. module.destroy(geometry);
  67390. }
  67391. module.destroy(decoder);
  67392. module.destroy(buffer);
  67393. }
  67394. return vertexData;
  67395. });
  67396. };
  67397. DracoCompression._GetDecoderModule = function () {
  67398. if (!DracoCompression._DecoderModulePromise) {
  67399. var promise = null;
  67400. var config_1 = {};
  67401. if (typeof DracoDecoderModule !== "undefined") {
  67402. promise = Promise.resolve();
  67403. }
  67404. else {
  67405. var decoder = DracoCompression.Configuration.decoder;
  67406. if (decoder) {
  67407. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  67408. promise = Promise.all([
  67409. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  67410. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  67411. config_1.wasmBinary = data;
  67412. })
  67413. ]);
  67414. }
  67415. else if (decoder.fallbackUrl) {
  67416. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  67417. }
  67418. }
  67419. }
  67420. if (!promise) {
  67421. throw new Error("Draco decoder module is not available");
  67422. }
  67423. DracoCompression._DecoderModulePromise = promise.then(function () {
  67424. return new Promise(function (resolve) {
  67425. config_1.onModuleLoaded = function (decoderModule) {
  67426. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  67427. resolve({ module: decoderModule });
  67428. };
  67429. DracoDecoderModule(config_1);
  67430. });
  67431. });
  67432. }
  67433. return DracoCompression._DecoderModulePromise;
  67434. };
  67435. DracoCompression._LoadScriptAsync = function (url) {
  67436. return new Promise(function (resolve, reject) {
  67437. BABYLON.Tools.LoadScript(url, function () {
  67438. resolve();
  67439. }, function (message) {
  67440. reject(new Error(message));
  67441. });
  67442. });
  67443. };
  67444. DracoCompression._LoadFileAsync = function (url) {
  67445. return new Promise(function (resolve, reject) {
  67446. BABYLON.Tools.LoadFile(url, function (data) {
  67447. resolve(data);
  67448. }, undefined, undefined, true, function (request, exception) {
  67449. reject(exception);
  67450. });
  67451. });
  67452. };
  67453. /**
  67454. * The configuration. Defaults to the following urls:
  67455. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  67456. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  67457. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  67458. */
  67459. DracoCompression.Configuration = {
  67460. decoder: {
  67461. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  67462. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  67463. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  67464. }
  67465. };
  67466. return DracoCompression;
  67467. }());
  67468. BABYLON.DracoCompression = DracoCompression;
  67469. })(BABYLON || (BABYLON = {}));
  67470. //# sourceMappingURL=babylon.dracoCompression.js.map
  67471. var BABYLON;
  67472. (function (BABYLON) {
  67473. // Sets the default audio engine to Babylon JS.
  67474. BABYLON.Engine.AudioEngineFactory = function (engine) { return new AudioEngine(engine); };
  67475. /**
  67476. * This represents the default audio engine used in babylon.
  67477. * It is responsible to play, synchronize and analyse sounds throughout the application.
  67478. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  67479. */
  67480. var AudioEngine = /** @class */ (function () {
  67481. /**
  67482. * Instantiates a new audio engine.
  67483. *
  67484. * There should be only one per page as some browsers restrict the number
  67485. * of audio contexts you can create.
  67486. * @param engine defines the hosting engine
  67487. */
  67488. function AudioEngine(engine) {
  67489. if (engine === void 0) { engine = BABYLON.Engine.LastCreatedEngine; }
  67490. var _this = this;
  67491. this._audioContext = null;
  67492. this._audioContextInitialized = false;
  67493. this._muteButton = null;
  67494. /**
  67495. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  67496. */
  67497. this.canUseWebAudio = false;
  67498. /**
  67499. * Defines if Babylon should emit a warning if WebAudio is not supported.
  67500. * @ignoreNaming
  67501. */
  67502. this.WarnedWebAudioUnsupported = false;
  67503. /**
  67504. * Gets whether or not mp3 are supported by your browser.
  67505. */
  67506. this.isMP3supported = false;
  67507. /**
  67508. * Gets whether or not ogg are supported by your browser.
  67509. */
  67510. this.isOGGsupported = false;
  67511. /**
  67512. * Gets whether audio has been unlocked on the device.
  67513. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  67514. * a user interaction has happened.
  67515. */
  67516. this.unlocked = true;
  67517. /**
  67518. * Defines if the audio engine relies on a custom unlocked button.
  67519. * In this case, the embedded button will not be displayed.
  67520. */
  67521. this.useCustomUnlockedButton = false;
  67522. /**
  67523. * Event raised when audio has been unlocked on the browser.
  67524. */
  67525. this.onAudioUnlockedObservable = new BABYLON.Observable();
  67526. /**
  67527. * Event raised when audio has been locked on the browser.
  67528. */
  67529. this.onAudioLockedObservable = new BABYLON.Observable();
  67530. this._tryToRun = false;
  67531. this._onResize = function () {
  67532. _this._moveButtonToTopLeft();
  67533. };
  67534. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  67535. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  67536. this.canUseWebAudio = true;
  67537. }
  67538. var audioElem = document.createElement('audio');
  67539. this._engine = engine;
  67540. try {
  67541. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  67542. this.isMP3supported = true;
  67543. }
  67544. }
  67545. catch (e) {
  67546. // protect error during capability check.
  67547. }
  67548. try {
  67549. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  67550. this.isOGGsupported = true;
  67551. }
  67552. }
  67553. catch (e) {
  67554. // protect error during capability check.
  67555. }
  67556. }
  67557. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  67558. /**
  67559. * Gets the current AudioContext if available.
  67560. */
  67561. get: function () {
  67562. if (!this._audioContextInitialized) {
  67563. this._initializeAudioContext();
  67564. }
  67565. else {
  67566. if (!this.unlocked && !this._muteButton) {
  67567. this._displayMuteButton();
  67568. }
  67569. }
  67570. return this._audioContext;
  67571. },
  67572. enumerable: true,
  67573. configurable: true
  67574. });
  67575. /**
  67576. * Flags the audio engine in Locked state.
  67577. * This happens due to new browser policies preventing audio to autoplay.
  67578. */
  67579. AudioEngine.prototype.lock = function () {
  67580. this._triggerSuspendedState();
  67581. };
  67582. /**
  67583. * Unlocks the audio engine once a user action has been done on the dom.
  67584. * This is helpful to resume play once browser policies have been satisfied.
  67585. */
  67586. AudioEngine.prototype.unlock = function () {
  67587. this._triggerRunningState();
  67588. };
  67589. AudioEngine.prototype._resumeAudioContext = function () {
  67590. var result;
  67591. if (this._audioContext.resume) {
  67592. result = this._audioContext.resume();
  67593. }
  67594. return result || Promise.resolve();
  67595. };
  67596. AudioEngine.prototype._initializeAudioContext = function () {
  67597. var _this = this;
  67598. try {
  67599. if (this.canUseWebAudio) {
  67600. this._audioContext = new AudioContext();
  67601. // create a global volume gain node
  67602. this.masterGain = this._audioContext.createGain();
  67603. this.masterGain.gain.value = 1;
  67604. this.masterGain.connect(this._audioContext.destination);
  67605. this._audioContextInitialized = true;
  67606. if (this._audioContext.state === "running") {
  67607. // Do not wait for the promise to unlock.
  67608. this._triggerRunningState();
  67609. }
  67610. else {
  67611. if (this._audioContext && this._audioContext.resume) {
  67612. this._resumeAudioContext().then(function () {
  67613. _this._triggerRunningState();
  67614. }).catch(function () {
  67615. // Can not resume automatically
  67616. // Needs user action
  67617. _this.lock();
  67618. });
  67619. }
  67620. }
  67621. }
  67622. }
  67623. catch (e) {
  67624. this.canUseWebAudio = false;
  67625. BABYLON.Tools.Error("Web Audio: " + e.message);
  67626. }
  67627. };
  67628. AudioEngine.prototype._triggerRunningState = function () {
  67629. var _this = this;
  67630. if (this._tryToRun) {
  67631. return;
  67632. }
  67633. this._tryToRun = true;
  67634. this._resumeAudioContext()
  67635. .then(function () {
  67636. _this._tryToRun = false;
  67637. _this.unlocked = true;
  67638. if (_this._muteButton) {
  67639. _this._hideMuteButton();
  67640. }
  67641. // Notify users that the audio stack is unlocked/unmuted
  67642. _this.onAudioUnlockedObservable.notifyObservers(_this);
  67643. }).catch(function () {
  67644. _this._tryToRun = false;
  67645. _this.unlocked = false;
  67646. });
  67647. };
  67648. AudioEngine.prototype._triggerSuspendedState = function () {
  67649. this.unlocked = false;
  67650. this.onAudioLockedObservable.notifyObservers(this);
  67651. this._displayMuteButton();
  67652. };
  67653. AudioEngine.prototype._displayMuteButton = function () {
  67654. var _this = this;
  67655. if (this.useCustomUnlockedButton) {
  67656. return;
  67657. }
  67658. this._canvas = this._engine.getRenderingCanvas();
  67659. this._muteButton = document.createElement("BUTTON");
  67660. this._muteButton.className = "babylonUnmuteIcon";
  67661. this._muteButton.id = "babylonUnmuteIconBtn";
  67662. this._muteButton.title = "Unmute";
  67663. 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) }";
  67664. var style = document.createElement('style');
  67665. style.appendChild(document.createTextNode(css));
  67666. document.getElementsByTagName('head')[0].appendChild(style);
  67667. document.body.appendChild(this._muteButton);
  67668. this._moveButtonToTopLeft();
  67669. this._muteButton.addEventListener('mousedown', function () {
  67670. _this._triggerRunningState();
  67671. }, true);
  67672. this._muteButton.addEventListener('touchend', function () {
  67673. _this._triggerRunningState();
  67674. }, true);
  67675. this._muteButton.addEventListener('click', function () {
  67676. _this._triggerRunningState();
  67677. }, true);
  67678. window.addEventListener("resize", this._onResize);
  67679. };
  67680. AudioEngine.prototype._moveButtonToTopLeft = function () {
  67681. if (this._canvas && this._muteButton) {
  67682. this._muteButton.style.top = this._canvas.offsetTop + 20 + "px";
  67683. this._muteButton.style.left = this._canvas.offsetLeft + 20 + "px";
  67684. }
  67685. };
  67686. AudioEngine.prototype._hideMuteButton = function () {
  67687. if (this._muteButton) {
  67688. document.body.removeChild(this._muteButton);
  67689. this._muteButton = null;
  67690. }
  67691. };
  67692. /**
  67693. * Destroy and release the resources associated with the audio ccontext.
  67694. */
  67695. AudioEngine.prototype.dispose = function () {
  67696. if (this.canUseWebAudio && this._audioContextInitialized) {
  67697. if (this._connectedAnalyser && this._audioContext) {
  67698. this._connectedAnalyser.stopDebugCanvas();
  67699. this._connectedAnalyser.dispose();
  67700. this.masterGain.disconnect();
  67701. this.masterGain.connect(this._audioContext.destination);
  67702. this._connectedAnalyser = null;
  67703. }
  67704. this.masterGain.gain.value = 1;
  67705. }
  67706. this.WarnedWebAudioUnsupported = false;
  67707. this._hideMuteButton();
  67708. window.removeEventListener("resize", this._onResize);
  67709. this.onAudioUnlockedObservable.clear();
  67710. this.onAudioLockedObservable.clear();
  67711. };
  67712. /**
  67713. * Gets the global volume sets on the master gain.
  67714. * @returns the global volume if set or -1 otherwise
  67715. */
  67716. AudioEngine.prototype.getGlobalVolume = function () {
  67717. if (this.canUseWebAudio && this._audioContextInitialized) {
  67718. return this.masterGain.gain.value;
  67719. }
  67720. else {
  67721. return -1;
  67722. }
  67723. };
  67724. /**
  67725. * Sets the global volume of your experience (sets on the master gain).
  67726. * @param newVolume Defines the new global volume of the application
  67727. */
  67728. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  67729. if (this.canUseWebAudio && this._audioContextInitialized) {
  67730. this.masterGain.gain.value = newVolume;
  67731. }
  67732. };
  67733. /**
  67734. * Connect the audio engine to an audio analyser allowing some amazing
  67735. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  67736. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  67737. * @param analyser The analyser to connect to the engine
  67738. */
  67739. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  67740. if (this._connectedAnalyser) {
  67741. this._connectedAnalyser.stopDebugCanvas();
  67742. }
  67743. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  67744. this._connectedAnalyser = analyser;
  67745. this.masterGain.disconnect();
  67746. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  67747. }
  67748. };
  67749. return AudioEngine;
  67750. }());
  67751. BABYLON.AudioEngine = AudioEngine;
  67752. })(BABYLON || (BABYLON = {}));
  67753. //# sourceMappingURL=babylon.audioEngine.js.map
  67754. var BABYLON;
  67755. (function (BABYLON) {
  67756. /**
  67757. * Defines a sound that can be played in the application.
  67758. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  67759. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  67760. */
  67761. var Sound = /** @class */ (function () {
  67762. /**
  67763. * Create a sound and attach it to a scene
  67764. * @param name Name of your sound
  67765. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  67766. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  67767. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  67768. */
  67769. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  67770. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  67771. var _this = this;
  67772. /**
  67773. * Does the sound autoplay once loaded.
  67774. */
  67775. this.autoplay = false;
  67776. /**
  67777. * Does the sound loop after it finishes playing once.
  67778. */
  67779. this.loop = false;
  67780. /**
  67781. * Does the sound use a custom attenuation curve to simulate the falloff
  67782. * happening when the source gets further away from the camera.
  67783. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  67784. */
  67785. this.useCustomAttenuation = false;
  67786. /**
  67787. * Is this sound currently played.
  67788. */
  67789. this.isPlaying = false;
  67790. /**
  67791. * Is this sound currently paused.
  67792. */
  67793. this.isPaused = false;
  67794. /**
  67795. * Does this sound enables spatial sound.
  67796. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67797. */
  67798. this.spatialSound = false;
  67799. /**
  67800. * Define the reference distance the sound should be heard perfectly.
  67801. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67802. */
  67803. this.refDistance = 1;
  67804. /**
  67805. * Define the roll off factor of spatial sounds.
  67806. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67807. */
  67808. this.rolloffFactor = 1;
  67809. /**
  67810. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  67811. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67812. */
  67813. this.maxDistance = 100;
  67814. /**
  67815. * Define the distance attenuation model the sound will follow.
  67816. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67817. */
  67818. this.distanceModel = "linear";
  67819. /**
  67820. * Observable event when the current playing sound finishes.
  67821. */
  67822. this.onEndedObservable = new BABYLON.Observable();
  67823. this._panningModel = "equalpower";
  67824. this._playbackRate = 1;
  67825. this._streaming = false;
  67826. this._startTime = 0;
  67827. this._startOffset = 0;
  67828. this._position = BABYLON.Vector3.Zero();
  67829. /** @hidden */
  67830. this._positionInEmitterSpace = false;
  67831. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  67832. this._volume = 1;
  67833. this._isReadyToPlay = false;
  67834. this._isDirectional = false;
  67835. // Used if you'd like to create a directional sound.
  67836. // If not set, the sound will be omnidirectional
  67837. this._coneInnerAngle = 360;
  67838. this._coneOuterAngle = 360;
  67839. this._coneOuterGain = 0;
  67840. this._isOutputConnected = false;
  67841. this._urlType = "Unknown";
  67842. this.name = name;
  67843. this._scene = scene;
  67844. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  67845. if (!compo) {
  67846. compo = new BABYLON.AudioSceneComponent(scene);
  67847. scene._addComponent(compo);
  67848. }
  67849. this._readyToPlayCallback = readyToPlayCallback;
  67850. // Default custom attenuation function is a linear attenuation
  67851. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  67852. if (currentDistance < maxDistance) {
  67853. return currentVolume * (1 - currentDistance / maxDistance);
  67854. }
  67855. else {
  67856. return 0;
  67857. }
  67858. };
  67859. if (options) {
  67860. this.autoplay = options.autoplay || false;
  67861. this.loop = options.loop || false;
  67862. // if volume === 0, we need another way to check this option
  67863. if (options.volume !== undefined) {
  67864. this._volume = options.volume;
  67865. }
  67866. this.spatialSound = options.spatialSound || false;
  67867. this.maxDistance = options.maxDistance || 100;
  67868. this.useCustomAttenuation = options.useCustomAttenuation || false;
  67869. this.rolloffFactor = options.rolloffFactor || 1;
  67870. this.refDistance = options.refDistance || 1;
  67871. this.distanceModel = options.distanceModel || "linear";
  67872. this._playbackRate = options.playbackRate || 1;
  67873. this._streaming = options.streaming || false;
  67874. }
  67875. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  67876. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  67877. this._soundGain.gain.value = this._volume;
  67878. this._inputAudioNode = this._soundGain;
  67879. this._outputAudioNode = this._soundGain;
  67880. if (this.spatialSound) {
  67881. this._createSpatialParameters();
  67882. }
  67883. this._scene.mainSoundTrack.AddSound(this);
  67884. var validParameter = true;
  67885. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  67886. if (urlOrArrayBuffer) {
  67887. try {
  67888. if (typeof (urlOrArrayBuffer) === "string") {
  67889. this._urlType = "String";
  67890. }
  67891. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  67892. this._urlType = "ArrayBuffer";
  67893. }
  67894. else if (urlOrArrayBuffer instanceof MediaStream) {
  67895. this._urlType = "MediaStream";
  67896. }
  67897. else if (Array.isArray(urlOrArrayBuffer)) {
  67898. this._urlType = "Array";
  67899. }
  67900. var urls = [];
  67901. var codecSupportedFound = false;
  67902. switch (this._urlType) {
  67903. case "MediaStream":
  67904. this._streaming = true;
  67905. this._isReadyToPlay = true;
  67906. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  67907. if (this.autoplay) {
  67908. this.play();
  67909. }
  67910. if (this._readyToPlayCallback) {
  67911. this._readyToPlayCallback();
  67912. }
  67913. break;
  67914. case "ArrayBuffer":
  67915. if (urlOrArrayBuffer.byteLength > 0) {
  67916. codecSupportedFound = true;
  67917. this._soundLoaded(urlOrArrayBuffer);
  67918. }
  67919. break;
  67920. case "String":
  67921. urls.push(urlOrArrayBuffer);
  67922. case "Array":
  67923. if (urls.length === 0)
  67924. urls = urlOrArrayBuffer;
  67925. // If we found a supported format, we load it immediately and stop the loop
  67926. for (var i = 0; i < urls.length; i++) {
  67927. var url = urls[i];
  67928. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  67929. codecSupportedFound = true;
  67930. }
  67931. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  67932. codecSupportedFound = true;
  67933. }
  67934. if (url.indexOf(".wav", url.length - 4) !== -1) {
  67935. codecSupportedFound = true;
  67936. }
  67937. if (url.indexOf("blob:") !== -1) {
  67938. codecSupportedFound = true;
  67939. }
  67940. if (codecSupportedFound) {
  67941. // Loading sound using XHR2
  67942. if (!this._streaming) {
  67943. this._scene._loadFile(url, function (data) {
  67944. _this._soundLoaded(data);
  67945. }, undefined, true, true, function (exception) {
  67946. if (exception) {
  67947. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  67948. }
  67949. BABYLON.Tools.Error("Sound creation aborted.");
  67950. _this._scene.mainSoundTrack.RemoveSound(_this);
  67951. });
  67952. }
  67953. // Streaming sound using HTML5 Audio tag
  67954. else {
  67955. this._htmlAudioElement = new Audio(url);
  67956. this._htmlAudioElement.controls = false;
  67957. this._htmlAudioElement.loop = this.loop;
  67958. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  67959. this._htmlAudioElement.preload = "auto";
  67960. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  67961. _this._isReadyToPlay = true;
  67962. if (_this.autoplay) {
  67963. _this.play();
  67964. }
  67965. if (_this._readyToPlayCallback) {
  67966. _this._readyToPlayCallback();
  67967. }
  67968. });
  67969. document.body.appendChild(this._htmlAudioElement);
  67970. this._htmlAudioElement.load();
  67971. }
  67972. break;
  67973. }
  67974. }
  67975. break;
  67976. default:
  67977. validParameter = false;
  67978. break;
  67979. }
  67980. if (!validParameter) {
  67981. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  67982. }
  67983. else {
  67984. if (!codecSupportedFound) {
  67985. this._isReadyToPlay = true;
  67986. // Simulating a ready to play event to avoid breaking code path
  67987. if (this._readyToPlayCallback) {
  67988. window.setTimeout(function () {
  67989. if (_this._readyToPlayCallback) {
  67990. _this._readyToPlayCallback();
  67991. }
  67992. }, 1000);
  67993. }
  67994. }
  67995. }
  67996. }
  67997. catch (ex) {
  67998. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  67999. this._scene.mainSoundTrack.RemoveSound(this);
  68000. }
  68001. }
  68002. }
  68003. else {
  68004. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  68005. this._scene.mainSoundTrack.AddSound(this);
  68006. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  68007. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  68008. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  68009. }
  68010. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  68011. if (this._readyToPlayCallback) {
  68012. window.setTimeout(function () {
  68013. if (_this._readyToPlayCallback) {
  68014. _this._readyToPlayCallback();
  68015. }
  68016. }, 1000);
  68017. }
  68018. }
  68019. }
  68020. /**
  68021. * Release the sound and its associated resources
  68022. */
  68023. Sound.prototype.dispose = function () {
  68024. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68025. if (this.isPlaying) {
  68026. this.stop();
  68027. }
  68028. this._isReadyToPlay = false;
  68029. if (this.soundTrackId === -1) {
  68030. this._scene.mainSoundTrack.RemoveSound(this);
  68031. }
  68032. else if (this._scene.soundTracks) {
  68033. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  68034. }
  68035. if (this._soundGain) {
  68036. this._soundGain.disconnect();
  68037. this._soundGain = null;
  68038. }
  68039. if (this._soundPanner) {
  68040. this._soundPanner.disconnect();
  68041. this._soundPanner = null;
  68042. }
  68043. if (this._soundSource) {
  68044. this._soundSource.disconnect();
  68045. this._soundSource = null;
  68046. }
  68047. this._audioBuffer = null;
  68048. if (this._htmlAudioElement) {
  68049. this._htmlAudioElement.pause();
  68050. this._htmlAudioElement.src = "";
  68051. document.body.removeChild(this._htmlAudioElement);
  68052. }
  68053. if (this._streamingSource) {
  68054. this._streamingSource.disconnect();
  68055. }
  68056. if (this._connectedMesh && this._registerFunc) {
  68057. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  68058. this._connectedMesh = null;
  68059. }
  68060. }
  68061. };
  68062. /**
  68063. * Gets if the sounds is ready to be played or not.
  68064. * @returns true if ready, otherwise false
  68065. */
  68066. Sound.prototype.isReady = function () {
  68067. return this._isReadyToPlay;
  68068. };
  68069. Sound.prototype._soundLoaded = function (audioData) {
  68070. var _this = this;
  68071. if (!BABYLON.Engine.audioEngine.audioContext) {
  68072. return;
  68073. }
  68074. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  68075. _this._audioBuffer = buffer;
  68076. _this._isReadyToPlay = true;
  68077. if (_this.autoplay) {
  68078. _this.play();
  68079. }
  68080. if (_this._readyToPlayCallback) {
  68081. _this._readyToPlayCallback();
  68082. }
  68083. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  68084. };
  68085. /**
  68086. * Sets the data of the sound from an audiobuffer
  68087. * @param audioBuffer The audioBuffer containing the data
  68088. */
  68089. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  68090. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68091. this._audioBuffer = audioBuffer;
  68092. this._isReadyToPlay = true;
  68093. }
  68094. };
  68095. /**
  68096. * Updates the current sounds options such as maxdistance, loop...
  68097. * @param options A JSON object containing values named as the object properties
  68098. */
  68099. Sound.prototype.updateOptions = function (options) {
  68100. if (options) {
  68101. this.loop = options.loop || this.loop;
  68102. this.maxDistance = options.maxDistance || this.maxDistance;
  68103. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  68104. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  68105. this.refDistance = options.refDistance || this.refDistance;
  68106. this.distanceModel = options.distanceModel || this.distanceModel;
  68107. this._playbackRate = options.playbackRate || this._playbackRate;
  68108. this._updateSpatialParameters();
  68109. if (this.isPlaying) {
  68110. if (this._streaming && this._htmlAudioElement) {
  68111. this._htmlAudioElement.playbackRate = this._playbackRate;
  68112. }
  68113. else {
  68114. if (this._soundSource) {
  68115. this._soundSource.playbackRate.value = this._playbackRate;
  68116. }
  68117. }
  68118. }
  68119. }
  68120. };
  68121. Sound.prototype._createSpatialParameters = function () {
  68122. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  68123. if (this._scene.headphone) {
  68124. this._panningModel = "HRTF";
  68125. }
  68126. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  68127. this._updateSpatialParameters();
  68128. this._soundPanner.connect(this._outputAudioNode);
  68129. this._inputAudioNode = this._soundPanner;
  68130. }
  68131. };
  68132. Sound.prototype._updateSpatialParameters = function () {
  68133. if (this.spatialSound && this._soundPanner) {
  68134. if (this.useCustomAttenuation) {
  68135. // Tricks to disable in a way embedded Web Audio attenuation
  68136. this._soundPanner.distanceModel = "linear";
  68137. this._soundPanner.maxDistance = Number.MAX_VALUE;
  68138. this._soundPanner.refDistance = 1;
  68139. this._soundPanner.rolloffFactor = 1;
  68140. this._soundPanner.panningModel = this._panningModel;
  68141. }
  68142. else {
  68143. this._soundPanner.distanceModel = this.distanceModel;
  68144. this._soundPanner.maxDistance = this.maxDistance;
  68145. this._soundPanner.refDistance = this.refDistance;
  68146. this._soundPanner.rolloffFactor = this.rolloffFactor;
  68147. this._soundPanner.panningModel = this._panningModel;
  68148. }
  68149. }
  68150. };
  68151. /**
  68152. * Switch the panning model to HRTF:
  68153. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  68154. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68155. */
  68156. Sound.prototype.switchPanningModelToHRTF = function () {
  68157. this._panningModel = "HRTF";
  68158. this._switchPanningModel();
  68159. };
  68160. /**
  68161. * Switch the panning model to Equal Power:
  68162. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  68163. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68164. */
  68165. Sound.prototype.switchPanningModelToEqualPower = function () {
  68166. this._panningModel = "equalpower";
  68167. this._switchPanningModel();
  68168. };
  68169. Sound.prototype._switchPanningModel = function () {
  68170. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  68171. this._soundPanner.panningModel = this._panningModel;
  68172. }
  68173. };
  68174. /**
  68175. * Connect this sound to a sound track audio node like gain...
  68176. * @param soundTrackAudioNode the sound track audio node to connect to
  68177. */
  68178. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  68179. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68180. if (this._isOutputConnected) {
  68181. this._outputAudioNode.disconnect();
  68182. }
  68183. this._outputAudioNode.connect(soundTrackAudioNode);
  68184. this._isOutputConnected = true;
  68185. }
  68186. };
  68187. /**
  68188. * Transform this sound into a directional source
  68189. * @param coneInnerAngle Size of the inner cone in degree
  68190. * @param coneOuterAngle Size of the outer cone in degree
  68191. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  68192. */
  68193. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  68194. if (coneOuterAngle < coneInnerAngle) {
  68195. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  68196. return;
  68197. }
  68198. this._coneInnerAngle = coneInnerAngle;
  68199. this._coneOuterAngle = coneOuterAngle;
  68200. this._coneOuterGain = coneOuterGain;
  68201. this._isDirectional = true;
  68202. if (this.isPlaying && this.loop) {
  68203. this.stop();
  68204. this.play();
  68205. }
  68206. };
  68207. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  68208. /**
  68209. * Gets or sets the inner angle for the directional cone.
  68210. */
  68211. get: function () {
  68212. return this._coneInnerAngle;
  68213. },
  68214. /**
  68215. * Gets or sets the inner angle for the directional cone.
  68216. */
  68217. set: function (value) {
  68218. if (value != this._coneInnerAngle) {
  68219. if (this._coneOuterAngle < value) {
  68220. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68221. return;
  68222. }
  68223. this._coneInnerAngle = value;
  68224. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  68225. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  68226. }
  68227. }
  68228. },
  68229. enumerable: true,
  68230. configurable: true
  68231. });
  68232. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  68233. /**
  68234. * Gets or sets the outer angle for the directional cone.
  68235. */
  68236. get: function () {
  68237. return this._coneOuterAngle;
  68238. },
  68239. /**
  68240. * Gets or sets the outer angle for the directional cone.
  68241. */
  68242. set: function (value) {
  68243. if (value != this._coneOuterAngle) {
  68244. if (value < this._coneInnerAngle) {
  68245. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68246. return;
  68247. }
  68248. this._coneOuterAngle = value;
  68249. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  68250. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  68251. }
  68252. }
  68253. },
  68254. enumerable: true,
  68255. configurable: true
  68256. });
  68257. /**
  68258. * Sets the position of the emitter if spatial sound is enabled
  68259. * @param newPosition Defines the new posisiton
  68260. */
  68261. Sound.prototype.setPosition = function (newPosition) {
  68262. this._position = newPosition;
  68263. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  68264. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  68265. }
  68266. };
  68267. /**
  68268. * Sets the local direction of the emitter if spatial sound is enabled
  68269. * @param newLocalDirection Defines the new local direction
  68270. */
  68271. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  68272. this._localDirection = newLocalDirection;
  68273. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  68274. this._updateDirection();
  68275. }
  68276. };
  68277. Sound.prototype._updateDirection = function () {
  68278. if (!this._connectedMesh || !this._soundPanner) {
  68279. return;
  68280. }
  68281. var mat = this._connectedMesh.getWorldMatrix();
  68282. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  68283. direction.normalize();
  68284. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  68285. };
  68286. /** @hidden */
  68287. Sound.prototype.updateDistanceFromListener = function () {
  68288. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  68289. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  68290. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  68291. }
  68292. };
  68293. /**
  68294. * Sets a new custom attenuation function for the sound.
  68295. * @param callback Defines the function used for the attenuation
  68296. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  68297. */
  68298. Sound.prototype.setAttenuationFunction = function (callback) {
  68299. this._customAttenuationFunction = callback;
  68300. };
  68301. /**
  68302. * Play the sound
  68303. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  68304. * @param offset (optional) Start the sound setting it at a specific time
  68305. */
  68306. Sound.prototype.play = function (time, offset) {
  68307. var _this = this;
  68308. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  68309. try {
  68310. if (this._startOffset < 0) {
  68311. time = -this._startOffset;
  68312. this._startOffset = 0;
  68313. }
  68314. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  68315. if (!this._soundSource || !this._streamingSource) {
  68316. if (this.spatialSound && this._soundPanner) {
  68317. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  68318. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  68319. }
  68320. if (this._isDirectional) {
  68321. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  68322. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  68323. this._soundPanner.coneOuterGain = this._coneOuterGain;
  68324. if (this._connectedMesh) {
  68325. this._updateDirection();
  68326. }
  68327. else {
  68328. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  68329. }
  68330. }
  68331. }
  68332. }
  68333. if (this._streaming) {
  68334. if (!this._streamingSource) {
  68335. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  68336. this._htmlAudioElement.onended = function () { _this._onended(); };
  68337. this._htmlAudioElement.playbackRate = this._playbackRate;
  68338. }
  68339. this._streamingSource.disconnect();
  68340. this._streamingSource.connect(this._inputAudioNode);
  68341. if (this._htmlAudioElement) {
  68342. // required to manage properly the new suspended default state of Chrome
  68343. // When the option 'streaming: true' is used, we need first to wait for
  68344. // the audio engine to be unlocked by a user gesture before trying to play
  68345. // an HTML Audio elememt
  68346. var tryToPlay = function () {
  68347. if (BABYLON.Engine.audioEngine.unlocked) {
  68348. var playPromise = _this._htmlAudioElement.play();
  68349. // In browsers that don’t yet support this functionality,
  68350. // playPromise won’t be defined.
  68351. if (playPromise !== undefined) {
  68352. playPromise.catch(function (error) {
  68353. // Automatic playback failed.
  68354. // Waiting for the audio engine to be unlocked by user click on unmute
  68355. BABYLON.Engine.audioEngine.lock();
  68356. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  68357. });
  68358. }
  68359. }
  68360. else {
  68361. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  68362. }
  68363. };
  68364. tryToPlay();
  68365. }
  68366. }
  68367. else {
  68368. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  68369. this._soundSource.buffer = this._audioBuffer;
  68370. this._soundSource.connect(this._inputAudioNode);
  68371. this._soundSource.loop = this.loop;
  68372. this._soundSource.playbackRate.value = this._playbackRate;
  68373. this._soundSource.onended = function () { _this._onended(); };
  68374. if (this._soundSource.buffer) {
  68375. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  68376. }
  68377. }
  68378. this._startTime = startTime;
  68379. this.isPlaying = true;
  68380. this.isPaused = false;
  68381. }
  68382. catch (ex) {
  68383. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  68384. }
  68385. }
  68386. };
  68387. Sound.prototype._onended = function () {
  68388. this.isPlaying = false;
  68389. if (this.onended) {
  68390. this.onended();
  68391. }
  68392. this.onEndedObservable.notifyObservers(this);
  68393. };
  68394. /**
  68395. * Stop the sound
  68396. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  68397. */
  68398. Sound.prototype.stop = function (time) {
  68399. if (this.isPlaying) {
  68400. if (this._streaming) {
  68401. if (this._htmlAudioElement) {
  68402. this._htmlAudioElement.pause();
  68403. // Test needed for Firefox or it will generate an Invalid State Error
  68404. if (this._htmlAudioElement.currentTime > 0) {
  68405. this._htmlAudioElement.currentTime = 0;
  68406. }
  68407. }
  68408. else {
  68409. this._streamingSource.disconnect();
  68410. }
  68411. }
  68412. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  68413. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  68414. this._soundSource.stop(stopTime);
  68415. this._soundSource.onended = function () { };
  68416. if (!this.isPaused) {
  68417. this._startOffset = 0;
  68418. }
  68419. }
  68420. this.isPlaying = false;
  68421. }
  68422. };
  68423. /**
  68424. * Put the sound in pause
  68425. */
  68426. Sound.prototype.pause = function () {
  68427. if (this.isPlaying) {
  68428. this.isPaused = true;
  68429. if (this._streaming) {
  68430. if (this._htmlAudioElement) {
  68431. this._htmlAudioElement.pause();
  68432. }
  68433. else {
  68434. this._streamingSource.disconnect();
  68435. }
  68436. }
  68437. else if (BABYLON.Engine.audioEngine.audioContext) {
  68438. this.stop(0);
  68439. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  68440. }
  68441. }
  68442. };
  68443. /**
  68444. * Sets a dedicated volume for this sounds
  68445. * @param newVolume Define the new volume of the sound
  68446. * @param time Define in how long the sound should be at this value
  68447. */
  68448. Sound.prototype.setVolume = function (newVolume, time) {
  68449. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  68450. if (time && BABYLON.Engine.audioEngine.audioContext) {
  68451. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  68452. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  68453. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  68454. }
  68455. else {
  68456. this._soundGain.gain.value = newVolume;
  68457. }
  68458. }
  68459. this._volume = newVolume;
  68460. };
  68461. /**
  68462. * Set the sound play back rate
  68463. * @param newPlaybackRate Define the playback rate the sound should be played at
  68464. */
  68465. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  68466. this._playbackRate = newPlaybackRate;
  68467. if (this.isPlaying) {
  68468. if (this._streaming && this._htmlAudioElement) {
  68469. this._htmlAudioElement.playbackRate = this._playbackRate;
  68470. }
  68471. else if (this._soundSource) {
  68472. this._soundSource.playbackRate.value = this._playbackRate;
  68473. }
  68474. }
  68475. };
  68476. /**
  68477. * Gets the volume of the sound.
  68478. * @returns the volume of the sound
  68479. */
  68480. Sound.prototype.getVolume = function () {
  68481. return this._volume;
  68482. };
  68483. /**
  68484. * Attach the sound to a dedicated mesh
  68485. * @param meshToConnectTo The mesh to connect the sound with
  68486. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  68487. */
  68488. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  68489. var _this = this;
  68490. if (this._connectedMesh && this._registerFunc) {
  68491. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  68492. this._registerFunc = null;
  68493. }
  68494. this._connectedMesh = meshToConnectTo;
  68495. if (!this.spatialSound) {
  68496. this.spatialSound = true;
  68497. this._createSpatialParameters();
  68498. if (this.isPlaying && this.loop) {
  68499. this.stop();
  68500. this.play();
  68501. }
  68502. }
  68503. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  68504. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  68505. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  68506. };
  68507. /**
  68508. * Detach the sound from the previously attached mesh
  68509. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  68510. */
  68511. Sound.prototype.detachFromMesh = function () {
  68512. if (this._connectedMesh && this._registerFunc) {
  68513. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  68514. this._registerFunc = null;
  68515. this._connectedMesh = null;
  68516. }
  68517. };
  68518. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  68519. if (!node.getBoundingInfo) {
  68520. return;
  68521. }
  68522. var mesh = node;
  68523. if (this._positionInEmitterSpace) {
  68524. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  68525. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  68526. }
  68527. else {
  68528. var boundingInfo = mesh.getBoundingInfo();
  68529. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  68530. }
  68531. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  68532. this._updateDirection();
  68533. }
  68534. };
  68535. /**
  68536. * Clone the current sound in the scene.
  68537. * @returns the new sound clone
  68538. */
  68539. Sound.prototype.clone = function () {
  68540. var _this = this;
  68541. if (!this._streaming) {
  68542. var setBufferAndRun = function () {
  68543. if (_this._isReadyToPlay) {
  68544. clonedSound._audioBuffer = _this.getAudioBuffer();
  68545. clonedSound._isReadyToPlay = true;
  68546. if (clonedSound.autoplay) {
  68547. clonedSound.play();
  68548. }
  68549. }
  68550. else {
  68551. window.setTimeout(setBufferAndRun, 300);
  68552. }
  68553. };
  68554. var currentOptions = {
  68555. autoplay: this.autoplay, loop: this.loop,
  68556. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  68557. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  68558. refDistance: this.refDistance, distanceModel: this.distanceModel
  68559. };
  68560. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  68561. if (this.useCustomAttenuation) {
  68562. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  68563. }
  68564. clonedSound.setPosition(this._position);
  68565. clonedSound.setPlaybackRate(this._playbackRate);
  68566. setBufferAndRun();
  68567. return clonedSound;
  68568. }
  68569. // Can't clone a streaming sound
  68570. else {
  68571. return null;
  68572. }
  68573. };
  68574. /**
  68575. * Gets the current underlying audio buffer containing the data
  68576. * @returns the audio buffer
  68577. */
  68578. Sound.prototype.getAudioBuffer = function () {
  68579. return this._audioBuffer;
  68580. };
  68581. /**
  68582. * Serializes the Sound in a JSON representation
  68583. * @returns the JSON representation of the sound
  68584. */
  68585. Sound.prototype.serialize = function () {
  68586. var serializationObject = {
  68587. name: this.name,
  68588. url: this.name,
  68589. autoplay: this.autoplay,
  68590. loop: this.loop,
  68591. volume: this._volume,
  68592. spatialSound: this.spatialSound,
  68593. maxDistance: this.maxDistance,
  68594. rolloffFactor: this.rolloffFactor,
  68595. refDistance: this.refDistance,
  68596. distanceModel: this.distanceModel,
  68597. playbackRate: this._playbackRate,
  68598. panningModel: this._panningModel,
  68599. soundTrackId: this.soundTrackId
  68600. };
  68601. if (this.spatialSound) {
  68602. if (this._connectedMesh)
  68603. serializationObject.connectedMeshId = this._connectedMesh.id;
  68604. serializationObject.position = this._position.asArray();
  68605. serializationObject.refDistance = this.refDistance;
  68606. serializationObject.distanceModel = this.distanceModel;
  68607. serializationObject.isDirectional = this._isDirectional;
  68608. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  68609. serializationObject.coneInnerAngle = this._coneInnerAngle;
  68610. serializationObject.coneOuterAngle = this._coneOuterAngle;
  68611. serializationObject.coneOuterGain = this._coneOuterGain;
  68612. }
  68613. return serializationObject;
  68614. };
  68615. /**
  68616. * Parse a JSON representation of a sound to innstantiate in a given scene
  68617. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  68618. * @param scene Define the scene the new parsed sound should be created in
  68619. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  68620. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  68621. * @returns the newly parsed sound
  68622. */
  68623. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  68624. var soundName = parsedSound.name;
  68625. var soundUrl;
  68626. if (parsedSound.url) {
  68627. soundUrl = rootUrl + parsedSound.url;
  68628. }
  68629. else {
  68630. soundUrl = rootUrl + soundName;
  68631. }
  68632. var options = {
  68633. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  68634. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  68635. rolloffFactor: parsedSound.rolloffFactor,
  68636. refDistance: parsedSound.refDistance,
  68637. distanceModel: parsedSound.distanceModel,
  68638. playbackRate: parsedSound.playbackRate
  68639. };
  68640. var newSound;
  68641. if (!sourceSound) {
  68642. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  68643. scene._addPendingData(newSound);
  68644. }
  68645. else {
  68646. var setBufferAndRun = function () {
  68647. if (sourceSound._isReadyToPlay) {
  68648. newSound._audioBuffer = sourceSound.getAudioBuffer();
  68649. newSound._isReadyToPlay = true;
  68650. if (newSound.autoplay) {
  68651. newSound.play();
  68652. }
  68653. }
  68654. else {
  68655. window.setTimeout(setBufferAndRun, 300);
  68656. }
  68657. };
  68658. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  68659. setBufferAndRun();
  68660. }
  68661. if (parsedSound.position) {
  68662. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  68663. newSound.setPosition(soundPosition);
  68664. }
  68665. if (parsedSound.isDirectional) {
  68666. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  68667. if (parsedSound.localDirectionToMesh) {
  68668. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  68669. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  68670. }
  68671. }
  68672. if (parsedSound.connectedMeshId) {
  68673. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  68674. if (connectedMesh) {
  68675. newSound.attachToMesh(connectedMesh);
  68676. }
  68677. }
  68678. return newSound;
  68679. };
  68680. return Sound;
  68681. }());
  68682. BABYLON.Sound = Sound;
  68683. })(BABYLON || (BABYLON = {}));
  68684. //# sourceMappingURL=babylon.sound.js.map
  68685. var BABYLON;
  68686. (function (BABYLON) {
  68687. /**
  68688. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  68689. * It will be also used in a future release to apply effects on a specific track.
  68690. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  68691. */
  68692. var SoundTrack = /** @class */ (function () {
  68693. /**
  68694. * Creates a new sound track.
  68695. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  68696. * @param scene Define the scene the sound track belongs to
  68697. * @param options
  68698. */
  68699. function SoundTrack(scene, options) {
  68700. if (options === void 0) { options = {}; }
  68701. /**
  68702. * The unique identifier of the sound track in the scene.
  68703. */
  68704. this.id = -1;
  68705. this._isMainTrack = false;
  68706. this._isInitialized = false;
  68707. this._scene = scene;
  68708. this.soundCollection = new Array();
  68709. this._options = options;
  68710. if (!this._isMainTrack && this._scene.soundTracks) {
  68711. this._scene.soundTracks.push(this);
  68712. this.id = this._scene.soundTracks.length - 1;
  68713. }
  68714. }
  68715. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  68716. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  68717. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  68718. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  68719. if (this._options) {
  68720. if (this._options.volume) {
  68721. this._outputAudioNode.gain.value = this._options.volume;
  68722. }
  68723. if (this._options.mainTrack) {
  68724. this._isMainTrack = this._options.mainTrack;
  68725. }
  68726. }
  68727. this._isInitialized = true;
  68728. }
  68729. };
  68730. /**
  68731. * Release the sound track and its associated resources
  68732. */
  68733. SoundTrack.prototype.dispose = function () {
  68734. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  68735. if (this._connectedAnalyser) {
  68736. this._connectedAnalyser.stopDebugCanvas();
  68737. }
  68738. while (this.soundCollection.length) {
  68739. this.soundCollection[0].dispose();
  68740. }
  68741. if (this._outputAudioNode) {
  68742. this._outputAudioNode.disconnect();
  68743. }
  68744. this._outputAudioNode = null;
  68745. }
  68746. };
  68747. /**
  68748. * Adds a sound to this sound track
  68749. * @param sound define the cound to add
  68750. * @ignoreNaming
  68751. */
  68752. SoundTrack.prototype.AddSound = function (sound) {
  68753. if (!this._isInitialized) {
  68754. this._initializeSoundTrackAudioGraph();
  68755. }
  68756. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68757. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  68758. }
  68759. if (sound.soundTrackId) {
  68760. if (sound.soundTrackId === -1) {
  68761. this._scene.mainSoundTrack.RemoveSound(sound);
  68762. }
  68763. else if (this._scene.soundTracks) {
  68764. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  68765. }
  68766. }
  68767. this.soundCollection.push(sound);
  68768. sound.soundTrackId = this.id;
  68769. };
  68770. /**
  68771. * Removes a sound to this sound track
  68772. * @param sound define the cound to remove
  68773. * @ignoreNaming
  68774. */
  68775. SoundTrack.prototype.RemoveSound = function (sound) {
  68776. var index = this.soundCollection.indexOf(sound);
  68777. if (index !== -1) {
  68778. this.soundCollection.splice(index, 1);
  68779. }
  68780. };
  68781. /**
  68782. * Set a global volume for the full sound track.
  68783. * @param newVolume Define the new volume of the sound track
  68784. */
  68785. SoundTrack.prototype.setVolume = function (newVolume) {
  68786. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68787. this._outputAudioNode.gain.value = newVolume;
  68788. }
  68789. };
  68790. /**
  68791. * Switch the panning model to HRTF:
  68792. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  68793. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68794. */
  68795. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  68796. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68797. for (var i = 0; i < this.soundCollection.length; i++) {
  68798. this.soundCollection[i].switchPanningModelToHRTF();
  68799. }
  68800. }
  68801. };
  68802. /**
  68803. * Switch the panning model to Equal Power:
  68804. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  68805. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68806. */
  68807. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  68808. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68809. for (var i = 0; i < this.soundCollection.length; i++) {
  68810. this.soundCollection[i].switchPanningModelToEqualPower();
  68811. }
  68812. }
  68813. };
  68814. /**
  68815. * Connect the sound track to an audio analyser allowing some amazing
  68816. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  68817. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  68818. * @param analyser The analyser to connect to the engine
  68819. */
  68820. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  68821. if (this._connectedAnalyser) {
  68822. this._connectedAnalyser.stopDebugCanvas();
  68823. }
  68824. this._connectedAnalyser = analyser;
  68825. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68826. this._outputAudioNode.disconnect();
  68827. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  68828. }
  68829. };
  68830. return SoundTrack;
  68831. }());
  68832. BABYLON.SoundTrack = SoundTrack;
  68833. })(BABYLON || (BABYLON = {}));
  68834. //# sourceMappingURL=babylon.soundtrack.js.map
  68835. var BABYLON;
  68836. (function (BABYLON) {
  68837. /**
  68838. * Class used to work with sound analyzer using fast fourier transform (FFT)
  68839. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  68840. */
  68841. var Analyser = /** @class */ (function () {
  68842. /**
  68843. * Creates a new analyser
  68844. * @param scene defines hosting scene
  68845. */
  68846. function Analyser(scene) {
  68847. /**
  68848. * Gets or sets the smoothing
  68849. * @ignorenaming
  68850. */
  68851. this.SMOOTHING = 0.75;
  68852. /**
  68853. * Gets or sets the FFT table size
  68854. * @ignorenaming
  68855. */
  68856. this.FFT_SIZE = 512;
  68857. /**
  68858. * Gets or sets the bar graph amplitude
  68859. * @ignorenaming
  68860. */
  68861. this.BARGRAPHAMPLITUDE = 256;
  68862. /**
  68863. * Gets or sets the position of the debug canvas
  68864. * @ignorenaming
  68865. */
  68866. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  68867. /**
  68868. * Gets or sets the debug canvas size
  68869. * @ignorenaming
  68870. */
  68871. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  68872. this._scene = scene;
  68873. this._audioEngine = BABYLON.Engine.audioEngine;
  68874. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  68875. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  68876. this._webAudioAnalyser.minDecibels = -140;
  68877. this._webAudioAnalyser.maxDecibels = 0;
  68878. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  68879. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  68880. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  68881. }
  68882. }
  68883. /**
  68884. * Get the number of data values you will have to play with for the visualization
  68885. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  68886. * @returns a number
  68887. */
  68888. Analyser.prototype.getFrequencyBinCount = function () {
  68889. if (this._audioEngine.canUseWebAudio) {
  68890. return this._webAudioAnalyser.frequencyBinCount;
  68891. }
  68892. else {
  68893. return 0;
  68894. }
  68895. };
  68896. /**
  68897. * Gets the current frequency data as a byte array
  68898. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  68899. * @returns a Uint8Array
  68900. */
  68901. Analyser.prototype.getByteFrequencyData = function () {
  68902. if (this._audioEngine.canUseWebAudio) {
  68903. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68904. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68905. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  68906. }
  68907. return this._byteFreqs;
  68908. };
  68909. /**
  68910. * Gets the current waveform as a byte array
  68911. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  68912. * @returns a Uint8Array
  68913. */
  68914. Analyser.prototype.getByteTimeDomainData = function () {
  68915. if (this._audioEngine.canUseWebAudio) {
  68916. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68917. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68918. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  68919. }
  68920. return this._byteTime;
  68921. };
  68922. /**
  68923. * Gets the current frequency data as a float array
  68924. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  68925. * @returns a Float32Array
  68926. */
  68927. Analyser.prototype.getFloatFrequencyData = function () {
  68928. if (this._audioEngine.canUseWebAudio) {
  68929. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68930. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68931. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  68932. }
  68933. return this._floatFreqs;
  68934. };
  68935. /**
  68936. * Renders the debug canvas
  68937. */
  68938. Analyser.prototype.drawDebugCanvas = function () {
  68939. var _this = this;
  68940. if (this._audioEngine.canUseWebAudio) {
  68941. if (!this._debugCanvas) {
  68942. this._debugCanvas = document.createElement("canvas");
  68943. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  68944. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  68945. this._debugCanvas.style.position = "absolute";
  68946. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  68947. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  68948. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  68949. document.body.appendChild(this._debugCanvas);
  68950. this._registerFunc = function () {
  68951. _this.drawDebugCanvas();
  68952. };
  68953. this._scene.registerBeforeRender(this._registerFunc);
  68954. }
  68955. if (this._registerFunc && this._debugCanvasContext) {
  68956. var workingArray = this.getByteFrequencyData();
  68957. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  68958. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  68959. // Draw the frequency domain chart.
  68960. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  68961. var value = workingArray[i];
  68962. var percent = value / this.BARGRAPHAMPLITUDE;
  68963. var height = this.DEBUGCANVASSIZE.height * percent;
  68964. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  68965. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  68966. var hue = i / this.getFrequencyBinCount() * 360;
  68967. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  68968. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  68969. }
  68970. }
  68971. }
  68972. };
  68973. /**
  68974. * Stops rendering the debug canvas and removes it
  68975. */
  68976. Analyser.prototype.stopDebugCanvas = function () {
  68977. if (this._debugCanvas) {
  68978. if (this._registerFunc) {
  68979. this._scene.unregisterBeforeRender(this._registerFunc);
  68980. this._registerFunc = null;
  68981. }
  68982. document.body.removeChild(this._debugCanvas);
  68983. this._debugCanvas = null;
  68984. this._debugCanvasContext = null;
  68985. }
  68986. };
  68987. /**
  68988. * Connects two audio nodes
  68989. * @param inputAudioNode defines first node to connect
  68990. * @param outputAudioNode defines second node to connect
  68991. */
  68992. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  68993. if (this._audioEngine.canUseWebAudio) {
  68994. inputAudioNode.connect(this._webAudioAnalyser);
  68995. this._webAudioAnalyser.connect(outputAudioNode);
  68996. }
  68997. };
  68998. /**
  68999. * Releases all associated resources
  69000. */
  69001. Analyser.prototype.dispose = function () {
  69002. if (this._audioEngine.canUseWebAudio) {
  69003. this._webAudioAnalyser.disconnect();
  69004. }
  69005. };
  69006. return Analyser;
  69007. }());
  69008. BABYLON.Analyser = Analyser;
  69009. })(BABYLON || (BABYLON = {}));
  69010. //# sourceMappingURL=babylon.analyser.js.map
  69011. var BABYLON;
  69012. (function (BABYLON) {
  69013. /**
  69014. * Wraps one or more Sound objects and selects one with random weight for playback.
  69015. */
  69016. var WeightedSound = /** @class */ (function () {
  69017. /**
  69018. * Creates a new WeightedSound from the list of sounds given.
  69019. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  69020. * @param sounds Array of Sounds that will be selected from.
  69021. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  69022. */
  69023. function WeightedSound(loop, sounds, weights) {
  69024. var _this = this;
  69025. /** When true a Sound will be selected and played when the current playing Sound completes. */
  69026. this.loop = false;
  69027. this._coneInnerAngle = 360;
  69028. this._coneOuterAngle = 360;
  69029. this._volume = 1;
  69030. /** A Sound is currently playing. */
  69031. this.isPlaying = false;
  69032. /** A Sound is currently paused. */
  69033. this.isPaused = false;
  69034. this._sounds = [];
  69035. this._weights = [];
  69036. if (sounds.length !== weights.length) {
  69037. throw new Error('Sounds length does not equal weights length');
  69038. }
  69039. this.loop = loop;
  69040. this._weights = weights;
  69041. // Normalize the weights
  69042. var weightSum = 0;
  69043. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  69044. var weight = weights_1[_i];
  69045. weightSum += weight;
  69046. }
  69047. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  69048. for (var i = 0; i < this._weights.length; i++) {
  69049. this._weights[i] *= invWeightSum;
  69050. }
  69051. this._sounds = sounds;
  69052. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  69053. var sound = _b[_a];
  69054. sound.onEndedObservable.add(function () { _this._onended(); });
  69055. }
  69056. }
  69057. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  69058. /**
  69059. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  69060. */
  69061. get: function () {
  69062. return this._coneInnerAngle;
  69063. },
  69064. /**
  69065. * The size of cone in degress for a directional sound in which there will be no attenuation.
  69066. */
  69067. set: function (value) {
  69068. if (value !== this._coneInnerAngle) {
  69069. if (this._coneOuterAngle < value) {
  69070. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69071. return;
  69072. }
  69073. this._coneInnerAngle = value;
  69074. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  69075. var sound = _a[_i];
  69076. sound.directionalConeInnerAngle = value;
  69077. }
  69078. }
  69079. },
  69080. enumerable: true,
  69081. configurable: true
  69082. });
  69083. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  69084. /**
  69085. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  69086. * Listener angles between innerAngle and outerAngle will falloff linearly.
  69087. */
  69088. get: function () {
  69089. return this._coneOuterAngle;
  69090. },
  69091. /**
  69092. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  69093. * Listener angles between innerAngle and outerAngle will falloff linearly.
  69094. */
  69095. set: function (value) {
  69096. if (value !== this._coneOuterAngle) {
  69097. if (value < this._coneInnerAngle) {
  69098. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69099. return;
  69100. }
  69101. this._coneOuterAngle = value;
  69102. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  69103. var sound = _a[_i];
  69104. sound.directionalConeOuterAngle = value;
  69105. }
  69106. }
  69107. },
  69108. enumerable: true,
  69109. configurable: true
  69110. });
  69111. Object.defineProperty(WeightedSound.prototype, "volume", {
  69112. /**
  69113. * Playback volume.
  69114. */
  69115. get: function () {
  69116. return this._volume;
  69117. },
  69118. /**
  69119. * Playback volume.
  69120. */
  69121. set: function (value) {
  69122. if (value !== this._volume) {
  69123. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  69124. var sound = _a[_i];
  69125. sound.setVolume(value);
  69126. }
  69127. }
  69128. },
  69129. enumerable: true,
  69130. configurable: true
  69131. });
  69132. WeightedSound.prototype._onended = function () {
  69133. if (this._currentIndex !== undefined) {
  69134. this._sounds[this._currentIndex].autoplay = false;
  69135. }
  69136. if (this.loop && this.isPlaying) {
  69137. this.play();
  69138. }
  69139. else {
  69140. this.isPlaying = false;
  69141. }
  69142. };
  69143. /**
  69144. * Suspend playback
  69145. */
  69146. WeightedSound.prototype.pause = function () {
  69147. this.isPaused = true;
  69148. if (this._currentIndex !== undefined) {
  69149. this._sounds[this._currentIndex].pause();
  69150. }
  69151. };
  69152. /**
  69153. * Stop playback
  69154. */
  69155. WeightedSound.prototype.stop = function () {
  69156. this.isPlaying = false;
  69157. if (this._currentIndex !== undefined) {
  69158. this._sounds[this._currentIndex].stop();
  69159. }
  69160. };
  69161. /**
  69162. * Start playback.
  69163. * @param startOffset Position the clip head at a specific time in seconds.
  69164. */
  69165. WeightedSound.prototype.play = function (startOffset) {
  69166. if (!this.isPaused) {
  69167. this.stop();
  69168. var randomValue = Math.random();
  69169. var total = 0;
  69170. for (var i = 0; i < this._weights.length; i++) {
  69171. total += this._weights[i];
  69172. if (randomValue <= total) {
  69173. this._currentIndex = i;
  69174. break;
  69175. }
  69176. }
  69177. }
  69178. var sound = this._sounds[this._currentIndex];
  69179. if (sound.isReady()) {
  69180. sound.play(0, this.isPaused ? undefined : startOffset);
  69181. }
  69182. else {
  69183. sound.autoplay = true;
  69184. }
  69185. this.isPlaying = true;
  69186. this.isPaused = false;
  69187. };
  69188. return WeightedSound;
  69189. }());
  69190. BABYLON.WeightedSound = WeightedSound;
  69191. })(BABYLON || (BABYLON = {}));
  69192. //# sourceMappingURL=babylon.weightedsound.js.map
  69193. var BABYLON;
  69194. (function (BABYLON) {
  69195. // Adds the parser to the scene parsers.
  69196. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  69197. // TODO: add sound
  69198. var loadedSounds = [];
  69199. var loadedSound;
  69200. container.sounds = container.sounds || [];
  69201. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  69202. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  69203. var parsedSound = parsedData.sounds[index];
  69204. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69205. if (!parsedSound.url)
  69206. parsedSound.url = parsedSound.name;
  69207. if (!loadedSounds[parsedSound.url]) {
  69208. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  69209. loadedSounds[parsedSound.url] = loadedSound;
  69210. container.sounds.push(loadedSound);
  69211. }
  69212. else {
  69213. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  69214. }
  69215. }
  69216. else {
  69217. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  69218. }
  69219. }
  69220. }
  69221. loadedSounds = [];
  69222. });
  69223. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  69224. get: function () {
  69225. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69226. if (!compo) {
  69227. compo = new AudioSceneComponent(this);
  69228. this._addComponent(compo);
  69229. }
  69230. if (!this._mainSoundTrack) {
  69231. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  69232. }
  69233. return this._mainSoundTrack;
  69234. },
  69235. enumerable: true,
  69236. configurable: true
  69237. });
  69238. BABYLON.Scene.prototype.getSoundByName = function (name) {
  69239. var index;
  69240. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  69241. if (this.mainSoundTrack.soundCollection[index].name === name) {
  69242. return this.mainSoundTrack.soundCollection[index];
  69243. }
  69244. }
  69245. if (this.soundTracks) {
  69246. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  69247. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  69248. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  69249. return this.soundTracks[sdIndex].soundCollection[index];
  69250. }
  69251. }
  69252. }
  69253. }
  69254. return null;
  69255. };
  69256. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  69257. get: function () {
  69258. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69259. if (!compo) {
  69260. compo = new AudioSceneComponent(this);
  69261. this._addComponent(compo);
  69262. }
  69263. return compo.audioEnabled;
  69264. },
  69265. set: function (value) {
  69266. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69267. if (!compo) {
  69268. compo = new AudioSceneComponent(this);
  69269. this._addComponent(compo);
  69270. }
  69271. if (value) {
  69272. compo.enableAudio();
  69273. }
  69274. else {
  69275. compo.disableAudio();
  69276. }
  69277. },
  69278. enumerable: true,
  69279. configurable: true
  69280. });
  69281. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  69282. get: function () {
  69283. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69284. if (!compo) {
  69285. compo = new AudioSceneComponent(this);
  69286. this._addComponent(compo);
  69287. }
  69288. return compo.headphone;
  69289. },
  69290. set: function (value) {
  69291. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69292. if (!compo) {
  69293. compo = new AudioSceneComponent(this);
  69294. this._addComponent(compo);
  69295. }
  69296. if (value) {
  69297. compo.switchAudioModeForHeadphones();
  69298. }
  69299. else {
  69300. compo.switchAudioModeForNormalSpeakers();
  69301. }
  69302. },
  69303. enumerable: true,
  69304. configurable: true
  69305. });
  69306. /**
  69307. * Defines the sound scene component responsible to manage any sounds
  69308. * in a given scene.
  69309. */
  69310. var AudioSceneComponent = /** @class */ (function () {
  69311. /**
  69312. * Creates a new instance of the component for the given scene
  69313. * @param scene Defines the scene to register the component in
  69314. */
  69315. function AudioSceneComponent(scene) {
  69316. /**
  69317. * The component name helpfull to identify the component in the list of scene components.
  69318. */
  69319. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  69320. this._audioEnabled = true;
  69321. this._headphone = false;
  69322. this.scene = scene;
  69323. scene.soundTracks = new Array();
  69324. scene.sounds = new Array();
  69325. }
  69326. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  69327. /**
  69328. * Gets whether audio is enabled or not.
  69329. * Please use related enable/disable method to switch state.
  69330. */
  69331. get: function () {
  69332. return this._audioEnabled;
  69333. },
  69334. enumerable: true,
  69335. configurable: true
  69336. });
  69337. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  69338. /**
  69339. * Gets whether audio is outputing to headphone or not.
  69340. * Please use the according Switch methods to change output.
  69341. */
  69342. get: function () {
  69343. return this._headphone;
  69344. },
  69345. enumerable: true,
  69346. configurable: true
  69347. });
  69348. /**
  69349. * Registers the component in a given scene
  69350. */
  69351. AudioSceneComponent.prototype.register = function () {
  69352. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  69353. };
  69354. /**
  69355. * Rebuilds the elements related to this component in case of
  69356. * context lost for instance.
  69357. */
  69358. AudioSceneComponent.prototype.rebuild = function () {
  69359. // Nothing to do here. (Not rendering related)
  69360. };
  69361. /**
  69362. * Serializes the component data to the specified json object
  69363. * @param serializationObject The object to serialize to
  69364. */
  69365. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  69366. serializationObject.sounds = [];
  69367. if (this.scene.soundTracks) {
  69368. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  69369. var soundtrack = this.scene.soundTracks[index];
  69370. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  69371. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  69372. }
  69373. }
  69374. }
  69375. };
  69376. /**
  69377. * Adds all the element from the container to the scene
  69378. * @param container the container holding the elements
  69379. */
  69380. AudioSceneComponent.prototype.addFromContainer = function (container) {
  69381. var _this = this;
  69382. if (!container.sounds) {
  69383. return;
  69384. }
  69385. container.sounds.forEach(function (sound) {
  69386. sound.play();
  69387. sound.autoplay = true;
  69388. _this.scene.mainSoundTrack.AddSound(sound);
  69389. });
  69390. };
  69391. /**
  69392. * Removes all the elements in the container from the scene
  69393. * @param container contains the elements to remove
  69394. */
  69395. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  69396. var _this = this;
  69397. if (!container.sounds) {
  69398. return;
  69399. }
  69400. container.sounds.forEach(function (sound) {
  69401. sound.stop();
  69402. sound.autoplay = false;
  69403. _this.scene.mainSoundTrack.RemoveSound(sound);
  69404. });
  69405. };
  69406. /**
  69407. * Disposes the component and the associated ressources.
  69408. */
  69409. AudioSceneComponent.prototype.dispose = function () {
  69410. var scene = this.scene;
  69411. if (scene._mainSoundTrack) {
  69412. scene.mainSoundTrack.dispose();
  69413. }
  69414. if (scene.soundTracks) {
  69415. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  69416. scene.soundTracks[scIndex].dispose();
  69417. }
  69418. }
  69419. };
  69420. /**
  69421. * Disables audio in the associated scene.
  69422. */
  69423. AudioSceneComponent.prototype.disableAudio = function () {
  69424. var scene = this.scene;
  69425. this._audioEnabled = false;
  69426. var i;
  69427. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  69428. scene.mainSoundTrack.soundCollection[i].pause();
  69429. }
  69430. if (scene.soundTracks) {
  69431. for (i = 0; i < scene.soundTracks.length; i++) {
  69432. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  69433. scene.soundTracks[i].soundCollection[j].pause();
  69434. }
  69435. }
  69436. }
  69437. };
  69438. /**
  69439. * Enables audio in the associated scene.
  69440. */
  69441. AudioSceneComponent.prototype.enableAudio = function () {
  69442. var scene = this.scene;
  69443. this._audioEnabled = true;
  69444. var i;
  69445. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  69446. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  69447. scene.mainSoundTrack.soundCollection[i].play();
  69448. }
  69449. }
  69450. if (scene.soundTracks) {
  69451. for (i = 0; i < scene.soundTracks.length; i++) {
  69452. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  69453. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  69454. scene.soundTracks[i].soundCollection[j].play();
  69455. }
  69456. }
  69457. }
  69458. }
  69459. };
  69460. /**
  69461. * Switch audio to headphone output.
  69462. */
  69463. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  69464. var scene = this.scene;
  69465. this._headphone = true;
  69466. scene.mainSoundTrack.switchPanningModelToHRTF();
  69467. if (scene.soundTracks) {
  69468. for (var i = 0; i < scene.soundTracks.length; i++) {
  69469. scene.soundTracks[i].switchPanningModelToHRTF();
  69470. }
  69471. }
  69472. };
  69473. /**
  69474. * Switch audio to normal speakers.
  69475. */
  69476. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  69477. var scene = this.scene;
  69478. this._headphone = false;
  69479. scene.mainSoundTrack.switchPanningModelToEqualPower();
  69480. if (scene.soundTracks) {
  69481. for (var i = 0; i < scene.soundTracks.length; i++) {
  69482. scene.soundTracks[i].switchPanningModelToEqualPower();
  69483. }
  69484. }
  69485. };
  69486. AudioSceneComponent.prototype._afterRender = function () {
  69487. var scene = this.scene;
  69488. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  69489. return;
  69490. }
  69491. var listeningCamera;
  69492. var audioEngine = BABYLON.Engine.audioEngine;
  69493. if (scene.activeCameras.length > 0) {
  69494. listeningCamera = scene.activeCameras[0];
  69495. }
  69496. else {
  69497. listeningCamera = scene.activeCamera;
  69498. }
  69499. if (listeningCamera && audioEngine.audioContext) {
  69500. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  69501. // for VR cameras
  69502. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  69503. listeningCamera = listeningCamera.rigCameras[0];
  69504. }
  69505. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  69506. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  69507. cameraDirection.normalize();
  69508. // To avoid some errors on GearVR
  69509. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  69510. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  69511. }
  69512. var i;
  69513. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  69514. var sound = scene.mainSoundTrack.soundCollection[i];
  69515. if (sound.useCustomAttenuation) {
  69516. sound.updateDistanceFromListener();
  69517. }
  69518. }
  69519. if (scene.soundTracks) {
  69520. for (i = 0; i < scene.soundTracks.length; i++) {
  69521. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  69522. sound = scene.soundTracks[i].soundCollection[j];
  69523. if (sound.useCustomAttenuation) {
  69524. sound.updateDistanceFromListener();
  69525. }
  69526. }
  69527. }
  69528. }
  69529. }
  69530. };
  69531. return AudioSceneComponent;
  69532. }());
  69533. BABYLON.AudioSceneComponent = AudioSceneComponent;
  69534. })(BABYLON || (BABYLON = {}));
  69535. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  69536. var BABYLON;
  69537. (function (BABYLON) {
  69538. /**
  69539. * This defines an action helpful to play a defined sound on a triggered action.
  69540. */
  69541. var PlaySoundAction = /** @class */ (function (_super) {
  69542. __extends(PlaySoundAction, _super);
  69543. /**
  69544. * Instantiate the action
  69545. * @param triggerOptions defines the trigger options
  69546. * @param sound defines the sound to play
  69547. * @param condition defines the trigger related conditions
  69548. */
  69549. function PlaySoundAction(triggerOptions, sound, condition) {
  69550. var _this = _super.call(this, triggerOptions, condition) || this;
  69551. _this._sound = sound;
  69552. return _this;
  69553. }
  69554. /** @hidden */
  69555. PlaySoundAction.prototype._prepare = function () {
  69556. };
  69557. /**
  69558. * Execute the action and play the sound.
  69559. */
  69560. PlaySoundAction.prototype.execute = function () {
  69561. if (this._sound !== undefined)
  69562. this._sound.play();
  69563. };
  69564. /**
  69565. * Serializes the actions and its related information.
  69566. * @param parent defines the object to serialize in
  69567. * @returns the serialized object
  69568. */
  69569. PlaySoundAction.prototype.serialize = function (parent) {
  69570. return _super.prototype._serialize.call(this, {
  69571. name: "PlaySoundAction",
  69572. properties: [{ name: "sound", value: this._sound.name }]
  69573. }, parent);
  69574. };
  69575. return PlaySoundAction;
  69576. }(BABYLON.Action));
  69577. BABYLON.PlaySoundAction = PlaySoundAction;
  69578. /**
  69579. * This defines an action helpful to stop a defined sound on a triggered action.
  69580. */
  69581. var StopSoundAction = /** @class */ (function (_super) {
  69582. __extends(StopSoundAction, _super);
  69583. /**
  69584. * Instantiate the action
  69585. * @param triggerOptions defines the trigger options
  69586. * @param sound defines the sound to stop
  69587. * @param condition defines the trigger related conditions
  69588. */
  69589. function StopSoundAction(triggerOptions, sound, condition) {
  69590. var _this = _super.call(this, triggerOptions, condition) || this;
  69591. _this._sound = sound;
  69592. return _this;
  69593. }
  69594. /** @hidden */
  69595. StopSoundAction.prototype._prepare = function () {
  69596. };
  69597. /**
  69598. * Execute the action and stop the sound.
  69599. */
  69600. StopSoundAction.prototype.execute = function () {
  69601. if (this._sound !== undefined)
  69602. this._sound.stop();
  69603. };
  69604. /**
  69605. * Serializes the actions and its related information.
  69606. * @param parent defines the object to serialize in
  69607. * @returns the serialized object
  69608. */
  69609. StopSoundAction.prototype.serialize = function (parent) {
  69610. return _super.prototype._serialize.call(this, {
  69611. name: "StopSoundAction",
  69612. properties: [{ name: "sound", value: this._sound.name }]
  69613. }, parent);
  69614. };
  69615. return StopSoundAction;
  69616. }(BABYLON.Action));
  69617. BABYLON.StopSoundAction = StopSoundAction;
  69618. })(BABYLON || (BABYLON = {}));
  69619. //# sourceMappingURL=babylon.directAudioActions.js.map
  69620. var BABYLON;
  69621. (function (BABYLON) {
  69622. var CubeTexture = /** @class */ (function (_super) {
  69623. __extends(CubeTexture, _super);
  69624. /**
  69625. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  69626. * as prefiltered data.
  69627. * @param rootUrl defines the url of the texture or the root name of the six images
  69628. * @param scene defines the scene the texture is attached to
  69629. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  69630. * @param noMipmap defines if mipmaps should be created or not
  69631. * @param files defines the six files to load for the different faces
  69632. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  69633. * @param onError defines a callback triggered in case of error during load
  69634. * @param format defines the internal format to use for the texture once loaded
  69635. * @param prefiltered defines whether or not the texture is created from prefiltered data
  69636. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  69637. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  69638. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  69639. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  69640. * @return the cube texture
  69641. */
  69642. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  69643. if (extensions === void 0) { extensions = null; }
  69644. if (noMipmap === void 0) { noMipmap = false; }
  69645. if (files === void 0) { files = null; }
  69646. if (onLoad === void 0) { onLoad = null; }
  69647. if (onError === void 0) { onError = null; }
  69648. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69649. if (prefiltered === void 0) { prefiltered = false; }
  69650. if (forcedExtension === void 0) { forcedExtension = null; }
  69651. if (createPolynomials === void 0) { createPolynomials = false; }
  69652. if (lodScale === void 0) { lodScale = 0.8; }
  69653. if (lodOffset === void 0) { lodOffset = 0; }
  69654. var _this = _super.call(this, scene) || this;
  69655. /**
  69656. * Gets or sets the center of the bounding box associated with the cube texture
  69657. * It must define where the camera used to render the texture was set
  69658. */
  69659. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  69660. _this._rotationY = 0;
  69661. /** @hidden */
  69662. _this._prefiltered = false;
  69663. _this.name = rootUrl;
  69664. _this.url = rootUrl;
  69665. _this._noMipmap = noMipmap;
  69666. _this.hasAlpha = false;
  69667. _this._format = format;
  69668. _this.isCube = true;
  69669. _this._textureMatrix = BABYLON.Matrix.Identity();
  69670. _this._createPolynomials = createPolynomials;
  69671. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  69672. if (!rootUrl && !files) {
  69673. return _this;
  69674. }
  69675. var lastDot = rootUrl.lastIndexOf(".");
  69676. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  69677. var isDDS = (extension === ".dds");
  69678. var isEnv = (extension === ".env");
  69679. if (isEnv) {
  69680. _this.gammaSpace = false;
  69681. _this._prefiltered = false;
  69682. }
  69683. else {
  69684. _this._prefiltered = prefiltered;
  69685. if (prefiltered) {
  69686. _this.gammaSpace = false;
  69687. }
  69688. }
  69689. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  69690. if (!files) {
  69691. if (!isEnv && !isDDS && !extensions) {
  69692. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  69693. }
  69694. files = [];
  69695. if (extensions) {
  69696. for (var index = 0; index < extensions.length; index++) {
  69697. files.push(rootUrl + extensions[index]);
  69698. }
  69699. }
  69700. }
  69701. _this._files = files;
  69702. if (!_this._texture) {
  69703. if (!scene.useDelayedTextureLoading) {
  69704. if (prefiltered) {
  69705. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  69706. }
  69707. else {
  69708. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  69709. }
  69710. }
  69711. else {
  69712. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  69713. }
  69714. }
  69715. else if (onLoad) {
  69716. if (_this._texture.isReady) {
  69717. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  69718. }
  69719. else {
  69720. _this._texture.onLoadedObservable.add(onLoad);
  69721. }
  69722. }
  69723. return _this;
  69724. }
  69725. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  69726. get: function () {
  69727. return this._boundingBoxSize;
  69728. },
  69729. /**
  69730. * Gets or sets the size of the bounding box associated with the cube texture
  69731. * When defined, the cubemap will switch to local mode
  69732. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  69733. * @example https://www.babylonjs-playground.com/#RNASML
  69734. */
  69735. set: function (value) {
  69736. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  69737. return;
  69738. }
  69739. this._boundingBoxSize = value;
  69740. var scene = this.getScene();
  69741. if (scene) {
  69742. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  69743. }
  69744. },
  69745. enumerable: true,
  69746. configurable: true
  69747. });
  69748. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  69749. /**
  69750. * Gets texture matrix rotation angle around Y axis radians.
  69751. */
  69752. get: function () {
  69753. return this._rotationY;
  69754. },
  69755. /**
  69756. * Sets texture matrix rotation angle around Y axis in radians.
  69757. */
  69758. set: function (value) {
  69759. this._rotationY = value;
  69760. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  69761. },
  69762. enumerable: true,
  69763. configurable: true
  69764. });
  69765. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  69766. var rootUrlKey = "";
  69767. files.forEach(function (url) { return rootUrlKey += url; });
  69768. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  69769. };
  69770. /**
  69771. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  69772. * @param url defines the url of the prefiltered texture
  69773. * @param scene defines the scene the texture is attached to
  69774. * @param forcedExtension defines the extension of the file if different from the url
  69775. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  69776. * @return the prefiltered texture
  69777. */
  69778. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  69779. if (forcedExtension === void 0) { forcedExtension = null; }
  69780. if (createPolynomials === void 0) { createPolynomials = true; }
  69781. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  69782. };
  69783. // Methods
  69784. CubeTexture.prototype.delayLoad = function () {
  69785. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  69786. return;
  69787. }
  69788. var scene = this.getScene();
  69789. if (!scene) {
  69790. return;
  69791. }
  69792. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  69793. this._texture = this._getFromCache(this.url, this._noMipmap);
  69794. if (!this._texture) {
  69795. if (this._prefiltered) {
  69796. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  69797. }
  69798. else {
  69799. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  69800. }
  69801. }
  69802. };
  69803. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  69804. return this._textureMatrix;
  69805. };
  69806. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  69807. this._textureMatrix = value;
  69808. };
  69809. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  69810. var texture = BABYLON.SerializationHelper.Parse(function () {
  69811. var prefiltered = false;
  69812. if (parsedTexture.prefiltered) {
  69813. prefiltered = parsedTexture.prefiltered;
  69814. }
  69815. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  69816. }, parsedTexture, scene);
  69817. // Local Cubemaps
  69818. if (parsedTexture.boundingBoxPosition) {
  69819. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  69820. }
  69821. if (parsedTexture.boundingBoxSize) {
  69822. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  69823. }
  69824. // Animations
  69825. if (parsedTexture.animations) {
  69826. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  69827. var parsedAnimation = parsedTexture.animations[animationIndex];
  69828. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  69829. }
  69830. }
  69831. return texture;
  69832. };
  69833. CubeTexture.prototype.clone = function () {
  69834. var _this = this;
  69835. return BABYLON.SerializationHelper.Clone(function () {
  69836. var scene = _this.getScene();
  69837. if (!scene) {
  69838. return _this;
  69839. }
  69840. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  69841. }, this);
  69842. };
  69843. __decorate([
  69844. BABYLON.serialize("rotationY")
  69845. ], CubeTexture.prototype, "rotationY", null);
  69846. return CubeTexture;
  69847. }(BABYLON.BaseTexture));
  69848. BABYLON.CubeTexture = CubeTexture;
  69849. })(BABYLON || (BABYLON = {}));
  69850. //# sourceMappingURL=babylon.cubeTexture.js.map
  69851. var BABYLON;
  69852. (function (BABYLON) {
  69853. /**
  69854. * Raw cube texture where the raw buffers are passed in
  69855. */
  69856. var RawCubeTexture = /** @class */ (function (_super) {
  69857. __extends(RawCubeTexture, _super);
  69858. /**
  69859. * Creates a cube texture where the raw buffers are passed in.
  69860. * @param scene defines the scene the texture is attached to
  69861. * @param data defines the array of data to use to create each face
  69862. * @param size defines the size of the textures
  69863. * @param format defines the format of the data
  69864. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  69865. * @param generateMipMaps defines if the engine should generate the mip levels
  69866. * @param invertY defines if data must be stored with Y axis inverted
  69867. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  69868. * @param compression defines the compression used (null by default)
  69869. */
  69870. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  69871. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69872. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69873. if (generateMipMaps === void 0) { generateMipMaps = false; }
  69874. if (invertY === void 0) { invertY = false; }
  69875. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69876. if (compression === void 0) { compression = null; }
  69877. var _this = _super.call(this, "", scene) || this;
  69878. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  69879. return _this;
  69880. }
  69881. /**
  69882. * Updates the raw cube texture.
  69883. * @param data defines the data to store
  69884. * @param format defines the data format
  69885. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  69886. * @param invertY defines if data must be stored with Y axis inverted
  69887. * @param compression defines the compression used (null by default)
  69888. * @param level defines which level of the texture to update
  69889. */
  69890. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  69891. if (compression === void 0) { compression = null; }
  69892. if (level === void 0) { level = 0; }
  69893. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  69894. };
  69895. /**
  69896. * Updates a raw cube texture with RGBD encoded data.
  69897. * @param data defines the array of data [mipmap][face] to use to create each face
  69898. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  69899. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  69900. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  69901. * @returns a promsie that resolves when the operation is complete
  69902. */
  69903. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  69904. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  69905. if (lodScale === void 0) { lodScale = 0.8; }
  69906. if (lodOffset === void 0) { lodOffset = 0; }
  69907. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  69908. };
  69909. /**
  69910. * Clones the raw cube texture.
  69911. * @return a new cube texture
  69912. */
  69913. RawCubeTexture.prototype.clone = function () {
  69914. var _this = this;
  69915. return BABYLON.SerializationHelper.Clone(function () {
  69916. var scene = _this.getScene();
  69917. var internalTexture = _this._texture;
  69918. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  69919. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  69920. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  69921. }
  69922. return texture;
  69923. }, this);
  69924. };
  69925. /** @hidden */
  69926. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  69927. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  69928. internalTexture._bufferViewArrayArray = data;
  69929. internalTexture._lodGenerationScale = lodScale;
  69930. internalTexture._lodGenerationOffset = lodOffset;
  69931. internalTexture._sphericalPolynomial = sphericalPolynomial;
  69932. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  69933. internalTexture.isReady = true;
  69934. });
  69935. };
  69936. return RawCubeTexture;
  69937. }(BABYLON.CubeTexture));
  69938. BABYLON.RawCubeTexture = RawCubeTexture;
  69939. })(BABYLON || (BABYLON = {}));
  69940. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  69941. var BABYLON;
  69942. (function (BABYLON) {
  69943. var RenderTargetTexture = /** @class */ (function (_super) {
  69944. __extends(RenderTargetTexture, _super);
  69945. /**
  69946. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  69947. * or used a shadow, depth texture...
  69948. * @param name The friendly name of the texture
  69949. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  69950. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  69951. * @param generateMipMaps True if mip maps need to be generated after render.
  69952. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  69953. * @param type The type of the buffer in the RTT (int, half float, float...)
  69954. * @param isCube True if a cube texture needs to be created
  69955. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  69956. * @param generateDepthBuffer True to generate a depth buffer
  69957. * @param generateStencilBuffer True to generate a stencil buffer
  69958. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  69959. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  69960. */
  69961. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  69962. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  69963. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69964. if (isCube === void 0) { isCube = false; }
  69965. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69966. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  69967. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  69968. if (isMulti === void 0) { isMulti = false; }
  69969. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69970. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69971. _this.isCube = isCube;
  69972. _this.renderParticles = true;
  69973. _this.renderSprites = false;
  69974. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  69975. _this.ignoreCameraViewport = false;
  69976. // Events
  69977. /**
  69978. * An event triggered when the texture is unbind.
  69979. */
  69980. _this.onBeforeBindObservable = new BABYLON.Observable();
  69981. /**
  69982. * An event triggered when the texture is unbind.
  69983. */
  69984. _this.onAfterUnbindObservable = new BABYLON.Observable();
  69985. /**
  69986. * An event triggered before rendering the texture
  69987. */
  69988. _this.onBeforeRenderObservable = new BABYLON.Observable();
  69989. /**
  69990. * An event triggered after rendering the texture
  69991. */
  69992. _this.onAfterRenderObservable = new BABYLON.Observable();
  69993. /**
  69994. * An event triggered after the texture clear
  69995. */
  69996. _this.onClearObservable = new BABYLON.Observable();
  69997. _this._currentRefreshId = -1;
  69998. _this._refreshRate = 1;
  69999. _this._samples = 1;
  70000. /**
  70001. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  70002. * It must define where the camera used to render the texture is set
  70003. */
  70004. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  70005. scene = _this.getScene();
  70006. if (!scene) {
  70007. return _this;
  70008. }
  70009. _this.renderList = new Array();
  70010. _this._engine = scene.getEngine();
  70011. _this.name = name;
  70012. _this.isRenderTarget = true;
  70013. _this._initialSizeParameter = size;
  70014. _this._processSizeParameter(size);
  70015. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  70016. });
  70017. _this._generateMipMaps = generateMipMaps ? true : false;
  70018. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  70019. // Rendering groups
  70020. _this._renderingManager = new BABYLON.RenderingManager(scene);
  70021. _this._renderingManager._useSceneAutoClearSetup = true;
  70022. if (isMulti) {
  70023. return _this;
  70024. }
  70025. _this._renderTargetOptions = {
  70026. generateMipMaps: generateMipMaps,
  70027. type: type,
  70028. format: format,
  70029. samplingMode: samplingMode,
  70030. generateDepthBuffer: generateDepthBuffer,
  70031. generateStencilBuffer: generateStencilBuffer
  70032. };
  70033. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  70034. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70035. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70036. }
  70037. if (isCube) {
  70038. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  70039. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  70040. _this._textureMatrix = BABYLON.Matrix.Identity();
  70041. }
  70042. else {
  70043. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  70044. }
  70045. return _this;
  70046. }
  70047. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  70048. get: function () {
  70049. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  70050. },
  70051. enumerable: true,
  70052. configurable: true
  70053. });
  70054. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  70055. get: function () {
  70056. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  70057. },
  70058. enumerable: true,
  70059. configurable: true
  70060. });
  70061. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  70062. get: function () {
  70063. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  70064. },
  70065. enumerable: true,
  70066. configurable: true
  70067. });
  70068. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  70069. /**
  70070. * Use this list to define the list of mesh you want to render.
  70071. */
  70072. get: function () {
  70073. return this._renderList;
  70074. },
  70075. set: function (value) {
  70076. this._renderList = value;
  70077. if (this._renderList) {
  70078. this._hookArray(this._renderList);
  70079. }
  70080. },
  70081. enumerable: true,
  70082. configurable: true
  70083. });
  70084. RenderTargetTexture.prototype._hookArray = function (array) {
  70085. var _this = this;
  70086. var oldPush = array.push;
  70087. array.push = function () {
  70088. var items = [];
  70089. for (var _i = 0; _i < arguments.length; _i++) {
  70090. items[_i] = arguments[_i];
  70091. }
  70092. var result = oldPush.apply(array, items);
  70093. _this.getScene().meshes.forEach(function (mesh) {
  70094. mesh._markSubMeshesAsLightDirty();
  70095. });
  70096. return result;
  70097. };
  70098. var oldSplice = array.splice;
  70099. array.splice = function (index, deleteCount) {
  70100. var deleted = oldSplice.apply(array, [index, deleteCount]);
  70101. _this.getScene().meshes.forEach(function (mesh) {
  70102. mesh._markSubMeshesAsLightDirty();
  70103. });
  70104. return deleted;
  70105. };
  70106. };
  70107. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  70108. set: function (callback) {
  70109. if (this._onAfterUnbindObserver) {
  70110. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  70111. }
  70112. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  70113. },
  70114. enumerable: true,
  70115. configurable: true
  70116. });
  70117. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  70118. set: function (callback) {
  70119. if (this._onBeforeRenderObserver) {
  70120. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  70121. }
  70122. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  70123. },
  70124. enumerable: true,
  70125. configurable: true
  70126. });
  70127. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  70128. set: function (callback) {
  70129. if (this._onAfterRenderObserver) {
  70130. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  70131. }
  70132. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  70133. },
  70134. enumerable: true,
  70135. configurable: true
  70136. });
  70137. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  70138. set: function (callback) {
  70139. if (this._onClearObserver) {
  70140. this.onClearObservable.remove(this._onClearObserver);
  70141. }
  70142. this._onClearObserver = this.onClearObservable.add(callback);
  70143. },
  70144. enumerable: true,
  70145. configurable: true
  70146. });
  70147. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  70148. get: function () {
  70149. return this._renderTargetOptions;
  70150. },
  70151. enumerable: true,
  70152. configurable: true
  70153. });
  70154. RenderTargetTexture.prototype._onRatioRescale = function () {
  70155. if (this._sizeRatio) {
  70156. this.resize(this._initialSizeParameter);
  70157. }
  70158. };
  70159. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  70160. get: function () {
  70161. return this._boundingBoxSize;
  70162. },
  70163. /**
  70164. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  70165. * When defined, the cubemap will switch to local mode
  70166. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  70167. * @example https://www.babylonjs-playground.com/#RNASML
  70168. */
  70169. set: function (value) {
  70170. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  70171. return;
  70172. }
  70173. this._boundingBoxSize = value;
  70174. var scene = this.getScene();
  70175. if (scene) {
  70176. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  70177. }
  70178. },
  70179. enumerable: true,
  70180. configurable: true
  70181. });
  70182. /**
  70183. * Creates a depth stencil texture.
  70184. * This is only available in WebGL 2 or with the depth texture extension available.
  70185. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  70186. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  70187. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  70188. */
  70189. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  70190. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  70191. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  70192. if (generateStencil === void 0) { generateStencil = false; }
  70193. if (!this.getScene()) {
  70194. return;
  70195. }
  70196. var engine = this.getScene().getEngine();
  70197. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  70198. bilinearFiltering: bilinearFiltering,
  70199. comparisonFunction: comparisonFunction,
  70200. generateStencil: generateStencil,
  70201. isCube: this.isCube
  70202. });
  70203. engine.setFrameBufferDepthStencilTexture(this);
  70204. };
  70205. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  70206. if (size.ratio) {
  70207. this._sizeRatio = size.ratio;
  70208. this._size = {
  70209. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  70210. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  70211. };
  70212. }
  70213. else {
  70214. this._size = size;
  70215. }
  70216. };
  70217. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  70218. get: function () {
  70219. return this._samples;
  70220. },
  70221. set: function (value) {
  70222. if (this._samples === value) {
  70223. return;
  70224. }
  70225. var scene = this.getScene();
  70226. if (!scene) {
  70227. return;
  70228. }
  70229. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  70230. },
  70231. enumerable: true,
  70232. configurable: true
  70233. });
  70234. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  70235. this._currentRefreshId = -1;
  70236. };
  70237. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  70238. get: function () {
  70239. return this._refreshRate;
  70240. },
  70241. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70242. set: function (value) {
  70243. this._refreshRate = value;
  70244. this.resetRefreshCounter();
  70245. },
  70246. enumerable: true,
  70247. configurable: true
  70248. });
  70249. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  70250. if (!this._postProcessManager) {
  70251. var scene = this.getScene();
  70252. if (!scene) {
  70253. return;
  70254. }
  70255. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  70256. this._postProcesses = new Array();
  70257. }
  70258. this._postProcesses.push(postProcess);
  70259. this._postProcesses[0].autoClear = false;
  70260. };
  70261. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  70262. if (!this._postProcesses) {
  70263. return;
  70264. }
  70265. if (dispose) {
  70266. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  70267. var postProcess = _a[_i];
  70268. postProcess.dispose();
  70269. }
  70270. }
  70271. this._postProcesses = [];
  70272. };
  70273. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  70274. if (!this._postProcesses) {
  70275. return;
  70276. }
  70277. var index = this._postProcesses.indexOf(postProcess);
  70278. if (index === -1) {
  70279. return;
  70280. }
  70281. this._postProcesses.splice(index, 1);
  70282. if (this._postProcesses.length > 0) {
  70283. this._postProcesses[0].autoClear = false;
  70284. }
  70285. };
  70286. /** @hidden */
  70287. RenderTargetTexture.prototype._shouldRender = function () {
  70288. if (this._currentRefreshId === -1) { // At least render once
  70289. this._currentRefreshId = 1;
  70290. return true;
  70291. }
  70292. if (this.refreshRate === this._currentRefreshId) {
  70293. this._currentRefreshId = 1;
  70294. return true;
  70295. }
  70296. this._currentRefreshId++;
  70297. return false;
  70298. };
  70299. RenderTargetTexture.prototype.getRenderSize = function () {
  70300. if (this._size.width) {
  70301. return this._size.width;
  70302. }
  70303. return this._size;
  70304. };
  70305. RenderTargetTexture.prototype.getRenderWidth = function () {
  70306. if (this._size.width) {
  70307. return this._size.width;
  70308. }
  70309. return this._size;
  70310. };
  70311. RenderTargetTexture.prototype.getRenderHeight = function () {
  70312. if (this._size.width) {
  70313. return this._size.height;
  70314. }
  70315. return this._size;
  70316. };
  70317. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  70318. get: function () {
  70319. return true;
  70320. },
  70321. enumerable: true,
  70322. configurable: true
  70323. });
  70324. RenderTargetTexture.prototype.scale = function (ratio) {
  70325. var newSize = this.getRenderSize() * ratio;
  70326. this.resize(newSize);
  70327. };
  70328. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  70329. if (this.isCube) {
  70330. return this._textureMatrix;
  70331. }
  70332. return _super.prototype.getReflectionTextureMatrix.call(this);
  70333. };
  70334. RenderTargetTexture.prototype.resize = function (size) {
  70335. this.releaseInternalTexture();
  70336. var scene = this.getScene();
  70337. if (!scene) {
  70338. return;
  70339. }
  70340. this._processSizeParameter(size);
  70341. if (this.isCube) {
  70342. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  70343. }
  70344. else {
  70345. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  70346. }
  70347. };
  70348. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  70349. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  70350. if (dumpForDebug === void 0) { dumpForDebug = false; }
  70351. var scene = this.getScene();
  70352. if (!scene) {
  70353. return;
  70354. }
  70355. var engine = scene.getEngine();
  70356. if (this.useCameraPostProcesses !== undefined) {
  70357. useCameraPostProcess = this.useCameraPostProcesses;
  70358. }
  70359. if (this._waitingRenderList) {
  70360. this.renderList = [];
  70361. for (var index = 0; index < this._waitingRenderList.length; index++) {
  70362. var id = this._waitingRenderList[index];
  70363. var mesh_1 = scene.getMeshByID(id);
  70364. if (mesh_1) {
  70365. this.renderList.push(mesh_1);
  70366. }
  70367. }
  70368. delete this._waitingRenderList;
  70369. }
  70370. // Is predicate defined?
  70371. if (this.renderListPredicate) {
  70372. if (this.renderList) {
  70373. this.renderList.splice(0); // Clear previous renderList
  70374. }
  70375. else {
  70376. this.renderList = [];
  70377. }
  70378. var scene = this.getScene();
  70379. if (!scene) {
  70380. return;
  70381. }
  70382. var sceneMeshes = scene.meshes;
  70383. for (var index = 0; index < sceneMeshes.length; index++) {
  70384. var mesh = sceneMeshes[index];
  70385. if (this.renderListPredicate(mesh)) {
  70386. this.renderList.push(mesh);
  70387. }
  70388. }
  70389. }
  70390. this.onBeforeBindObservable.notifyObservers(this);
  70391. // Set custom projection.
  70392. // Needs to be before binding to prevent changing the aspect ratio.
  70393. var camera;
  70394. if (this.activeCamera) {
  70395. camera = this.activeCamera;
  70396. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  70397. if (this.activeCamera !== scene.activeCamera) {
  70398. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  70399. }
  70400. }
  70401. else {
  70402. camera = scene.activeCamera;
  70403. if (camera) {
  70404. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  70405. }
  70406. }
  70407. // Prepare renderingManager
  70408. this._renderingManager.reset();
  70409. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  70410. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  70411. var sceneRenderId = scene.getRenderId();
  70412. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  70413. var mesh = currentRenderList[meshIndex];
  70414. if (mesh) {
  70415. if (!mesh.isReady(this.refreshRate === 0)) {
  70416. this.resetRefreshCounter();
  70417. continue;
  70418. }
  70419. mesh._preActivateForIntermediateRendering(sceneRenderId);
  70420. var isMasked = void 0;
  70421. if (!this.renderList && camera) {
  70422. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  70423. }
  70424. else {
  70425. isMasked = false;
  70426. }
  70427. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  70428. mesh._activate(sceneRenderId);
  70429. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  70430. var subMesh = mesh.subMeshes[subIndex];
  70431. scene._activeIndices.addCount(subMesh.indexCount, false);
  70432. this._renderingManager.dispatch(subMesh, mesh);
  70433. }
  70434. }
  70435. }
  70436. }
  70437. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  70438. var particleSystem = scene.particleSystems[particleIndex];
  70439. var emitter = particleSystem.emitter;
  70440. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  70441. continue;
  70442. }
  70443. if (currentRenderList.indexOf(emitter) >= 0) {
  70444. this._renderingManager.dispatchParticles(particleSystem);
  70445. }
  70446. }
  70447. if (this.isCube) {
  70448. for (var face = 0; face < 6; face++) {
  70449. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  70450. scene.incrementRenderId();
  70451. scene.resetCachedMaterial();
  70452. }
  70453. }
  70454. else {
  70455. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  70456. }
  70457. this.onAfterUnbindObservable.notifyObservers(this);
  70458. if (scene.activeCamera) {
  70459. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  70460. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  70461. }
  70462. engine.setViewport(scene.activeCamera.viewport);
  70463. }
  70464. scene.resetCachedMaterial();
  70465. };
  70466. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  70467. var minimum = 128;
  70468. var x = renderDimension * scale;
  70469. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  70470. // Ensure we don't exceed the render dimension (while staying POT)
  70471. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  70472. };
  70473. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  70474. var _this = this;
  70475. if (!this._texture) {
  70476. return;
  70477. }
  70478. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  70479. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  70480. });
  70481. };
  70482. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  70483. var scene = this.getScene();
  70484. if (!scene) {
  70485. return;
  70486. }
  70487. var engine = scene.getEngine();
  70488. if (!this._texture) {
  70489. return;
  70490. }
  70491. // Bind
  70492. if (this._postProcessManager) {
  70493. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  70494. }
  70495. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  70496. if (this._texture) {
  70497. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  70498. }
  70499. }
  70500. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  70501. // Clear
  70502. if (this.onClearObservable.hasObservers()) {
  70503. this.onClearObservable.notifyObservers(engine);
  70504. }
  70505. else {
  70506. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  70507. }
  70508. if (!this._doNotChangeAspectRatio) {
  70509. scene.updateTransformMatrix(true);
  70510. }
  70511. // Render
  70512. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  70513. if (this._postProcessManager) {
  70514. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  70515. }
  70516. else if (useCameraPostProcess) {
  70517. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  70518. }
  70519. if (!this._doNotChangeAspectRatio) {
  70520. scene.updateTransformMatrix(true);
  70521. }
  70522. // Dump ?
  70523. if (dumpForDebug) {
  70524. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  70525. }
  70526. // Unbind
  70527. if (!this.isCube || faceIndex === 5) {
  70528. if (this.isCube) {
  70529. if (faceIndex === 5) {
  70530. engine.generateMipMapsForCubemap(this._texture);
  70531. }
  70532. }
  70533. this.unbindFrameBuffer(engine, faceIndex);
  70534. }
  70535. else {
  70536. this.onAfterRenderObservable.notifyObservers(faceIndex);
  70537. }
  70538. };
  70539. /**
  70540. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  70541. * This allowed control for front to back rendering or reversly depending of the special needs.
  70542. *
  70543. * @param renderingGroupId The rendering group id corresponding to its index
  70544. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  70545. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  70546. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  70547. */
  70548. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  70549. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  70550. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  70551. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  70552. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  70553. };
  70554. /**
  70555. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  70556. *
  70557. * @param renderingGroupId The rendering group id corresponding to its index
  70558. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  70559. */
  70560. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  70561. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  70562. this._renderingManager._useSceneAutoClearSetup = false;
  70563. };
  70564. RenderTargetTexture.prototype.clone = function () {
  70565. var textureSize = this.getSize();
  70566. 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);
  70567. // Base texture
  70568. newTexture.hasAlpha = this.hasAlpha;
  70569. newTexture.level = this.level;
  70570. // RenderTarget Texture
  70571. newTexture.coordinatesMode = this.coordinatesMode;
  70572. if (this.renderList) {
  70573. newTexture.renderList = this.renderList.slice(0);
  70574. }
  70575. return newTexture;
  70576. };
  70577. RenderTargetTexture.prototype.serialize = function () {
  70578. if (!this.name) {
  70579. return null;
  70580. }
  70581. var serializationObject = _super.prototype.serialize.call(this);
  70582. serializationObject.renderTargetSize = this.getRenderSize();
  70583. serializationObject.renderList = [];
  70584. if (this.renderList) {
  70585. for (var index = 0; index < this.renderList.length; index++) {
  70586. serializationObject.renderList.push(this.renderList[index].id);
  70587. }
  70588. }
  70589. return serializationObject;
  70590. };
  70591. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  70592. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  70593. var objBuffer = this.getInternalTexture();
  70594. var scene = this.getScene();
  70595. if (objBuffer && scene) {
  70596. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  70597. }
  70598. };
  70599. RenderTargetTexture.prototype.dispose = function () {
  70600. if (this._postProcessManager) {
  70601. this._postProcessManager.dispose();
  70602. this._postProcessManager = null;
  70603. }
  70604. this.clearPostProcesses(true);
  70605. if (this._resizeObserver) {
  70606. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  70607. this._resizeObserver = null;
  70608. }
  70609. this.renderList = null;
  70610. // Remove from custom render targets
  70611. var scene = this.getScene();
  70612. if (!scene) {
  70613. return;
  70614. }
  70615. var index = scene.customRenderTargets.indexOf(this);
  70616. if (index >= 0) {
  70617. scene.customRenderTargets.splice(index, 1);
  70618. }
  70619. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  70620. var camera = _a[_i];
  70621. index = camera.customRenderTargets.indexOf(this);
  70622. if (index >= 0) {
  70623. camera.customRenderTargets.splice(index, 1);
  70624. }
  70625. }
  70626. _super.prototype.dispose.call(this);
  70627. };
  70628. /** @hidden */
  70629. RenderTargetTexture.prototype._rebuild = function () {
  70630. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70631. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70632. }
  70633. if (this._postProcessManager) {
  70634. this._postProcessManager._rebuild();
  70635. }
  70636. };
  70637. /**
  70638. * Clear the info related to rendering groups preventing retention point in material dispose.
  70639. */
  70640. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  70641. if (this._renderingManager) {
  70642. this._renderingManager.freeRenderingGroups();
  70643. }
  70644. };
  70645. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  70646. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  70647. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  70648. return RenderTargetTexture;
  70649. }(BABYLON.Texture));
  70650. BABYLON.RenderTargetTexture = RenderTargetTexture;
  70651. })(BABYLON || (BABYLON = {}));
  70652. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  70653. var BABYLON;
  70654. (function (BABYLON) {
  70655. ;
  70656. var MultiRenderTarget = /** @class */ (function (_super) {
  70657. __extends(MultiRenderTarget, _super);
  70658. function MultiRenderTarget(name, size, count, scene, options) {
  70659. var _this = this;
  70660. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  70661. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  70662. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  70663. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  70664. _this._engine = scene.getEngine();
  70665. if (!_this.isSupported) {
  70666. _this.dispose();
  70667. return;
  70668. }
  70669. var types = [];
  70670. var samplingModes = [];
  70671. for (var i = 0; i < count; i++) {
  70672. if (options && options.types && options.types[i] !== undefined) {
  70673. types.push(options.types[i]);
  70674. }
  70675. else {
  70676. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70677. }
  70678. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  70679. samplingModes.push(options.samplingModes[i]);
  70680. }
  70681. else {
  70682. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70683. }
  70684. }
  70685. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  70686. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  70687. _this._size = size;
  70688. _this._multiRenderTargetOptions = {
  70689. samplingModes: samplingModes,
  70690. generateMipMaps: generateMipMaps,
  70691. generateDepthBuffer: generateDepthBuffer,
  70692. generateStencilBuffer: generateStencilBuffer,
  70693. generateDepthTexture: generateDepthTexture,
  70694. types: types,
  70695. textureCount: count
  70696. };
  70697. _this._createInternalTextures();
  70698. _this._createTextures();
  70699. return _this;
  70700. }
  70701. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  70702. get: function () {
  70703. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  70704. },
  70705. enumerable: true,
  70706. configurable: true
  70707. });
  70708. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  70709. get: function () {
  70710. return this._textures;
  70711. },
  70712. enumerable: true,
  70713. configurable: true
  70714. });
  70715. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  70716. get: function () {
  70717. return this._textures[this._textures.length - 1];
  70718. },
  70719. enumerable: true,
  70720. configurable: true
  70721. });
  70722. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  70723. set: function (wrap) {
  70724. if (this._textures) {
  70725. for (var i = 0; i < this._textures.length; i++) {
  70726. this._textures[i].wrapU = wrap;
  70727. }
  70728. }
  70729. },
  70730. enumerable: true,
  70731. configurable: true
  70732. });
  70733. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  70734. set: function (wrap) {
  70735. if (this._textures) {
  70736. for (var i = 0; i < this._textures.length; i++) {
  70737. this._textures[i].wrapV = wrap;
  70738. }
  70739. }
  70740. },
  70741. enumerable: true,
  70742. configurable: true
  70743. });
  70744. /** @hidden */
  70745. MultiRenderTarget.prototype._rebuild = function () {
  70746. this.releaseInternalTextures();
  70747. this._createInternalTextures();
  70748. for (var i = 0; i < this._internalTextures.length; i++) {
  70749. var texture = this._textures[i];
  70750. texture._texture = this._internalTextures[i];
  70751. }
  70752. // Keeps references to frame buffer and stencil/depth buffer
  70753. this._texture = this._internalTextures[0];
  70754. };
  70755. MultiRenderTarget.prototype._createInternalTextures = function () {
  70756. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  70757. };
  70758. MultiRenderTarget.prototype._createTextures = function () {
  70759. this._textures = [];
  70760. for (var i = 0; i < this._internalTextures.length; i++) {
  70761. var texture = new BABYLON.Texture(null, this.getScene());
  70762. texture._texture = this._internalTextures[i];
  70763. this._textures.push(texture);
  70764. }
  70765. // Keeps references to frame buffer and stencil/depth buffer
  70766. this._texture = this._internalTextures[0];
  70767. };
  70768. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  70769. get: function () {
  70770. return this._samples;
  70771. },
  70772. set: function (value) {
  70773. if (this._samples === value) {
  70774. return;
  70775. }
  70776. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  70777. },
  70778. enumerable: true,
  70779. configurable: true
  70780. });
  70781. MultiRenderTarget.prototype.resize = function (size) {
  70782. this.releaseInternalTextures();
  70783. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  70784. this._createInternalTextures();
  70785. };
  70786. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  70787. var _this = this;
  70788. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  70789. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  70790. });
  70791. };
  70792. MultiRenderTarget.prototype.dispose = function () {
  70793. this.releaseInternalTextures();
  70794. _super.prototype.dispose.call(this);
  70795. };
  70796. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  70797. if (!this._internalTextures) {
  70798. return;
  70799. }
  70800. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  70801. if (this._internalTextures[i] !== undefined) {
  70802. this._internalTextures[i].dispose();
  70803. this._internalTextures.splice(i, 1);
  70804. }
  70805. }
  70806. };
  70807. return MultiRenderTarget;
  70808. }(BABYLON.RenderTargetTexture));
  70809. BABYLON.MultiRenderTarget = MultiRenderTarget;
  70810. })(BABYLON || (BABYLON = {}));
  70811. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  70812. var BABYLON;
  70813. (function (BABYLON) {
  70814. var MirrorTexture = /** @class */ (function (_super) {
  70815. __extends(MirrorTexture, _super);
  70816. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  70817. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70818. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70819. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  70820. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  70821. _this.scene = scene;
  70822. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  70823. _this._transformMatrix = BABYLON.Matrix.Zero();
  70824. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  70825. _this._adaptiveBlurKernel = 0;
  70826. _this._blurKernelX = 0;
  70827. _this._blurKernelY = 0;
  70828. _this._blurRatio = 1.0;
  70829. _this.ignoreCameraViewport = true;
  70830. _this._updateGammaSpace();
  70831. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  70832. _this._updateGammaSpace;
  70833. });
  70834. _this.onBeforeRenderObservable.add(function () {
  70835. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  70836. _this._savedViewMatrix = scene.getViewMatrix();
  70837. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  70838. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  70839. scene.clipPlane = _this.mirrorPlane;
  70840. scene.getEngine().cullBackFaces = false;
  70841. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  70842. });
  70843. _this.onAfterRenderObservable.add(function () {
  70844. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  70845. scene.getEngine().cullBackFaces = true;
  70846. scene._mirroredCameraPosition = null;
  70847. delete scene.clipPlane;
  70848. });
  70849. return _this;
  70850. }
  70851. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  70852. get: function () {
  70853. return this._blurRatio;
  70854. },
  70855. set: function (value) {
  70856. if (this._blurRatio === value) {
  70857. return;
  70858. }
  70859. this._blurRatio = value;
  70860. this._preparePostProcesses();
  70861. },
  70862. enumerable: true,
  70863. configurable: true
  70864. });
  70865. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  70866. set: function (value) {
  70867. this._adaptiveBlurKernel = value;
  70868. this._autoComputeBlurKernel();
  70869. },
  70870. enumerable: true,
  70871. configurable: true
  70872. });
  70873. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  70874. set: function (value) {
  70875. this.blurKernelX = value;
  70876. this.blurKernelY = value;
  70877. },
  70878. enumerable: true,
  70879. configurable: true
  70880. });
  70881. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  70882. get: function () {
  70883. return this._blurKernelX;
  70884. },
  70885. set: function (value) {
  70886. if (this._blurKernelX === value) {
  70887. return;
  70888. }
  70889. this._blurKernelX = value;
  70890. this._preparePostProcesses();
  70891. },
  70892. enumerable: true,
  70893. configurable: true
  70894. });
  70895. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  70896. get: function () {
  70897. return this._blurKernelY;
  70898. },
  70899. set: function (value) {
  70900. if (this._blurKernelY === value) {
  70901. return;
  70902. }
  70903. this._blurKernelY = value;
  70904. this._preparePostProcesses();
  70905. },
  70906. enumerable: true,
  70907. configurable: true
  70908. });
  70909. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  70910. var engine = this.getScene().getEngine();
  70911. var dw = this.getRenderWidth() / engine.getRenderWidth();
  70912. var dh = this.getRenderHeight() / engine.getRenderHeight();
  70913. this.blurKernelX = this._adaptiveBlurKernel * dw;
  70914. this.blurKernelY = this._adaptiveBlurKernel * dh;
  70915. };
  70916. MirrorTexture.prototype._onRatioRescale = function () {
  70917. if (this._sizeRatio) {
  70918. this.resize(this._initialSizeParameter);
  70919. if (!this._adaptiveBlurKernel) {
  70920. this._preparePostProcesses();
  70921. }
  70922. }
  70923. if (this._adaptiveBlurKernel) {
  70924. this._autoComputeBlurKernel();
  70925. }
  70926. };
  70927. MirrorTexture.prototype._updateGammaSpace = function () {
  70928. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  70929. };
  70930. MirrorTexture.prototype._preparePostProcesses = function () {
  70931. this.clearPostProcesses(true);
  70932. if (this._blurKernelX && this._blurKernelY) {
  70933. var engine = this.getScene().getEngine();
  70934. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70935. 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);
  70936. this._blurX.autoClear = false;
  70937. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  70938. this._blurX.inputTexture = this._texture;
  70939. }
  70940. else {
  70941. this._blurX.alwaysForcePOT = true;
  70942. }
  70943. 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);
  70944. this._blurY.autoClear = false;
  70945. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  70946. this.addPostProcess(this._blurX);
  70947. this.addPostProcess(this._blurY);
  70948. }
  70949. else {
  70950. if (this._blurY) {
  70951. this.removePostProcess(this._blurY);
  70952. this._blurY.dispose();
  70953. this._blurY = null;
  70954. }
  70955. if (this._blurX) {
  70956. this.removePostProcess(this._blurX);
  70957. this._blurX.dispose();
  70958. this._blurX = null;
  70959. }
  70960. }
  70961. };
  70962. MirrorTexture.prototype.clone = function () {
  70963. var scene = this.getScene();
  70964. if (!scene) {
  70965. return this;
  70966. }
  70967. var textureSize = this.getSize();
  70968. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  70969. // Base texture
  70970. newTexture.hasAlpha = this.hasAlpha;
  70971. newTexture.level = this.level;
  70972. // Mirror Texture
  70973. newTexture.mirrorPlane = this.mirrorPlane.clone();
  70974. if (this.renderList) {
  70975. newTexture.renderList = this.renderList.slice(0);
  70976. }
  70977. return newTexture;
  70978. };
  70979. MirrorTexture.prototype.serialize = function () {
  70980. if (!this.name) {
  70981. return null;
  70982. }
  70983. var serializationObject = _super.prototype.serialize.call(this);
  70984. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  70985. return serializationObject;
  70986. };
  70987. MirrorTexture.prototype.dispose = function () {
  70988. _super.prototype.dispose.call(this);
  70989. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  70990. };
  70991. return MirrorTexture;
  70992. }(BABYLON.RenderTargetTexture));
  70993. BABYLON.MirrorTexture = MirrorTexture;
  70994. })(BABYLON || (BABYLON = {}));
  70995. //# sourceMappingURL=babylon.mirrorTexture.js.map
  70996. var BABYLON;
  70997. (function (BABYLON) {
  70998. /**
  70999. * Creates a refraction texture used by refraction channel of the standard material.
  71000. * @param name the texture name
  71001. * @param size size of the underlying texture
  71002. * @param scene root scene
  71003. */
  71004. var RefractionTexture = /** @class */ (function (_super) {
  71005. __extends(RefractionTexture, _super);
  71006. function RefractionTexture(name, size, scene, generateMipMaps) {
  71007. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  71008. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  71009. _this.depth = 2.0;
  71010. _this.onBeforeRenderObservable.add(function () {
  71011. scene.clipPlane = _this.refractionPlane;
  71012. });
  71013. _this.onAfterRenderObservable.add(function () {
  71014. delete scene.clipPlane;
  71015. });
  71016. return _this;
  71017. }
  71018. RefractionTexture.prototype.clone = function () {
  71019. var scene = this.getScene();
  71020. if (!scene) {
  71021. return this;
  71022. }
  71023. var textureSize = this.getSize();
  71024. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  71025. // Base texture
  71026. newTexture.hasAlpha = this.hasAlpha;
  71027. newTexture.level = this.level;
  71028. // Refraction Texture
  71029. newTexture.refractionPlane = this.refractionPlane.clone();
  71030. if (this.renderList) {
  71031. newTexture.renderList = this.renderList.slice(0);
  71032. }
  71033. newTexture.depth = this.depth;
  71034. return newTexture;
  71035. };
  71036. RefractionTexture.prototype.serialize = function () {
  71037. if (!this.name) {
  71038. return null;
  71039. }
  71040. var serializationObject = _super.prototype.serialize.call(this);
  71041. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  71042. serializationObject.depth = this.depth;
  71043. return serializationObject;
  71044. };
  71045. return RefractionTexture;
  71046. }(BABYLON.RenderTargetTexture));
  71047. BABYLON.RefractionTexture = RefractionTexture;
  71048. })(BABYLON || (BABYLON = {}));
  71049. //# sourceMappingURL=babylon.refractionTexture.js.map
  71050. var BABYLON;
  71051. (function (BABYLON) {
  71052. /**
  71053. * A class extending {BABYLON.Texture} allowing drawing on a texture
  71054. * @see http://doc.babylonjs.com/how_to/dynamictexture
  71055. */
  71056. var DynamicTexture = /** @class */ (function (_super) {
  71057. __extends(DynamicTexture, _super);
  71058. /**
  71059. * Creates a {BABYLON.DynamicTexture}
  71060. * @param name defines the name of the texture
  71061. * @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
  71062. * @param scene defines the scene where you want the texture
  71063. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  71064. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  71065. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  71066. */
  71067. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  71068. if (scene === void 0) { scene = null; }
  71069. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71070. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71071. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  71072. _this.name = name;
  71073. _this._engine = _this.getScene().getEngine();
  71074. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71075. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71076. _this._generateMipMaps = generateMipMaps;
  71077. if (options.getContext) {
  71078. _this._canvas = options;
  71079. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  71080. }
  71081. else {
  71082. _this._canvas = document.createElement("canvas");
  71083. if (options.width || options.width === 0) {
  71084. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  71085. }
  71086. else {
  71087. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  71088. }
  71089. }
  71090. var textureSize = _this.getSize();
  71091. _this._canvas.width = textureSize.width;
  71092. _this._canvas.height = textureSize.height;
  71093. _this._context = _this._canvas.getContext("2d");
  71094. return _this;
  71095. }
  71096. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  71097. /**
  71098. * Gets the current state of canRescale
  71099. */
  71100. get: function () {
  71101. return true;
  71102. },
  71103. enumerable: true,
  71104. configurable: true
  71105. });
  71106. DynamicTexture.prototype._recreate = function (textureSize) {
  71107. this._canvas.width = textureSize.width;
  71108. this._canvas.height = textureSize.height;
  71109. this.releaseInternalTexture();
  71110. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  71111. };
  71112. /**
  71113. * Scales the texture
  71114. * @param ratio the scale factor to apply to both width and height
  71115. */
  71116. DynamicTexture.prototype.scale = function (ratio) {
  71117. var textureSize = this.getSize();
  71118. textureSize.width *= ratio;
  71119. textureSize.height *= ratio;
  71120. this._recreate(textureSize);
  71121. };
  71122. /**
  71123. * Resizes the texture
  71124. * @param width the new width
  71125. * @param height the new height
  71126. */
  71127. DynamicTexture.prototype.scaleTo = function (width, height) {
  71128. var textureSize = this.getSize();
  71129. textureSize.width = width;
  71130. textureSize.height = height;
  71131. this._recreate(textureSize);
  71132. };
  71133. /**
  71134. * Gets the context of the canvas used by the texture
  71135. * @returns the canvas context of the dynamic texture
  71136. */
  71137. DynamicTexture.prototype.getContext = function () {
  71138. return this._context;
  71139. };
  71140. /**
  71141. * Clears the texture
  71142. */
  71143. DynamicTexture.prototype.clear = function () {
  71144. var size = this.getSize();
  71145. this._context.fillRect(0, 0, size.width, size.height);
  71146. };
  71147. /**
  71148. * Updates the texture
  71149. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  71150. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  71151. */
  71152. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  71153. if (premulAlpha === void 0) { premulAlpha = false; }
  71154. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  71155. };
  71156. /**
  71157. * Draws text onto the texture
  71158. * @param text defines the text to be drawn
  71159. * @param x defines the placement of the text from the left
  71160. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  71161. * @param font defines the font to be used with font-style, font-size, font-name
  71162. * @param color defines the color used for the text
  71163. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  71164. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  71165. * @param update defines whether texture is immediately update (default is true)
  71166. */
  71167. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  71168. if (update === void 0) { update = true; }
  71169. var size = this.getSize();
  71170. if (clearColor) {
  71171. this._context.fillStyle = clearColor;
  71172. this._context.fillRect(0, 0, size.width, size.height);
  71173. }
  71174. this._context.font = font;
  71175. if (x === null || x === undefined) {
  71176. var textSize = this._context.measureText(text);
  71177. x = (size.width - textSize.width) / 2;
  71178. }
  71179. if (y === null || y === undefined) {
  71180. var fontSize = parseInt((font.replace(/\D/g, '')));
  71181. y = (size.height / 2) + (fontSize / 3.65);
  71182. }
  71183. this._context.fillStyle = color;
  71184. this._context.fillText(text, x, y);
  71185. if (update) {
  71186. this.update(invertY);
  71187. }
  71188. };
  71189. /**
  71190. * Clones the texture
  71191. * @returns the clone of the texture.
  71192. */
  71193. DynamicTexture.prototype.clone = function () {
  71194. var scene = this.getScene();
  71195. if (!scene) {
  71196. return this;
  71197. }
  71198. var textureSize = this.getSize();
  71199. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  71200. // Base texture
  71201. newTexture.hasAlpha = this.hasAlpha;
  71202. newTexture.level = this.level;
  71203. // Dynamic Texture
  71204. newTexture.wrapU = this.wrapU;
  71205. newTexture.wrapV = this.wrapV;
  71206. return newTexture;
  71207. };
  71208. /**
  71209. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  71210. * @returns a serialized dynamic texture object
  71211. */
  71212. DynamicTexture.prototype.serialize = function () {
  71213. var scene = this.getScene();
  71214. if (scene && !scene.isReady()) {
  71215. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  71216. }
  71217. var serializationObject = _super.prototype.serialize.call(this);
  71218. serializationObject.base64String = this._canvas.toDataURL();
  71219. serializationObject.invertY = this._invertY;
  71220. serializationObject.samplingMode = this.samplingMode;
  71221. return serializationObject;
  71222. };
  71223. /** @hidden */
  71224. DynamicTexture.prototype._rebuild = function () {
  71225. this.update();
  71226. };
  71227. return DynamicTexture;
  71228. }(BABYLON.Texture));
  71229. BABYLON.DynamicTexture = DynamicTexture;
  71230. })(BABYLON || (BABYLON = {}));
  71231. //# sourceMappingURL=babylon.dynamicTexture.js.map
  71232. var BABYLON;
  71233. (function (BABYLON) {
  71234. var VideoTexture = /** @class */ (function (_super) {
  71235. __extends(VideoTexture, _super);
  71236. /**
  71237. * Creates a video texture.
  71238. * Sample : https://doc.babylonjs.com/how_to/video_texture
  71239. * @param {string | null} name optional name, will detect from video source, if not defined
  71240. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  71241. * @param {BABYLON.Scene} scene is obviously the current scene.
  71242. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  71243. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  71244. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  71245. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  71246. */
  71247. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  71248. if (generateMipMaps === void 0) { generateMipMaps = false; }
  71249. if (invertY === void 0) { invertY = false; }
  71250. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71251. if (settings === void 0) { settings = {
  71252. autoPlay: true,
  71253. loop: true,
  71254. autoUpdateTexture: true,
  71255. }; }
  71256. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  71257. _this._onUserActionRequestedObservable = null;
  71258. _this._stillImageCaptured = false;
  71259. _this._poster = false;
  71260. _this._createInternalTexture = function () {
  71261. if (_this._texture != null) {
  71262. if (_this._poster) {
  71263. _this._texture.dispose();
  71264. _this._poster = false;
  71265. }
  71266. else {
  71267. return;
  71268. }
  71269. }
  71270. if (!_this._engine.needPOTTextures ||
  71271. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  71272. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  71273. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  71274. }
  71275. else {
  71276. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71277. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71278. _this._generateMipMaps = false;
  71279. }
  71280. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  71281. if (!_this.video.autoplay) {
  71282. var oldHandler_1 = _this.video.onplaying;
  71283. var error_1 = false;
  71284. _this.video.onplaying = function () {
  71285. _this.video.onplaying = oldHandler_1;
  71286. _this._texture.isReady = true;
  71287. _this._updateInternalTexture();
  71288. if (!error_1) {
  71289. _this.video.pause();
  71290. }
  71291. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  71292. _this.onLoadObservable.notifyObservers(_this);
  71293. }
  71294. };
  71295. var playing = _this.video.play();
  71296. if (playing) {
  71297. playing.then(function () {
  71298. // Everything is good.
  71299. })
  71300. .catch(function () {
  71301. error_1 = true;
  71302. // On Chrome for instance, new policies might prevent playing without user interaction.
  71303. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  71304. _this._onUserActionRequestedObservable.notifyObservers(_this);
  71305. }
  71306. });
  71307. }
  71308. else {
  71309. _this.video.onplaying = oldHandler_1;
  71310. _this._texture.isReady = true;
  71311. _this._updateInternalTexture();
  71312. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  71313. _this.onLoadObservable.notifyObservers(_this);
  71314. }
  71315. }
  71316. }
  71317. else {
  71318. _this._texture.isReady = true;
  71319. _this._updateInternalTexture();
  71320. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  71321. _this.onLoadObservable.notifyObservers(_this);
  71322. }
  71323. }
  71324. };
  71325. _this.reset = function () {
  71326. if (_this._texture == null) {
  71327. return;
  71328. }
  71329. if (!_this._poster) {
  71330. _this._texture.dispose();
  71331. _this._texture = null;
  71332. }
  71333. };
  71334. _this._updateInternalTexture = function (e) {
  71335. if (_this._texture == null || !_this._texture.isReady) {
  71336. return;
  71337. }
  71338. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  71339. return;
  71340. }
  71341. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  71342. };
  71343. _this._engine = _this.getScene().getEngine();
  71344. _this._generateMipMaps = generateMipMaps;
  71345. _this._samplingMode = samplingMode;
  71346. _this.autoUpdateTexture = settings.autoUpdateTexture;
  71347. _this.name = name || _this._getName(src);
  71348. _this.video = _this._getVideo(src);
  71349. if (settings.poster) {
  71350. _this.video.poster = settings.poster;
  71351. }
  71352. if (settings.autoPlay !== undefined) {
  71353. _this.video.autoplay = settings.autoPlay;
  71354. }
  71355. if (settings.loop !== undefined) {
  71356. _this.video.loop = settings.loop;
  71357. }
  71358. _this.video.setAttribute("playsinline", "");
  71359. _this.video.addEventListener("canplay", _this._createInternalTexture);
  71360. _this.video.addEventListener("paused", _this._updateInternalTexture);
  71361. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  71362. _this.video.addEventListener("emptied", _this.reset);
  71363. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  71364. _this._createInternalTexture();
  71365. }
  71366. if (settings.poster) {
  71367. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  71368. _this._poster = true;
  71369. }
  71370. return _this;
  71371. }
  71372. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  71373. get: function () {
  71374. if (!this._onUserActionRequestedObservable) {
  71375. this._onUserActionRequestedObservable = new BABYLON.Observable();
  71376. }
  71377. return this._onUserActionRequestedObservable;
  71378. },
  71379. enumerable: true,
  71380. configurable: true
  71381. });
  71382. VideoTexture.prototype._getName = function (src) {
  71383. if (src instanceof HTMLVideoElement) {
  71384. return src.currentSrc;
  71385. }
  71386. if (typeof src === "object") {
  71387. return src.toString();
  71388. }
  71389. return src;
  71390. };
  71391. ;
  71392. VideoTexture.prototype._getVideo = function (src) {
  71393. if (src instanceof HTMLVideoElement) {
  71394. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  71395. return src;
  71396. }
  71397. var video = document.createElement("video");
  71398. if (typeof src === "string") {
  71399. BABYLON.Tools.SetCorsBehavior(src, video);
  71400. video.src = src;
  71401. }
  71402. else {
  71403. BABYLON.Tools.SetCorsBehavior(src[0], video);
  71404. src.forEach(function (url) {
  71405. var source = document.createElement("source");
  71406. source.src = url;
  71407. video.appendChild(source);
  71408. });
  71409. }
  71410. return video;
  71411. };
  71412. ;
  71413. /**
  71414. * @hidden Internal method to initiate `update`.
  71415. */
  71416. VideoTexture.prototype._rebuild = function () {
  71417. this.update();
  71418. };
  71419. /**
  71420. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  71421. */
  71422. VideoTexture.prototype.update = function () {
  71423. if (!this.autoUpdateTexture) {
  71424. // Expecting user to call `updateTexture` manually
  71425. return;
  71426. }
  71427. this.updateTexture(true);
  71428. };
  71429. /**
  71430. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  71431. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  71432. */
  71433. VideoTexture.prototype.updateTexture = function (isVisible) {
  71434. if (!isVisible) {
  71435. return;
  71436. }
  71437. if (this.video.paused && this._stillImageCaptured) {
  71438. return;
  71439. }
  71440. this._stillImageCaptured = true;
  71441. this._updateInternalTexture();
  71442. };
  71443. /**
  71444. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  71445. * @param url New url.
  71446. */
  71447. VideoTexture.prototype.updateURL = function (url) {
  71448. this.video.src = url;
  71449. };
  71450. VideoTexture.prototype.dispose = function () {
  71451. _super.prototype.dispose.call(this);
  71452. if (this._onUserActionRequestedObservable) {
  71453. this._onUserActionRequestedObservable.clear();
  71454. this._onUserActionRequestedObservable = null;
  71455. }
  71456. this.video.removeEventListener("canplay", this._createInternalTexture);
  71457. this.video.removeEventListener("paused", this._updateInternalTexture);
  71458. this.video.removeEventListener("seeked", this._updateInternalTexture);
  71459. this.video.removeEventListener("emptied", this.reset);
  71460. this.video.pause();
  71461. };
  71462. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  71463. var video = document.createElement("video");
  71464. video.setAttribute('autoplay', '');
  71465. video.setAttribute('muted', '');
  71466. video.setAttribute('playsinline', '');
  71467. var constraintsDeviceId;
  71468. if (constraints && constraints.deviceId) {
  71469. constraintsDeviceId = {
  71470. exact: constraints.deviceId,
  71471. };
  71472. }
  71473. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  71474. if (navigator.mediaDevices) {
  71475. navigator.mediaDevices.getUserMedia({ video: constraints })
  71476. .then(function (stream) {
  71477. if (video.mozSrcObject !== undefined) {
  71478. // hack for Firefox < 19
  71479. video.mozSrcObject = stream;
  71480. }
  71481. else {
  71482. video.srcObject = stream;
  71483. }
  71484. var onPlaying = function () {
  71485. if (onReady) {
  71486. onReady(new VideoTexture("video", video, scene, true, true));
  71487. }
  71488. video.removeEventListener("playing", onPlaying);
  71489. };
  71490. video.addEventListener("playing", onPlaying);
  71491. video.play();
  71492. })
  71493. .catch(function (err) {
  71494. BABYLON.Tools.Error(err.name);
  71495. });
  71496. }
  71497. else {
  71498. navigator.getUserMedia =
  71499. navigator.getUserMedia ||
  71500. navigator.webkitGetUserMedia ||
  71501. navigator.mozGetUserMedia ||
  71502. navigator.msGetUserMedia;
  71503. if (navigator.getUserMedia) {
  71504. navigator.getUserMedia({
  71505. video: {
  71506. deviceId: constraintsDeviceId,
  71507. width: {
  71508. min: (constraints && constraints.minWidth) || 256,
  71509. max: (constraints && constraints.maxWidth) || 640,
  71510. },
  71511. height: {
  71512. min: (constraints && constraints.minHeight) || 256,
  71513. max: (constraints && constraints.maxHeight) || 480,
  71514. },
  71515. },
  71516. }, function (stream) {
  71517. if (video.mozSrcObject !== undefined) {
  71518. // hack for Firefox < 19
  71519. video.mozSrcObject = stream;
  71520. }
  71521. else {
  71522. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  71523. }
  71524. video.play();
  71525. if (onReady) {
  71526. onReady(new VideoTexture("video", video, scene, true, true));
  71527. }
  71528. }, function (e) {
  71529. BABYLON.Tools.Error(e.name);
  71530. });
  71531. }
  71532. }
  71533. };
  71534. return VideoTexture;
  71535. }(BABYLON.Texture));
  71536. BABYLON.VideoTexture = VideoTexture;
  71537. })(BABYLON || (BABYLON = {}));
  71538. //# sourceMappingURL=babylon.videoTexture.js.map
  71539. var BABYLON;
  71540. (function (BABYLON) {
  71541. var RawTexture = /** @class */ (function (_super) {
  71542. __extends(RawTexture, _super);
  71543. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  71544. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71545. if (invertY === void 0) { invertY = false; }
  71546. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71547. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71548. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  71549. _this.format = format;
  71550. _this._engine = scene.getEngine();
  71551. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  71552. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71553. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71554. return _this;
  71555. }
  71556. RawTexture.prototype.update = function (data) {
  71557. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  71558. };
  71559. // Statics
  71560. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  71561. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71562. if (invertY === void 0) { invertY = false; }
  71563. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71564. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  71565. };
  71566. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  71567. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71568. if (invertY === void 0) { invertY = false; }
  71569. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71570. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  71571. };
  71572. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  71573. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71574. if (invertY === void 0) { invertY = false; }
  71575. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71576. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  71577. };
  71578. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  71579. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71580. if (invertY === void 0) { invertY = false; }
  71581. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71582. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71583. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  71584. };
  71585. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  71586. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71587. if (invertY === void 0) { invertY = false; }
  71588. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71589. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71590. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  71591. };
  71592. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  71593. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71594. if (invertY === void 0) { invertY = false; }
  71595. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71596. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  71597. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  71598. };
  71599. return RawTexture;
  71600. }(BABYLON.Texture));
  71601. BABYLON.RawTexture = RawTexture;
  71602. })(BABYLON || (BABYLON = {}));
  71603. //# sourceMappingURL=babylon.rawTexture.js.map
  71604. var BABYLON;
  71605. (function (BABYLON) {
  71606. /**
  71607. * Class used to store 3D textures containing user data
  71608. */
  71609. var RawTexture3D = /** @class */ (function (_super) {
  71610. __extends(RawTexture3D, _super);
  71611. /**
  71612. * Create a new RawTexture3D
  71613. * @param data defines the data of the texture
  71614. * @param width defines the width of the texture
  71615. * @param height defines the height of the texture
  71616. * @param depth defines the depth of the texture
  71617. * @param format defines the texture format to use
  71618. * @param scene defines the hosting scene
  71619. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  71620. * @param invertY defines if texture must be stored with Y axis inverted
  71621. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  71622. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  71623. */
  71624. function RawTexture3D(data, width, height, depth,
  71625. /** Gets or sets the texture format to use */
  71626. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  71627. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71628. if (invertY === void 0) { invertY = false; }
  71629. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71630. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71631. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  71632. _this.format = format;
  71633. _this._engine = scene.getEngine();
  71634. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  71635. _this.is3D = true;
  71636. return _this;
  71637. }
  71638. /**
  71639. * Update the texture with new data
  71640. * @param data defines the data to store in the texture
  71641. */
  71642. RawTexture3D.prototype.update = function (data) {
  71643. if (!this._texture) {
  71644. return;
  71645. }
  71646. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  71647. };
  71648. return RawTexture3D;
  71649. }(BABYLON.Texture));
  71650. BABYLON.RawTexture3D = RawTexture3D;
  71651. })(BABYLON || (BABYLON = {}));
  71652. //# sourceMappingURL=babylon.rawTexture3D.js.map
  71653. var BABYLON;
  71654. (function (BABYLON) {
  71655. /**
  71656. * PostProcessManager is used to manage one or more post processes or post process pipelines
  71657. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  71658. */
  71659. var PostProcessManager = /** @class */ (function () {
  71660. /**
  71661. * Creates a new instance PostProcess
  71662. * @param scene The scene that the post process is associated with.
  71663. */
  71664. function PostProcessManager(scene) {
  71665. this._vertexBuffers = {};
  71666. this._scene = scene;
  71667. }
  71668. PostProcessManager.prototype._prepareBuffers = function () {
  71669. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  71670. return;
  71671. }
  71672. // VBO
  71673. var vertices = [];
  71674. vertices.push(1, 1);
  71675. vertices.push(-1, 1);
  71676. vertices.push(-1, -1);
  71677. vertices.push(1, -1);
  71678. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71679. this._buildIndexBuffer();
  71680. };
  71681. PostProcessManager.prototype._buildIndexBuffer = function () {
  71682. // Indices
  71683. var indices = [];
  71684. indices.push(0);
  71685. indices.push(1);
  71686. indices.push(2);
  71687. indices.push(0);
  71688. indices.push(2);
  71689. indices.push(3);
  71690. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  71691. };
  71692. /**
  71693. * Rebuilds the vertex buffers of the manager.
  71694. * @hidden
  71695. */
  71696. PostProcessManager.prototype._rebuild = function () {
  71697. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71698. if (!vb) {
  71699. return;
  71700. }
  71701. vb._rebuild();
  71702. this._buildIndexBuffer();
  71703. };
  71704. // Methods
  71705. /**
  71706. * Prepares a frame to be run through a post process.
  71707. * @param sourceTexture The input texture to the post procesess. (default: null)
  71708. * @param postProcesses An array of post processes to be run. (default: null)
  71709. * @returns True if the post processes were able to be run.
  71710. * @hidden
  71711. */
  71712. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  71713. if (sourceTexture === void 0) { sourceTexture = null; }
  71714. if (postProcesses === void 0) { postProcesses = null; }
  71715. var camera = this._scene.activeCamera;
  71716. if (!camera) {
  71717. return false;
  71718. }
  71719. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  71720. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  71721. return false;
  71722. }
  71723. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  71724. return true;
  71725. };
  71726. /**
  71727. * Manually render a set of post processes to a texture.
  71728. * @param postProcesses An array of post processes to be run.
  71729. * @param targetTexture The target texture to render to.
  71730. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  71731. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  71732. * @param lodLevel defines which lod of the texture to render to
  71733. */
  71734. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  71735. if (targetTexture === void 0) { targetTexture = null; }
  71736. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  71737. if (faceIndex === void 0) { faceIndex = 0; }
  71738. if (lodLevel === void 0) { lodLevel = 0; }
  71739. var engine = this._scene.getEngine();
  71740. for (var index = 0; index < postProcesses.length; index++) {
  71741. if (index < postProcesses.length - 1) {
  71742. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  71743. }
  71744. else {
  71745. if (targetTexture) {
  71746. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  71747. }
  71748. else {
  71749. engine.restoreDefaultFramebuffer();
  71750. }
  71751. }
  71752. var pp = postProcesses[index];
  71753. var effect = pp.apply();
  71754. if (effect) {
  71755. pp.onBeforeRenderObservable.notifyObservers(effect);
  71756. // VBOs
  71757. this._prepareBuffers();
  71758. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  71759. // Draw order
  71760. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71761. pp.onAfterRenderObservable.notifyObservers(effect);
  71762. }
  71763. }
  71764. // Restore depth buffer
  71765. engine.setDepthBuffer(true);
  71766. engine.setDepthWrite(true);
  71767. };
  71768. /**
  71769. * Finalize the result of the output of the postprocesses.
  71770. * @param doNotPresent If true the result will not be displayed to the screen.
  71771. * @param targetTexture The target texture to render to.
  71772. * @param faceIndex The index of the face to bind the target texture to.
  71773. * @param postProcesses The array of post processes to render.
  71774. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  71775. * @hidden
  71776. */
  71777. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  71778. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  71779. var camera = this._scene.activeCamera;
  71780. if (!camera) {
  71781. return;
  71782. }
  71783. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  71784. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  71785. return;
  71786. }
  71787. var engine = this._scene.getEngine();
  71788. for (var index = 0, len = postProcesses.length; index < len; index++) {
  71789. var pp = postProcesses[index];
  71790. if (index < len - 1) {
  71791. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  71792. }
  71793. else {
  71794. if (targetTexture) {
  71795. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  71796. pp._outputTexture = targetTexture;
  71797. }
  71798. else {
  71799. engine.restoreDefaultFramebuffer();
  71800. pp._outputTexture = null;
  71801. }
  71802. }
  71803. if (doNotPresent) {
  71804. break;
  71805. }
  71806. var effect = pp.apply();
  71807. if (effect) {
  71808. pp.onBeforeRenderObservable.notifyObservers(effect);
  71809. // VBOs
  71810. this._prepareBuffers();
  71811. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  71812. // Draw order
  71813. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71814. pp.onAfterRenderObservable.notifyObservers(effect);
  71815. }
  71816. }
  71817. // Restore states
  71818. engine.setDepthBuffer(true);
  71819. engine.setDepthWrite(true);
  71820. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71821. };
  71822. /**
  71823. * Disposes of the post process manager.
  71824. */
  71825. PostProcessManager.prototype.dispose = function () {
  71826. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71827. if (buffer) {
  71828. buffer.dispose();
  71829. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71830. }
  71831. if (this._indexBuffer) {
  71832. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71833. this._indexBuffer = null;
  71834. }
  71835. };
  71836. return PostProcessManager;
  71837. }());
  71838. BABYLON.PostProcessManager = PostProcessManager;
  71839. })(BABYLON || (BABYLON = {}));
  71840. //# sourceMappingURL=babylon.postProcessManager.js.map
  71841. var BABYLON;
  71842. (function (BABYLON) {
  71843. /**
  71844. * PostProcess can be used to apply a shader to a texture after it has been rendered
  71845. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  71846. */
  71847. var PostProcess = /** @class */ (function () {
  71848. /**
  71849. * Creates a new instance PostProcess
  71850. * @param name The name of the PostProcess.
  71851. * @param fragmentUrl The url of the fragment shader to be used.
  71852. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  71853. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  71854. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  71855. * @param camera The camera to apply the render pass to.
  71856. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71857. * @param engine The engine which the post process will be applied. (default: current engine)
  71858. * @param reusable If the post process can be reused on the same frame. (default: false)
  71859. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  71860. * @param textureType Type of textures used when performing the post process. (default: 0)
  71861. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  71862. * @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
  71863. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  71864. */
  71865. function PostProcess(
  71866. /** Name of the PostProcess. */
  71867. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  71868. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  71869. if (defines === void 0) { defines = null; }
  71870. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71871. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  71872. if (blockCompilation === void 0) { blockCompilation = false; }
  71873. this.name = name;
  71874. /**
  71875. * Width of the texture to apply the post process on
  71876. */
  71877. this.width = -1;
  71878. /**
  71879. * Height of the texture to apply the post process on
  71880. */
  71881. this.height = -1;
  71882. /**
  71883. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  71884. * @hidden
  71885. */
  71886. this._outputTexture = null;
  71887. /**
  71888. * If the buffer needs to be cleared before applying the post process. (default: true)
  71889. * Should be set to false if shader will overwrite all previous pixels.
  71890. */
  71891. this.autoClear = true;
  71892. /**
  71893. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  71894. */
  71895. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  71896. /**
  71897. * Animations to be used for the post processing
  71898. */
  71899. this.animations = new Array();
  71900. /**
  71901. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  71902. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  71903. */
  71904. this.enablePixelPerfectMode = false;
  71905. /**
  71906. * Force the postprocess to be applied without taking in account viewport
  71907. */
  71908. this.forceFullscreenViewport = true;
  71909. /**
  71910. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  71911. *
  71912. * | Value | Type | Description |
  71913. * | ----- | ----------------------------------- | ----------- |
  71914. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  71915. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  71916. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  71917. *
  71918. */
  71919. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  71920. /**
  71921. * Force textures to be a power of two (default: false)
  71922. */
  71923. this.alwaysForcePOT = false;
  71924. this._samples = 1;
  71925. /**
  71926. * Modify the scale of the post process to be the same as the viewport (default: false)
  71927. */
  71928. this.adaptScaleToCurrentViewport = false;
  71929. this._reusable = false;
  71930. /**
  71931. * Smart array of input and output textures for the post process.
  71932. * @hidden
  71933. */
  71934. this._textures = new BABYLON.SmartArray(2);
  71935. /**
  71936. * The index in _textures that corresponds to the output texture.
  71937. * @hidden
  71938. */
  71939. this._currentRenderTextureInd = 0;
  71940. this._scaleRatio = new BABYLON.Vector2(1, 1);
  71941. this._texelSize = BABYLON.Vector2.Zero();
  71942. // Events
  71943. /**
  71944. * An event triggered when the postprocess is activated.
  71945. */
  71946. this.onActivateObservable = new BABYLON.Observable();
  71947. /**
  71948. * An event triggered when the postprocess changes its size.
  71949. */
  71950. this.onSizeChangedObservable = new BABYLON.Observable();
  71951. /**
  71952. * An event triggered when the postprocess applies its effect.
  71953. */
  71954. this.onApplyObservable = new BABYLON.Observable();
  71955. /**
  71956. * An event triggered before rendering the postprocess
  71957. */
  71958. this.onBeforeRenderObservable = new BABYLON.Observable();
  71959. /**
  71960. * An event triggered after rendering the postprocess
  71961. */
  71962. this.onAfterRenderObservable = new BABYLON.Observable();
  71963. if (camera != null) {
  71964. this._camera = camera;
  71965. this._scene = camera.getScene();
  71966. camera.attachPostProcess(this);
  71967. this._engine = this._scene.getEngine();
  71968. this._scene.postProcesses.push(this);
  71969. }
  71970. else if (engine) {
  71971. this._engine = engine;
  71972. this._engine.postProcesses.push(this);
  71973. }
  71974. this._options = options;
  71975. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  71976. this._reusable = reusable || false;
  71977. this._textureType = textureType;
  71978. this._samplers = samplers || [];
  71979. this._samplers.push("textureSampler");
  71980. this._fragmentUrl = fragmentUrl;
  71981. this._vertexUrl = vertexUrl;
  71982. this._parameters = parameters || [];
  71983. this._parameters.push("scale");
  71984. this._indexParameters = indexParameters;
  71985. if (!blockCompilation) {
  71986. this.updateEffect(defines);
  71987. }
  71988. }
  71989. Object.defineProperty(PostProcess.prototype, "samples", {
  71990. /**
  71991. * Number of sample textures (default: 1)
  71992. */
  71993. get: function () {
  71994. return this._samples;
  71995. },
  71996. set: function (n) {
  71997. var _this = this;
  71998. this._samples = n;
  71999. this._textures.forEach(function (texture) {
  72000. if (texture.samples !== _this._samples) {
  72001. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  72002. }
  72003. });
  72004. },
  72005. enumerable: true,
  72006. configurable: true
  72007. });
  72008. Object.defineProperty(PostProcess.prototype, "onActivate", {
  72009. /**
  72010. * A function that is added to the onActivateObservable
  72011. */
  72012. set: function (callback) {
  72013. if (this._onActivateObserver) {
  72014. this.onActivateObservable.remove(this._onActivateObserver);
  72015. }
  72016. if (callback) {
  72017. this._onActivateObserver = this.onActivateObservable.add(callback);
  72018. }
  72019. },
  72020. enumerable: true,
  72021. configurable: true
  72022. });
  72023. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  72024. /**
  72025. * A function that is added to the onSizeChangedObservable
  72026. */
  72027. set: function (callback) {
  72028. if (this._onSizeChangedObserver) {
  72029. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  72030. }
  72031. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  72032. },
  72033. enumerable: true,
  72034. configurable: true
  72035. });
  72036. Object.defineProperty(PostProcess.prototype, "onApply", {
  72037. /**
  72038. * A function that is added to the onApplyObservable
  72039. */
  72040. set: function (callback) {
  72041. if (this._onApplyObserver) {
  72042. this.onApplyObservable.remove(this._onApplyObserver);
  72043. }
  72044. this._onApplyObserver = this.onApplyObservable.add(callback);
  72045. },
  72046. enumerable: true,
  72047. configurable: true
  72048. });
  72049. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  72050. /**
  72051. * A function that is added to the onBeforeRenderObservable
  72052. */
  72053. set: function (callback) {
  72054. if (this._onBeforeRenderObserver) {
  72055. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  72056. }
  72057. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  72058. },
  72059. enumerable: true,
  72060. configurable: true
  72061. });
  72062. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  72063. /**
  72064. * A function that is added to the onAfterRenderObservable
  72065. */
  72066. set: function (callback) {
  72067. if (this._onAfterRenderObserver) {
  72068. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  72069. }
  72070. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  72071. },
  72072. enumerable: true,
  72073. configurable: true
  72074. });
  72075. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  72076. /**
  72077. * 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
  72078. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  72079. */
  72080. get: function () {
  72081. return this._textures.data[this._currentRenderTextureInd];
  72082. },
  72083. set: function (value) {
  72084. this._forcedOutputTexture = value;
  72085. },
  72086. enumerable: true,
  72087. configurable: true
  72088. });
  72089. /**
  72090. * Gets the camera which post process is applied to.
  72091. * @returns The camera the post process is applied to.
  72092. */
  72093. PostProcess.prototype.getCamera = function () {
  72094. return this._camera;
  72095. };
  72096. Object.defineProperty(PostProcess.prototype, "texelSize", {
  72097. /**
  72098. * Gets the texel size of the postprocess.
  72099. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  72100. */
  72101. get: function () {
  72102. if (this._shareOutputWithPostProcess) {
  72103. return this._shareOutputWithPostProcess.texelSize;
  72104. }
  72105. if (this._forcedOutputTexture) {
  72106. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  72107. }
  72108. return this._texelSize;
  72109. },
  72110. enumerable: true,
  72111. configurable: true
  72112. });
  72113. /**
  72114. * Gets the engine which this post process belongs to.
  72115. * @returns The engine the post process was enabled with.
  72116. */
  72117. PostProcess.prototype.getEngine = function () {
  72118. return this._engine;
  72119. };
  72120. /**
  72121. * The effect that is created when initializing the post process.
  72122. * @returns The created effect corrisponding the the postprocess.
  72123. */
  72124. PostProcess.prototype.getEffect = function () {
  72125. return this._effect;
  72126. };
  72127. /**
  72128. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  72129. * @param postProcess The post process to share the output with.
  72130. * @returns This post process.
  72131. */
  72132. PostProcess.prototype.shareOutputWith = function (postProcess) {
  72133. this._disposeTextures();
  72134. this._shareOutputWithPostProcess = postProcess;
  72135. return this;
  72136. };
  72137. /**
  72138. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  72139. * This should be called if the post process that shares output with this post process is disabled/disposed.
  72140. */
  72141. PostProcess.prototype.useOwnOutput = function () {
  72142. if (this._textures.length == 0) {
  72143. this._textures = new BABYLON.SmartArray(2);
  72144. }
  72145. this._shareOutputWithPostProcess = null;
  72146. };
  72147. /**
  72148. * Updates the effect with the current post process compile time values and recompiles the shader.
  72149. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  72150. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  72151. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  72152. * @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
  72153. * @param onCompiled Called when the shader has been compiled.
  72154. * @param onError Called if there is an error when compiling a shader.
  72155. */
  72156. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  72157. if (defines === void 0) { defines = null; }
  72158. if (uniforms === void 0) { uniforms = null; }
  72159. if (samplers === void 0) { samplers = null; }
  72160. 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);
  72161. };
  72162. /**
  72163. * The post process is reusable if it can be used multiple times within one frame.
  72164. * @returns If the post process is reusable
  72165. */
  72166. PostProcess.prototype.isReusable = function () {
  72167. return this._reusable;
  72168. };
  72169. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  72170. PostProcess.prototype.markTextureDirty = function () {
  72171. this.width = -1;
  72172. };
  72173. /**
  72174. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  72175. * 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.
  72176. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  72177. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  72178. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  72179. * @returns The target texture that was bound to be written to.
  72180. */
  72181. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  72182. var _this = this;
  72183. if (sourceTexture === void 0) { sourceTexture = null; }
  72184. camera = camera || this._camera;
  72185. var scene = camera.getScene();
  72186. var engine = scene.getEngine();
  72187. var maxSize = engine.getCaps().maxTextureSize;
  72188. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  72189. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  72190. // 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
  72191. var webVRCamera = camera.parent;
  72192. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  72193. requiredWidth /= 2;
  72194. }
  72195. var desiredWidth = (this._options.width || requiredWidth);
  72196. var desiredHeight = this._options.height || requiredHeight;
  72197. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  72198. if (this.adaptScaleToCurrentViewport) {
  72199. var currentViewport = engine.currentViewport;
  72200. if (currentViewport) {
  72201. desiredWidth *= currentViewport.width;
  72202. desiredHeight *= currentViewport.height;
  72203. }
  72204. }
  72205. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  72206. if (!this._options.width) {
  72207. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  72208. }
  72209. if (!this._options.height) {
  72210. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  72211. }
  72212. }
  72213. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  72214. if (this._textures.length > 0) {
  72215. for (var i = 0; i < this._textures.length; i++) {
  72216. this._engine._releaseTexture(this._textures.data[i]);
  72217. }
  72218. this._textures.reset();
  72219. }
  72220. this.width = desiredWidth;
  72221. this.height = desiredHeight;
  72222. var textureSize = { width: this.width, height: this.height };
  72223. var textureOptions = {
  72224. generateMipMaps: false,
  72225. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  72226. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  72227. samplingMode: this.renderTargetSamplingMode,
  72228. type: this._textureType
  72229. };
  72230. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  72231. if (this._reusable) {
  72232. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  72233. }
  72234. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  72235. this.onSizeChangedObservable.notifyObservers(this);
  72236. }
  72237. this._textures.forEach(function (texture) {
  72238. if (texture.samples !== _this.samples) {
  72239. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  72240. }
  72241. });
  72242. }
  72243. var target;
  72244. if (this._shareOutputWithPostProcess) {
  72245. target = this._shareOutputWithPostProcess.inputTexture;
  72246. }
  72247. else if (this._forcedOutputTexture) {
  72248. target = this._forcedOutputTexture;
  72249. this.width = this._forcedOutputTexture.width;
  72250. this.height = this._forcedOutputTexture.height;
  72251. }
  72252. else {
  72253. target = this.inputTexture;
  72254. }
  72255. // Bind the input of this post process to be used as the output of the previous post process.
  72256. if (this.enablePixelPerfectMode) {
  72257. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  72258. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  72259. }
  72260. else {
  72261. this._scaleRatio.copyFromFloats(1, 1);
  72262. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  72263. }
  72264. this.onActivateObservable.notifyObservers(camera);
  72265. // Clear
  72266. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  72267. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  72268. }
  72269. if (this._reusable) {
  72270. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  72271. }
  72272. return target;
  72273. };
  72274. Object.defineProperty(PostProcess.prototype, "isSupported", {
  72275. /**
  72276. * If the post process is supported.
  72277. */
  72278. get: function () {
  72279. return this._effect.isSupported;
  72280. },
  72281. enumerable: true,
  72282. configurable: true
  72283. });
  72284. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  72285. /**
  72286. * The aspect ratio of the output texture.
  72287. */
  72288. get: function () {
  72289. if (this._shareOutputWithPostProcess) {
  72290. return this._shareOutputWithPostProcess.aspectRatio;
  72291. }
  72292. if (this._forcedOutputTexture) {
  72293. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  72294. }
  72295. return this.width / this.height;
  72296. },
  72297. enumerable: true,
  72298. configurable: true
  72299. });
  72300. /**
  72301. * Get a value indicating if the post-process is ready to be used
  72302. * @returns true if the post-process is ready (shader is compiled)
  72303. */
  72304. PostProcess.prototype.isReady = function () {
  72305. return this._effect && this._effect.isReady();
  72306. };
  72307. /**
  72308. * Binds all textures and uniforms to the shader, this will be run on every pass.
  72309. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  72310. */
  72311. PostProcess.prototype.apply = function () {
  72312. // Check
  72313. if (!this._effect || !this._effect.isReady())
  72314. return null;
  72315. // States
  72316. this._engine.enableEffect(this._effect);
  72317. this._engine.setState(false);
  72318. this._engine.setDepthBuffer(false);
  72319. this._engine.setDepthWrite(false);
  72320. // Alpha
  72321. this._engine.setAlphaMode(this.alphaMode);
  72322. if (this.alphaConstants) {
  72323. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  72324. }
  72325. // Bind the output texture of the preivous post process as the input to this post process.
  72326. var source;
  72327. if (this._shareOutputWithPostProcess) {
  72328. source = this._shareOutputWithPostProcess.inputTexture;
  72329. }
  72330. else if (this._forcedOutputTexture) {
  72331. source = this._forcedOutputTexture;
  72332. }
  72333. else {
  72334. source = this.inputTexture;
  72335. }
  72336. this._effect._bindTexture("textureSampler", source);
  72337. // Parameters
  72338. this._effect.setVector2("scale", this._scaleRatio);
  72339. this.onApplyObservable.notifyObservers(this._effect);
  72340. return this._effect;
  72341. };
  72342. PostProcess.prototype._disposeTextures = function () {
  72343. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  72344. return;
  72345. }
  72346. if (this._textures.length > 0) {
  72347. for (var i = 0; i < this._textures.length; i++) {
  72348. this._engine._releaseTexture(this._textures.data[i]);
  72349. }
  72350. }
  72351. this._textures.dispose();
  72352. };
  72353. /**
  72354. * Disposes the post process.
  72355. * @param camera The camera to dispose the post process on.
  72356. */
  72357. PostProcess.prototype.dispose = function (camera) {
  72358. camera = camera || this._camera;
  72359. this._disposeTextures();
  72360. if (this._scene) {
  72361. var index_1 = this._scene.postProcesses.indexOf(this);
  72362. if (index_1 !== -1) {
  72363. this._scene.postProcesses.splice(index_1, 1);
  72364. }
  72365. }
  72366. else {
  72367. var index_2 = this._engine.postProcesses.indexOf(this);
  72368. if (index_2 !== -1) {
  72369. this._engine.postProcesses.splice(index_2, 1);
  72370. }
  72371. }
  72372. if (!camera) {
  72373. return;
  72374. }
  72375. camera.detachPostProcess(this);
  72376. var index = camera._postProcesses.indexOf(this);
  72377. if (index === 0 && camera._postProcesses.length > 0) {
  72378. var firstPostProcess = this._camera._getFirstPostProcess();
  72379. if (firstPostProcess) {
  72380. firstPostProcess.markTextureDirty();
  72381. }
  72382. }
  72383. this.onActivateObservable.clear();
  72384. this.onAfterRenderObservable.clear();
  72385. this.onApplyObservable.clear();
  72386. this.onBeforeRenderObservable.clear();
  72387. this.onSizeChangedObservable.clear();
  72388. };
  72389. return PostProcess;
  72390. }());
  72391. BABYLON.PostProcess = PostProcess;
  72392. })(BABYLON || (BABYLON = {}));
  72393. //# sourceMappingURL=babylon.postProcess.js.map
  72394. var BABYLON;
  72395. (function (BABYLON) {
  72396. var PassPostProcess = /** @class */ (function (_super) {
  72397. __extends(PassPostProcess, _super);
  72398. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72399. if (camera === void 0) { camera = null; }
  72400. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72401. if (blockCompilation === void 0) { blockCompilation = false; }
  72402. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  72403. }
  72404. return PassPostProcess;
  72405. }(BABYLON.PostProcess));
  72406. BABYLON.PassPostProcess = PassPostProcess;
  72407. })(BABYLON || (BABYLON = {}));
  72408. //# sourceMappingURL=babylon.passPostProcess.js.map
  72409. var __assign = (this && this.__assign) || function () {
  72410. __assign = Object.assign || function(t) {
  72411. for (var s, i = 1, n = arguments.length; i < n; i++) {
  72412. s = arguments[i];
  72413. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  72414. t[p] = s[p];
  72415. }
  72416. return t;
  72417. };
  72418. return __assign.apply(this, arguments);
  72419. };
  72420. var BABYLON;
  72421. (function (BABYLON) {
  72422. /**
  72423. * Default implementation IShadowGenerator.
  72424. * This is the main object responsible of generating shadows in the framework.
  72425. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  72426. */
  72427. var ShadowGenerator = /** @class */ (function () {
  72428. /**
  72429. * Creates a ShadowGenerator object.
  72430. * A ShadowGenerator is the required tool to use the shadows.
  72431. * Each light casting shadows needs to use its own ShadowGenerator.
  72432. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  72433. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  72434. * @param light The light object generating the shadows.
  72435. * @param useFullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
  72436. */
  72437. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  72438. this._bias = 0.00005;
  72439. this._normalBias = 0;
  72440. this._blurBoxOffset = 1;
  72441. this._blurScale = 2;
  72442. this._blurKernel = 1;
  72443. this._useKernelBlur = false;
  72444. this._filter = ShadowGenerator.FILTER_NONE;
  72445. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  72446. this._contactHardeningLightSizeUVRatio = 0.1;
  72447. this._darkness = 0;
  72448. this._transparencyShadow = false;
  72449. /**
  72450. * Controls the extent to which the shadows fade out at the edge of the frustum
  72451. * Used only by directionals and spots
  72452. */
  72453. this.frustumEdgeFalloff = 0;
  72454. /**
  72455. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  72456. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  72457. * It might on the other hand introduce peter panning.
  72458. */
  72459. this.forceBackFacesOnly = false;
  72460. this._lightDirection = BABYLON.Vector3.Zero();
  72461. this._viewMatrix = BABYLON.Matrix.Zero();
  72462. this._projectionMatrix = BABYLON.Matrix.Zero();
  72463. this._transformMatrix = BABYLON.Matrix.Zero();
  72464. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  72465. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  72466. this._currentFaceIndex = 0;
  72467. this._currentFaceIndexCache = 0;
  72468. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  72469. this._mapSize = mapSize;
  72470. this._light = light;
  72471. this._scene = light.getScene();
  72472. light._shadowGenerator = this;
  72473. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  72474. if (!component) {
  72475. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  72476. this._scene._addComponent(component);
  72477. }
  72478. // Texture type fallback from float to int if not supported.
  72479. var caps = this._scene.getEngine().getCaps();
  72480. if (!useFullFloatFirst) {
  72481. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  72482. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72483. }
  72484. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  72485. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72486. }
  72487. else {
  72488. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72489. }
  72490. }
  72491. else {
  72492. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  72493. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72494. }
  72495. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  72496. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72497. }
  72498. else {
  72499. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72500. }
  72501. }
  72502. this._initializeGenerator();
  72503. this._applyFilterValues();
  72504. }
  72505. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  72506. /**
  72507. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  72508. */
  72509. get: function () {
  72510. return this._bias;
  72511. },
  72512. /**
  72513. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  72514. */
  72515. set: function (bias) {
  72516. this._bias = bias;
  72517. },
  72518. enumerable: true,
  72519. configurable: true
  72520. });
  72521. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  72522. /**
  72523. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  72524. */
  72525. get: function () {
  72526. return this._normalBias;
  72527. },
  72528. /**
  72529. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  72530. */
  72531. set: function (normalBias) {
  72532. this._normalBias = normalBias;
  72533. },
  72534. enumerable: true,
  72535. configurable: true
  72536. });
  72537. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  72538. /**
  72539. * Gets the blur box offset: offset applied during the blur pass.
  72540. * Only usefull if useKernelBlur = false
  72541. */
  72542. get: function () {
  72543. return this._blurBoxOffset;
  72544. },
  72545. /**
  72546. * Sets the blur box offset: offset applied during the blur pass.
  72547. * Only usefull if useKernelBlur = false
  72548. */
  72549. set: function (value) {
  72550. if (this._blurBoxOffset === value) {
  72551. return;
  72552. }
  72553. this._blurBoxOffset = value;
  72554. this._disposeBlurPostProcesses();
  72555. },
  72556. enumerable: true,
  72557. configurable: true
  72558. });
  72559. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  72560. /**
  72561. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  72562. * 2 means half of the size.
  72563. */
  72564. get: function () {
  72565. return this._blurScale;
  72566. },
  72567. /**
  72568. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  72569. * 2 means half of the size.
  72570. */
  72571. set: function (value) {
  72572. if (this._blurScale === value) {
  72573. return;
  72574. }
  72575. this._blurScale = value;
  72576. this._disposeBlurPostProcesses();
  72577. },
  72578. enumerable: true,
  72579. configurable: true
  72580. });
  72581. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  72582. /**
  72583. * Gets the blur kernel: kernel size of the blur pass.
  72584. * Only usefull if useKernelBlur = true
  72585. */
  72586. get: function () {
  72587. return this._blurKernel;
  72588. },
  72589. /**
  72590. * Sets the blur kernel: kernel size of the blur pass.
  72591. * Only usefull if useKernelBlur = true
  72592. */
  72593. set: function (value) {
  72594. if (this._blurKernel === value) {
  72595. return;
  72596. }
  72597. this._blurKernel = value;
  72598. this._disposeBlurPostProcesses();
  72599. },
  72600. enumerable: true,
  72601. configurable: true
  72602. });
  72603. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  72604. /**
  72605. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  72606. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  72607. */
  72608. get: function () {
  72609. return this._useKernelBlur;
  72610. },
  72611. /**
  72612. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  72613. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  72614. */
  72615. set: function (value) {
  72616. if (this._useKernelBlur === value) {
  72617. return;
  72618. }
  72619. this._useKernelBlur = value;
  72620. this._disposeBlurPostProcesses();
  72621. },
  72622. enumerable: true,
  72623. configurable: true
  72624. });
  72625. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  72626. /**
  72627. * Gets the depth scale used in ESM mode.
  72628. */
  72629. get: function () {
  72630. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  72631. },
  72632. /**
  72633. * Sets the depth scale used in ESM mode.
  72634. * This can override the scale stored on the light.
  72635. */
  72636. set: function (value) {
  72637. this._depthScale = value;
  72638. },
  72639. enumerable: true,
  72640. configurable: true
  72641. });
  72642. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  72643. /**
  72644. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  72645. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  72646. */
  72647. get: function () {
  72648. return this._filter;
  72649. },
  72650. /**
  72651. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  72652. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  72653. */
  72654. set: function (value) {
  72655. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  72656. if (this._light.needCube()) {
  72657. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  72658. this.useExponentialShadowMap = true;
  72659. return;
  72660. }
  72661. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  72662. this.useCloseExponentialShadowMap = true;
  72663. return;
  72664. }
  72665. // PCF on cubemap would also be expensive
  72666. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  72667. this.usePoissonSampling = true;
  72668. return;
  72669. }
  72670. }
  72671. // Weblg1 fallback for PCF.
  72672. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  72673. if (this._scene.getEngine().webGLVersion === 1) {
  72674. this.usePoissonSampling = true;
  72675. return;
  72676. }
  72677. }
  72678. if (this._filter === value) {
  72679. return;
  72680. }
  72681. this._filter = value;
  72682. this._disposeBlurPostProcesses();
  72683. this._applyFilterValues();
  72684. this._light._markMeshesAsLightDirty();
  72685. },
  72686. enumerable: true,
  72687. configurable: true
  72688. });
  72689. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  72690. /**
  72691. * Gets if the current filter is set to Poisson Sampling.
  72692. */
  72693. get: function () {
  72694. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  72695. },
  72696. /**
  72697. * Sets the current filter to Poisson Sampling.
  72698. */
  72699. set: function (value) {
  72700. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  72701. return;
  72702. }
  72703. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  72704. },
  72705. enumerable: true,
  72706. configurable: true
  72707. });
  72708. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  72709. /**
  72710. * Gets if the current filter is set to VSM.
  72711. * DEPRECATED. Should use useExponentialShadowMap instead.
  72712. */
  72713. get: function () {
  72714. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  72715. return this.useExponentialShadowMap;
  72716. },
  72717. /**
  72718. * Sets the current filter is to VSM.
  72719. * DEPRECATED. Should use useExponentialShadowMap instead.
  72720. */
  72721. set: function (value) {
  72722. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  72723. this.useExponentialShadowMap = value;
  72724. },
  72725. enumerable: true,
  72726. configurable: true
  72727. });
  72728. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  72729. /**
  72730. * Gets if the current filter is set to blurred VSM.
  72731. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  72732. */
  72733. get: function () {
  72734. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  72735. return this.useBlurExponentialShadowMap;
  72736. },
  72737. /**
  72738. * Sets the current filter is to blurred VSM.
  72739. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  72740. */
  72741. set: function (value) {
  72742. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  72743. this.useBlurExponentialShadowMap = value;
  72744. },
  72745. enumerable: true,
  72746. configurable: true
  72747. });
  72748. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  72749. /**
  72750. * Gets if the current filter is set to ESM.
  72751. */
  72752. get: function () {
  72753. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  72754. },
  72755. /**
  72756. * Sets the current filter is to ESM.
  72757. */
  72758. set: function (value) {
  72759. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  72760. return;
  72761. }
  72762. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72763. },
  72764. enumerable: true,
  72765. configurable: true
  72766. });
  72767. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  72768. /**
  72769. * Gets if the current filter is set to filtered ESM.
  72770. */
  72771. get: function () {
  72772. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  72773. },
  72774. /**
  72775. * Gets if the current filter is set to filtered ESM.
  72776. */
  72777. set: function (value) {
  72778. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  72779. return;
  72780. }
  72781. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72782. },
  72783. enumerable: true,
  72784. configurable: true
  72785. });
  72786. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  72787. /**
  72788. * Gets if the current filter is set to "close ESM" (using the inverse of the
  72789. * exponential to prevent steep falloff artifacts).
  72790. */
  72791. get: function () {
  72792. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  72793. },
  72794. /**
  72795. * Sets the current filter to "close ESM" (using the inverse of the
  72796. * exponential to prevent steep falloff artifacts).
  72797. */
  72798. set: function (value) {
  72799. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  72800. return;
  72801. }
  72802. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72803. },
  72804. enumerable: true,
  72805. configurable: true
  72806. });
  72807. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  72808. /**
  72809. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  72810. * exponential to prevent steep falloff artifacts).
  72811. */
  72812. get: function () {
  72813. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  72814. },
  72815. /**
  72816. * Sets the current filter to filtered "close ESM" (using the inverse of the
  72817. * exponential to prevent steep falloff artifacts).
  72818. */
  72819. set: function (value) {
  72820. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  72821. return;
  72822. }
  72823. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72824. },
  72825. enumerable: true,
  72826. configurable: true
  72827. });
  72828. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  72829. /**
  72830. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  72831. */
  72832. get: function () {
  72833. return this.filter === ShadowGenerator.FILTER_PCF;
  72834. },
  72835. /**
  72836. * Sets the current filter to "PCF" (percentage closer filtering).
  72837. */
  72838. set: function (value) {
  72839. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  72840. return;
  72841. }
  72842. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  72843. },
  72844. enumerable: true,
  72845. configurable: true
  72846. });
  72847. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  72848. /**
  72849. * Gets the PCF or PCSS Quality.
  72850. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  72851. */
  72852. get: function () {
  72853. return this._filteringQuality;
  72854. },
  72855. /**
  72856. * Sets the PCF or PCSS Quality.
  72857. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  72858. */
  72859. set: function (filteringQuality) {
  72860. this._filteringQuality = filteringQuality;
  72861. },
  72862. enumerable: true,
  72863. configurable: true
  72864. });
  72865. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  72866. /**
  72867. * Gets if the current filter is set to "PCSS" (contact hardening).
  72868. */
  72869. get: function () {
  72870. return this.filter === ShadowGenerator.FILTER_PCSS;
  72871. },
  72872. /**
  72873. * Sets the current filter to "PCSS" (contact hardening).
  72874. */
  72875. set: function (value) {
  72876. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  72877. return;
  72878. }
  72879. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  72880. },
  72881. enumerable: true,
  72882. configurable: true
  72883. });
  72884. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  72885. /**
  72886. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  72887. * Using a ratio helps keeping shape stability independently of the map size.
  72888. *
  72889. * It does not account for the light projection as it was having too much
  72890. * instability during the light setup or during light position changes.
  72891. *
  72892. * Only valid if useContactHardeningShadow is true.
  72893. */
  72894. get: function () {
  72895. return this._contactHardeningLightSizeUVRatio;
  72896. },
  72897. /**
  72898. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  72899. * Using a ratio helps keeping shape stability independently of the map size.
  72900. *
  72901. * It does not account for the light projection as it was having too much
  72902. * instability during the light setup or during light position changes.
  72903. *
  72904. * Only valid if useContactHardeningShadow is true.
  72905. */
  72906. set: function (contactHardeningLightSizeUVRatio) {
  72907. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  72908. },
  72909. enumerable: true,
  72910. configurable: true
  72911. });
  72912. /**
  72913. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  72914. * 0 means strongest and 1 would means no shadow.
  72915. * @returns the darkness.
  72916. */
  72917. ShadowGenerator.prototype.getDarkness = function () {
  72918. return this._darkness;
  72919. };
  72920. /**
  72921. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  72922. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  72923. * @returns the shadow generator allowing fluent coding.
  72924. */
  72925. ShadowGenerator.prototype.setDarkness = function (darkness) {
  72926. if (darkness >= 1.0)
  72927. this._darkness = 1.0;
  72928. else if (darkness <= 0.0)
  72929. this._darkness = 0.0;
  72930. else
  72931. this._darkness = darkness;
  72932. return this;
  72933. };
  72934. /**
  72935. * Sets the ability to have transparent shadow (boolean).
  72936. * @param transparent True if transparent else False
  72937. * @returns the shadow generator allowing fluent coding
  72938. */
  72939. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  72940. this._transparencyShadow = transparent;
  72941. return this;
  72942. };
  72943. /**
  72944. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  72945. * @returns The render target texture if present otherwise, null
  72946. */
  72947. ShadowGenerator.prototype.getShadowMap = function () {
  72948. return this._shadowMap;
  72949. };
  72950. /**
  72951. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  72952. * @returns The render target texture if the shadow map is present otherwise, null
  72953. */
  72954. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  72955. if (this._shadowMap2) {
  72956. return this._shadowMap2;
  72957. }
  72958. return this._shadowMap;
  72959. };
  72960. /**
  72961. * Helper function to add a mesh and its descendants to the list of shadow casters.
  72962. * @param mesh Mesh to add
  72963. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  72964. * @returns the Shadow Generator itself
  72965. */
  72966. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  72967. if (includeDescendants === void 0) { includeDescendants = true; }
  72968. var _a;
  72969. if (!this._shadowMap) {
  72970. return this;
  72971. }
  72972. if (!this._shadowMap.renderList) {
  72973. this._shadowMap.renderList = [];
  72974. }
  72975. this._shadowMap.renderList.push(mesh);
  72976. if (includeDescendants) {
  72977. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  72978. }
  72979. return this;
  72980. };
  72981. /**
  72982. * Helper function to remove a mesh and its descendants from the list of shadow casters
  72983. * @param mesh Mesh to remove
  72984. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  72985. * @returns the Shadow Generator itself
  72986. */
  72987. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  72988. if (includeDescendants === void 0) { includeDescendants = true; }
  72989. if (!this._shadowMap || !this._shadowMap.renderList) {
  72990. return this;
  72991. }
  72992. var index = this._shadowMap.renderList.indexOf(mesh);
  72993. if (index !== -1) {
  72994. this._shadowMap.renderList.splice(index, 1);
  72995. }
  72996. if (includeDescendants) {
  72997. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  72998. var child = _a[_i];
  72999. this.removeShadowCaster(child);
  73000. }
  73001. }
  73002. return this;
  73003. };
  73004. /**
  73005. * Returns the associated light object.
  73006. * @returns the light generating the shadow
  73007. */
  73008. ShadowGenerator.prototype.getLight = function () {
  73009. return this._light;
  73010. };
  73011. ShadowGenerator.prototype._initializeGenerator = function () {
  73012. this._light._markMeshesAsLightDirty();
  73013. this._initializeShadowMap();
  73014. };
  73015. ShadowGenerator.prototype._initializeShadowMap = function () {
  73016. var _this = this;
  73017. // Render target
  73018. var engine = this._scene.getEngine();
  73019. if (engine.webGLVersion > 1) {
  73020. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  73021. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  73022. }
  73023. else {
  73024. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  73025. }
  73026. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73027. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73028. this._shadowMap.anisotropicFilteringLevel = 1;
  73029. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73030. this._shadowMap.renderParticles = false;
  73031. this._shadowMap.ignoreCameraViewport = true;
  73032. // Record Face Index before render.
  73033. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  73034. _this._currentFaceIndex = faceIndex;
  73035. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  73036. engine.setColorWrite(false);
  73037. }
  73038. });
  73039. // Custom render function.
  73040. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  73041. // Blur if required afer render.
  73042. this._shadowMap.onAfterUnbindObservable.add(function () {
  73043. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  73044. engine.setColorWrite(true);
  73045. }
  73046. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  73047. return;
  73048. }
  73049. var shadowMap = _this.getShadowMapForRendering();
  73050. if (shadowMap) {
  73051. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  73052. }
  73053. });
  73054. // Clear according to the chosen filter.
  73055. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  73056. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  73057. this._shadowMap.onClearObservable.add(function (engine) {
  73058. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  73059. engine.clear(clearOne, false, true, false);
  73060. }
  73061. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  73062. engine.clear(clearZero, true, true, false);
  73063. }
  73064. else {
  73065. engine.clear(clearOne, true, true, false);
  73066. }
  73067. });
  73068. };
  73069. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  73070. var _this = this;
  73071. var engine = this._scene.getEngine();
  73072. var targetSize = this._mapSize / this.blurScale;
  73073. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  73074. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  73075. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73076. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73077. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73078. }
  73079. if (this.useKernelBlur) {
  73080. 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);
  73081. this._kernelBlurXPostprocess.width = targetSize;
  73082. this._kernelBlurXPostprocess.height = targetSize;
  73083. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  73084. effect.setTexture("textureSampler", _this._shadowMap);
  73085. });
  73086. 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);
  73087. this._kernelBlurXPostprocess.autoClear = false;
  73088. this._kernelBlurYPostprocess.autoClear = false;
  73089. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73090. this._kernelBlurXPostprocess.packedFloat = true;
  73091. this._kernelBlurYPostprocess.packedFloat = true;
  73092. }
  73093. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  73094. }
  73095. else {
  73096. 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);
  73097. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  73098. effect.setFloat2("screenSize", targetSize, targetSize);
  73099. effect.setTexture("textureSampler", _this._shadowMap);
  73100. });
  73101. this._boxBlurPostprocess.autoClear = false;
  73102. this._blurPostProcesses = [this._boxBlurPostprocess];
  73103. }
  73104. };
  73105. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73106. var index;
  73107. var engine = this._scene.getEngine();
  73108. if (depthOnlySubMeshes.length) {
  73109. engine.setColorWrite(false);
  73110. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73111. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  73112. }
  73113. engine.setColorWrite(true);
  73114. }
  73115. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73116. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  73117. }
  73118. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73119. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  73120. }
  73121. if (this._transparencyShadow) {
  73122. for (index = 0; index < transparentSubMeshes.length; index++) {
  73123. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  73124. }
  73125. }
  73126. };
  73127. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  73128. var _this = this;
  73129. var mesh = subMesh.getRenderingMesh();
  73130. var scene = this._scene;
  73131. var engine = scene.getEngine();
  73132. var material = subMesh.getMaterial();
  73133. if (!material) {
  73134. return;
  73135. }
  73136. // Culling
  73137. engine.setState(material.backFaceCulling);
  73138. // Managing instances
  73139. var batch = mesh._getInstancesRenderList(subMesh._id);
  73140. if (batch.mustReturn) {
  73141. return;
  73142. }
  73143. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  73144. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  73145. engine.enableEffect(this._effect);
  73146. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  73147. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  73148. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  73149. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  73150. this._effect.setVector3("lightData", this._cachedDirection);
  73151. }
  73152. else {
  73153. this._effect.setVector3("lightData", this._cachedPosition);
  73154. }
  73155. if (scene.activeCamera) {
  73156. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  73157. }
  73158. // Alpha test
  73159. if (material && material.needAlphaTesting()) {
  73160. var alphaTexture = material.getAlphaTestTexture();
  73161. if (alphaTexture) {
  73162. this._effect.setTexture("diffuseSampler", alphaTexture);
  73163. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  73164. }
  73165. }
  73166. // Bones
  73167. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73168. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  73169. }
  73170. // Morph targets
  73171. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  73172. if (this.forceBackFacesOnly) {
  73173. engine.setState(true, 0, false, true);
  73174. }
  73175. // Draw
  73176. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73177. if (this.forceBackFacesOnly) {
  73178. engine.setState(true, 0, false, false);
  73179. }
  73180. }
  73181. else {
  73182. // Need to reset refresh rate of the shadowMap
  73183. if (this._shadowMap) {
  73184. this._shadowMap.resetRefreshCounter();
  73185. }
  73186. }
  73187. };
  73188. ShadowGenerator.prototype._applyFilterValues = function () {
  73189. if (!this._shadowMap) {
  73190. return;
  73191. }
  73192. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  73193. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  73194. }
  73195. else {
  73196. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73197. }
  73198. };
  73199. /**
  73200. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  73201. * @param onCompiled Callback triggered at the and of the effects compilation
  73202. * @param options Sets of optional options forcing the compilation with different modes
  73203. */
  73204. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  73205. var _this = this;
  73206. var localOptions = __assign({ useInstances: false }, options);
  73207. var shadowMap = this.getShadowMap();
  73208. if (!shadowMap) {
  73209. if (onCompiled) {
  73210. onCompiled(this);
  73211. }
  73212. return;
  73213. }
  73214. var renderList = shadowMap.renderList;
  73215. if (!renderList) {
  73216. if (onCompiled) {
  73217. onCompiled(this);
  73218. }
  73219. return;
  73220. }
  73221. var subMeshes = new Array();
  73222. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  73223. var mesh = renderList_1[_i];
  73224. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  73225. }
  73226. if (subMeshes.length === 0) {
  73227. if (onCompiled) {
  73228. onCompiled(this);
  73229. }
  73230. return;
  73231. }
  73232. var currentIndex = 0;
  73233. var checkReady = function () {
  73234. if (!_this._scene || !_this._scene.getEngine()) {
  73235. return;
  73236. }
  73237. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  73238. currentIndex++;
  73239. if (currentIndex >= subMeshes.length) {
  73240. if (onCompiled) {
  73241. onCompiled(_this);
  73242. }
  73243. return;
  73244. }
  73245. }
  73246. setTimeout(checkReady, 16);
  73247. };
  73248. checkReady();
  73249. };
  73250. /**
  73251. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  73252. * @param options Sets of optional options forcing the compilation with different modes
  73253. * @returns A promise that resolves when the compilation completes
  73254. */
  73255. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  73256. var _this = this;
  73257. return new Promise(function (resolve) {
  73258. _this.forceCompilation(function () {
  73259. resolve();
  73260. }, options);
  73261. });
  73262. };
  73263. /**
  73264. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  73265. * @param subMesh The submesh we want to render in the shadow map
  73266. * @param useInstances Defines wether will draw in the map using instances
  73267. * @returns true if ready otherwise, false
  73268. */
  73269. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  73270. var defines = [];
  73271. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73272. defines.push("#define FLOAT");
  73273. }
  73274. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  73275. defines.push("#define ESM");
  73276. }
  73277. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  73278. defines.push("#define DEPTHTEXTURE");
  73279. }
  73280. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73281. var mesh = subMesh.getMesh();
  73282. var material = subMesh.getMaterial();
  73283. // Normal bias.
  73284. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  73285. attribs.push(BABYLON.VertexBuffer.NormalKind);
  73286. defines.push("#define NORMAL");
  73287. if (mesh.nonUniformScaling) {
  73288. defines.push("#define NONUNIFORMSCALING");
  73289. }
  73290. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  73291. defines.push("#define DIRECTIONINLIGHTDATA");
  73292. }
  73293. }
  73294. // Alpha test
  73295. if (material && material.needAlphaTesting()) {
  73296. var alphaTexture = material.getAlphaTestTexture();
  73297. if (alphaTexture) {
  73298. defines.push("#define ALPHATEST");
  73299. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73300. attribs.push(BABYLON.VertexBuffer.UVKind);
  73301. defines.push("#define UV1");
  73302. }
  73303. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73304. if (alphaTexture.coordinatesIndex === 1) {
  73305. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73306. defines.push("#define UV2");
  73307. }
  73308. }
  73309. }
  73310. }
  73311. // Bones
  73312. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73313. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73314. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73315. if (mesh.numBoneInfluencers > 4) {
  73316. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73317. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73318. }
  73319. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73320. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  73321. }
  73322. else {
  73323. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73324. }
  73325. // Morph targets
  73326. var manager = mesh.morphTargetManager;
  73327. var morphInfluencers = 0;
  73328. if (manager) {
  73329. if (manager.numInfluencers > 0) {
  73330. defines.push("#define MORPHTARGETS");
  73331. morphInfluencers = manager.numInfluencers;
  73332. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  73333. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  73334. }
  73335. }
  73336. // Instances
  73337. if (useInstances) {
  73338. defines.push("#define INSTANCES");
  73339. attribs.push("world0");
  73340. attribs.push("world1");
  73341. attribs.push("world2");
  73342. attribs.push("world3");
  73343. }
  73344. // Get correct effect
  73345. var join = defines.join("\n");
  73346. if (this._cachedDefines !== join) {
  73347. this._cachedDefines = join;
  73348. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  73349. }
  73350. if (!this._effect.isReady()) {
  73351. return false;
  73352. }
  73353. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  73354. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  73355. this._initializeBlurRTTAndPostProcesses();
  73356. }
  73357. }
  73358. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  73359. return false;
  73360. }
  73361. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  73362. return false;
  73363. }
  73364. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  73365. return false;
  73366. }
  73367. return true;
  73368. };
  73369. /**
  73370. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  73371. * @param defines Defines of the material we want to update
  73372. * @param lightIndex Index of the light in the enabled light list of the material
  73373. */
  73374. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  73375. var scene = this._scene;
  73376. var light = this._light;
  73377. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  73378. return;
  73379. }
  73380. defines["SHADOW" + lightIndex] = true;
  73381. if (this.useContactHardeningShadow) {
  73382. defines["SHADOWPCSS" + lightIndex] = true;
  73383. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  73384. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  73385. }
  73386. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  73387. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  73388. }
  73389. // else default to high.
  73390. }
  73391. if (this.usePercentageCloserFiltering) {
  73392. defines["SHADOWPCF" + lightIndex] = true;
  73393. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  73394. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  73395. }
  73396. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  73397. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  73398. }
  73399. // else default to high.
  73400. }
  73401. else if (this.usePoissonSampling) {
  73402. defines["SHADOWPOISSON" + lightIndex] = true;
  73403. }
  73404. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  73405. defines["SHADOWESM" + lightIndex] = true;
  73406. }
  73407. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  73408. defines["SHADOWCLOSEESM" + lightIndex] = true;
  73409. }
  73410. if (light.needCube()) {
  73411. defines["SHADOWCUBE" + lightIndex] = true;
  73412. }
  73413. };
  73414. /**
  73415. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  73416. * defined in the generator but impacting the effect).
  73417. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  73418. * @param effect The effect we are binfing the information for
  73419. */
  73420. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  73421. var light = this._light;
  73422. var scene = this._scene;
  73423. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  73424. return;
  73425. }
  73426. var camera = scene.activeCamera;
  73427. if (!camera) {
  73428. return;
  73429. }
  73430. var shadowMap = this.getShadowMap();
  73431. if (!shadowMap) {
  73432. return;
  73433. }
  73434. if (!light.needCube()) {
  73435. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  73436. }
  73437. // Only PCF uses depth stencil texture.
  73438. if (this._filter === ShadowGenerator.FILTER_PCF) {
  73439. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  73440. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  73441. }
  73442. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  73443. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  73444. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  73445. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  73446. }
  73447. else {
  73448. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  73449. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  73450. }
  73451. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  73452. };
  73453. /**
  73454. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  73455. * (eq to shadow prjection matrix * light transform matrix)
  73456. * @returns The transform matrix used to create the shadow map
  73457. */
  73458. ShadowGenerator.prototype.getTransformMatrix = function () {
  73459. var scene = this._scene;
  73460. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  73461. return this._transformMatrix;
  73462. }
  73463. this._currentRenderID = scene.getRenderId();
  73464. this._currentFaceIndexCache = this._currentFaceIndex;
  73465. var lightPosition = this._light.position;
  73466. if (this._light.computeTransformedInformation()) {
  73467. lightPosition = this._light.transformedPosition;
  73468. }
  73469. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  73470. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  73471. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  73472. }
  73473. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  73474. this._cachedPosition.copyFrom(lightPosition);
  73475. this._cachedDirection.copyFrom(this._lightDirection);
  73476. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  73477. var shadowMap = this.getShadowMap();
  73478. if (shadowMap) {
  73479. var renderList = shadowMap.renderList;
  73480. if (renderList) {
  73481. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  73482. }
  73483. }
  73484. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  73485. }
  73486. return this._transformMatrix;
  73487. };
  73488. /**
  73489. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  73490. * Cube and 2D textures for instance.
  73491. */
  73492. ShadowGenerator.prototype.recreateShadowMap = function () {
  73493. var shadowMap = this._shadowMap;
  73494. if (!shadowMap) {
  73495. return;
  73496. }
  73497. // Track render list.
  73498. var renderList = shadowMap.renderList;
  73499. // Clean up existing data.
  73500. this._disposeRTTandPostProcesses();
  73501. // Reinitializes.
  73502. this._initializeGenerator();
  73503. // Reaffect the filter to ensure a correct fallback if necessary.
  73504. this.filter = this.filter;
  73505. // Reaffect the filter.
  73506. this._applyFilterValues();
  73507. // Reaffect Render List.
  73508. this._shadowMap.renderList = renderList;
  73509. };
  73510. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  73511. if (this._shadowMap2) {
  73512. this._shadowMap2.dispose();
  73513. this._shadowMap2 = null;
  73514. }
  73515. if (this._boxBlurPostprocess) {
  73516. this._boxBlurPostprocess.dispose();
  73517. this._boxBlurPostprocess = null;
  73518. }
  73519. if (this._kernelBlurXPostprocess) {
  73520. this._kernelBlurXPostprocess.dispose();
  73521. this._kernelBlurXPostprocess = null;
  73522. }
  73523. if (this._kernelBlurYPostprocess) {
  73524. this._kernelBlurYPostprocess.dispose();
  73525. this._kernelBlurYPostprocess = null;
  73526. }
  73527. this._blurPostProcesses = [];
  73528. };
  73529. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  73530. if (this._shadowMap) {
  73531. this._shadowMap.dispose();
  73532. this._shadowMap = null;
  73533. }
  73534. this._disposeBlurPostProcesses();
  73535. };
  73536. /**
  73537. * Disposes the ShadowGenerator.
  73538. * Returns nothing.
  73539. */
  73540. ShadowGenerator.prototype.dispose = function () {
  73541. this._disposeRTTandPostProcesses();
  73542. if (this._light) {
  73543. this._light._shadowGenerator = null;
  73544. this._light._markMeshesAsLightDirty();
  73545. }
  73546. };
  73547. /**
  73548. * Serializes the shadow generator setup to a json object.
  73549. * @returns The serialized JSON object
  73550. */
  73551. ShadowGenerator.prototype.serialize = function () {
  73552. var serializationObject = {};
  73553. var shadowMap = this.getShadowMap();
  73554. if (!shadowMap) {
  73555. return serializationObject;
  73556. }
  73557. serializationObject.lightId = this._light.id;
  73558. serializationObject.mapSize = shadowMap.getRenderSize();
  73559. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  73560. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  73561. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  73562. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  73563. serializationObject.usePoissonSampling = this.usePoissonSampling;
  73564. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  73565. serializationObject.depthScale = this.depthScale;
  73566. serializationObject.darkness = this.getDarkness();
  73567. serializationObject.blurBoxOffset = this.blurBoxOffset;
  73568. serializationObject.blurKernel = this.blurKernel;
  73569. serializationObject.blurScale = this.blurScale;
  73570. serializationObject.useKernelBlur = this.useKernelBlur;
  73571. serializationObject.transparencyShadow = this._transparencyShadow;
  73572. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  73573. serializationObject.bias = this.bias;
  73574. serializationObject.normalBias = this.normalBias;
  73575. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  73576. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  73577. serializationObject.filteringQuality = this.filteringQuality;
  73578. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  73579. serializationObject.renderList = [];
  73580. if (shadowMap.renderList) {
  73581. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  73582. var mesh = shadowMap.renderList[meshIndex];
  73583. serializationObject.renderList.push(mesh.id);
  73584. }
  73585. }
  73586. return serializationObject;
  73587. };
  73588. /**
  73589. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  73590. * @param parsedShadowGenerator The JSON object to parse
  73591. * @param scene The scene to create the shadow map for
  73592. * @returns The parsed shadow generator
  73593. */
  73594. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  73595. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  73596. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  73597. var shadowMap = shadowGenerator.getShadowMap();
  73598. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  73599. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  73600. meshes.forEach(function (mesh) {
  73601. if (!shadowMap) {
  73602. return;
  73603. }
  73604. if (!shadowMap.renderList) {
  73605. shadowMap.renderList = [];
  73606. }
  73607. shadowMap.renderList.push(mesh);
  73608. });
  73609. }
  73610. if (parsedShadowGenerator.usePoissonSampling) {
  73611. shadowGenerator.usePoissonSampling = true;
  73612. }
  73613. else if (parsedShadowGenerator.useExponentialShadowMap) {
  73614. shadowGenerator.useExponentialShadowMap = true;
  73615. }
  73616. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  73617. shadowGenerator.useBlurExponentialShadowMap = true;
  73618. }
  73619. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  73620. shadowGenerator.useCloseExponentialShadowMap = true;
  73621. }
  73622. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  73623. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  73624. }
  73625. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  73626. shadowGenerator.usePercentageCloserFiltering = true;
  73627. }
  73628. else if (parsedShadowGenerator.useContactHardeningShadow) {
  73629. shadowGenerator.useContactHardeningShadow = true;
  73630. }
  73631. if (parsedShadowGenerator.filteringQuality) {
  73632. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  73633. }
  73634. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  73635. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  73636. }
  73637. // Backward compat
  73638. else if (parsedShadowGenerator.useVarianceShadowMap) {
  73639. shadowGenerator.useExponentialShadowMap = true;
  73640. }
  73641. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  73642. shadowGenerator.useBlurExponentialShadowMap = true;
  73643. }
  73644. if (parsedShadowGenerator.depthScale) {
  73645. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  73646. }
  73647. if (parsedShadowGenerator.blurScale) {
  73648. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  73649. }
  73650. if (parsedShadowGenerator.blurBoxOffset) {
  73651. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  73652. }
  73653. if (parsedShadowGenerator.useKernelBlur) {
  73654. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  73655. }
  73656. if (parsedShadowGenerator.blurKernel) {
  73657. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  73658. }
  73659. if (parsedShadowGenerator.bias !== undefined) {
  73660. shadowGenerator.bias = parsedShadowGenerator.bias;
  73661. }
  73662. if (parsedShadowGenerator.normalBias !== undefined) {
  73663. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  73664. }
  73665. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  73666. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  73667. }
  73668. if (parsedShadowGenerator.darkness) {
  73669. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  73670. }
  73671. if (parsedShadowGenerator.transparencyShadow) {
  73672. shadowGenerator.setTransparencyShadow(true);
  73673. }
  73674. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  73675. return shadowGenerator;
  73676. };
  73677. /**
  73678. * Shadow generator mode None: no filtering applied.
  73679. */
  73680. ShadowGenerator.FILTER_NONE = 0;
  73681. /**
  73682. * Shadow generator mode ESM: Exponential Shadow Mapping.
  73683. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73684. */
  73685. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  73686. /**
  73687. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  73688. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  73689. */
  73690. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  73691. /**
  73692. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  73693. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73694. */
  73695. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  73696. /**
  73697. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  73698. * edge artifacts on steep falloff.
  73699. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73700. */
  73701. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  73702. /**
  73703. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  73704. * edge artifacts on steep falloff.
  73705. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73706. */
  73707. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  73708. /**
  73709. * Shadow generator mode PCF: Percentage Closer Filtering
  73710. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  73711. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  73712. */
  73713. ShadowGenerator.FILTER_PCF = 6;
  73714. /**
  73715. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  73716. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  73717. * Contact Hardening
  73718. */
  73719. ShadowGenerator.FILTER_PCSS = 7;
  73720. /**
  73721. * Reserved for PCF and PCSS
  73722. * Highest Quality.
  73723. *
  73724. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  73725. *
  73726. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  73727. */
  73728. ShadowGenerator.QUALITY_HIGH = 0;
  73729. /**
  73730. * Reserved for PCF and PCSS
  73731. * Good tradeoff for quality/perf cross devices
  73732. *
  73733. * Execute PCF on a 3*3 kernel.
  73734. *
  73735. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  73736. */
  73737. ShadowGenerator.QUALITY_MEDIUM = 1;
  73738. /**
  73739. * Reserved for PCF and PCSS
  73740. * The lowest quality but the fastest.
  73741. *
  73742. * Execute PCF on a 1*1 kernel.
  73743. *
  73744. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  73745. */
  73746. ShadowGenerator.QUALITY_LOW = 2;
  73747. return ShadowGenerator;
  73748. }());
  73749. BABYLON.ShadowGenerator = ShadowGenerator;
  73750. })(BABYLON || (BABYLON = {}));
  73751. //# sourceMappingURL=babylon.shadowGenerator.js.map
  73752. var BABYLON;
  73753. (function (BABYLON) {
  73754. // Adds the parser to the scene parsers.
  73755. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  73756. // Shadows
  73757. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  73758. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  73759. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  73760. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  73761. // SG would be available on their associated lights
  73762. }
  73763. }
  73764. });
  73765. /**
  73766. * Defines the shadow generator component responsible to manage any shadow generators
  73767. * in a given scene.
  73768. */
  73769. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  73770. /**
  73771. * Creates a new instance of the component for the given scene
  73772. * @param scene Defines the scene to register the component in
  73773. */
  73774. function ShadowGeneratorSceneComponent(scene) {
  73775. /**
  73776. * The component name helpfull to identify the component in the list of scene components.
  73777. */
  73778. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  73779. this.scene = scene;
  73780. }
  73781. /**
  73782. * Registers the component in a given scene
  73783. */
  73784. ShadowGeneratorSceneComponent.prototype.register = function () {
  73785. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  73786. };
  73787. /**
  73788. * Rebuilds the elements related to this component in case of
  73789. * context lost for instance.
  73790. */
  73791. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  73792. // Nothing To Do Here.
  73793. };
  73794. /**
  73795. * Serializes the component data to the specified json object
  73796. * @param serializationObject The object to serialize to
  73797. */
  73798. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  73799. // Shadows
  73800. serializationObject.shadowGenerators = [];
  73801. var lights = this.scene.lights;
  73802. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  73803. var light = lights_1[_i];
  73804. var shadowGenerator = light.getShadowGenerator();
  73805. if (shadowGenerator) {
  73806. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  73807. }
  73808. }
  73809. };
  73810. /**
  73811. * Adds all the element from the container to the scene
  73812. * @param container the container holding the elements
  73813. */
  73814. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  73815. // Nothing To Do Here. (directly attached to a light)
  73816. };
  73817. /**
  73818. * Removes all the elements in the container from the scene
  73819. * @param container contains the elements to remove
  73820. */
  73821. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  73822. // Nothing To Do Here. (directly attached to a light)
  73823. };
  73824. /**
  73825. * Rebuilds the elements related to this component in case of
  73826. * context lost for instance.
  73827. */
  73828. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  73829. // Nothing To Do Here.
  73830. };
  73831. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  73832. // Shadows
  73833. var scene = this.scene;
  73834. if (this.scene.shadowsEnabled) {
  73835. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  73836. var light = scene.lights[lightIndex];
  73837. var shadowGenerator = light.getShadowGenerator();
  73838. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  73839. var shadowMap = (shadowGenerator.getShadowMap());
  73840. if (scene.textures.indexOf(shadowMap) !== -1) {
  73841. renderTargets.push(shadowMap);
  73842. }
  73843. }
  73844. }
  73845. }
  73846. };
  73847. return ShadowGeneratorSceneComponent;
  73848. }());
  73849. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  73850. })(BABYLON || (BABYLON = {}));
  73851. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  73852. var BABYLON;
  73853. (function (BABYLON) {
  73854. var DefaultLoadingScreen = /** @class */ (function () {
  73855. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  73856. if (_loadingText === void 0) { _loadingText = ""; }
  73857. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  73858. var _this = this;
  73859. this._renderingCanvas = _renderingCanvas;
  73860. this._loadingText = _loadingText;
  73861. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  73862. // Resize
  73863. this._resizeLoadingUI = function () {
  73864. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  73865. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  73866. if (!_this._loadingDiv) {
  73867. return;
  73868. }
  73869. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  73870. _this._loadingDiv.style.left = canvasRect.left + "px";
  73871. _this._loadingDiv.style.top = canvasRect.top + "px";
  73872. _this._loadingDiv.style.width = canvasRect.width + "px";
  73873. _this._loadingDiv.style.height = canvasRect.height + "px";
  73874. };
  73875. }
  73876. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  73877. if (this._loadingDiv) {
  73878. // Do not add a loading screen if there is already one
  73879. return;
  73880. }
  73881. this._loadingDiv = document.createElement("div");
  73882. this._loadingDiv.id = "babylonjsLoadingDiv";
  73883. this._loadingDiv.style.opacity = "0";
  73884. this._loadingDiv.style.transition = "opacity 1.5s ease";
  73885. this._loadingDiv.style.pointerEvents = "none";
  73886. // Loading text
  73887. this._loadingTextDiv = document.createElement("div");
  73888. this._loadingTextDiv.style.position = "absolute";
  73889. this._loadingTextDiv.style.left = "0";
  73890. this._loadingTextDiv.style.top = "50%";
  73891. this._loadingTextDiv.style.marginTop = "80px";
  73892. this._loadingTextDiv.style.width = "100%";
  73893. this._loadingTextDiv.style.height = "20px";
  73894. this._loadingTextDiv.style.fontFamily = "Arial";
  73895. this._loadingTextDiv.style.fontSize = "14px";
  73896. this._loadingTextDiv.style.color = "white";
  73897. this._loadingTextDiv.style.textAlign = "center";
  73898. this._loadingTextDiv.innerHTML = "Loading";
  73899. this._loadingDiv.appendChild(this._loadingTextDiv);
  73900. //set the predefined text
  73901. this._loadingTextDiv.innerHTML = this._loadingText;
  73902. // Generating keyframes
  73903. var style = document.createElement('style');
  73904. style.type = 'text/css';
  73905. 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 }";
  73906. style.innerHTML = keyFrames;
  73907. document.getElementsByTagName('head')[0].appendChild(style);
  73908. // Loading img
  73909. var imgBack = new Image();
  73910. 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";
  73911. imgBack.style.position = "absolute";
  73912. imgBack.style.left = "50%";
  73913. imgBack.style.top = "50%";
  73914. imgBack.style.marginLeft = "-60px";
  73915. imgBack.style.marginTop = "-60px";
  73916. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  73917. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  73918. imgBack.style.transformOrigin = "50% 50%";
  73919. imgBack.style.webkitTransformOrigin = "50% 50%";
  73920. this._loadingDiv.appendChild(imgBack);
  73921. this._resizeLoadingUI();
  73922. window.addEventListener("resize", this._resizeLoadingUI);
  73923. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  73924. document.body.appendChild(this._loadingDiv);
  73925. this._loadingDiv.style.opacity = "1";
  73926. };
  73927. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  73928. var _this = this;
  73929. if (!this._loadingDiv) {
  73930. return;
  73931. }
  73932. var onTransitionEnd = function () {
  73933. if (!_this._loadingDiv) {
  73934. return;
  73935. }
  73936. document.body.removeChild(_this._loadingDiv);
  73937. window.removeEventListener("resize", _this._resizeLoadingUI);
  73938. _this._loadingDiv = null;
  73939. };
  73940. this._loadingDiv.style.opacity = "0";
  73941. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  73942. };
  73943. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  73944. set: function (text) {
  73945. this._loadingText = text;
  73946. if (this._loadingTextDiv) {
  73947. this._loadingTextDiv.innerHTML = this._loadingText;
  73948. }
  73949. },
  73950. enumerable: true,
  73951. configurable: true
  73952. });
  73953. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  73954. get: function () {
  73955. return this._loadingDivBackgroundColor;
  73956. },
  73957. set: function (color) {
  73958. this._loadingDivBackgroundColor = color;
  73959. if (!this._loadingDiv) {
  73960. return;
  73961. }
  73962. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  73963. },
  73964. enumerable: true,
  73965. configurable: true
  73966. });
  73967. return DefaultLoadingScreen;
  73968. }());
  73969. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  73970. })(BABYLON || (BABYLON = {}));
  73971. //# sourceMappingURL=babylon.loadingScreen.js.map
  73972. var BABYLON;
  73973. (function (BABYLON) {
  73974. var SceneLoaderProgressEvent = /** @class */ (function () {
  73975. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  73976. this.lengthComputable = lengthComputable;
  73977. this.loaded = loaded;
  73978. this.total = total;
  73979. }
  73980. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  73981. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  73982. };
  73983. return SceneLoaderProgressEvent;
  73984. }());
  73985. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  73986. var SceneLoader = /** @class */ (function () {
  73987. function SceneLoader() {
  73988. }
  73989. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  73990. get: function () {
  73991. return 0;
  73992. },
  73993. enumerable: true,
  73994. configurable: true
  73995. });
  73996. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  73997. get: function () {
  73998. return 1;
  73999. },
  74000. enumerable: true,
  74001. configurable: true
  74002. });
  74003. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  74004. get: function () {
  74005. return 2;
  74006. },
  74007. enumerable: true,
  74008. configurable: true
  74009. });
  74010. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  74011. get: function () {
  74012. return 3;
  74013. },
  74014. enumerable: true,
  74015. configurable: true
  74016. });
  74017. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  74018. get: function () {
  74019. return SceneLoader._ForceFullSceneLoadingForIncremental;
  74020. },
  74021. set: function (value) {
  74022. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  74023. },
  74024. enumerable: true,
  74025. configurable: true
  74026. });
  74027. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  74028. get: function () {
  74029. return SceneLoader._ShowLoadingScreen;
  74030. },
  74031. set: function (value) {
  74032. SceneLoader._ShowLoadingScreen = value;
  74033. },
  74034. enumerable: true,
  74035. configurable: true
  74036. });
  74037. Object.defineProperty(SceneLoader, "loggingLevel", {
  74038. get: function () {
  74039. return SceneLoader._loggingLevel;
  74040. },
  74041. set: function (value) {
  74042. SceneLoader._loggingLevel = value;
  74043. },
  74044. enumerable: true,
  74045. configurable: true
  74046. });
  74047. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  74048. get: function () {
  74049. return SceneLoader._CleanBoneMatrixWeights;
  74050. },
  74051. set: function (value) {
  74052. SceneLoader._CleanBoneMatrixWeights = value;
  74053. },
  74054. enumerable: true,
  74055. configurable: true
  74056. });
  74057. SceneLoader._getDefaultPlugin = function () {
  74058. return SceneLoader._registeredPlugins[".babylon"];
  74059. };
  74060. SceneLoader._getPluginForExtension = function (extension) {
  74061. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  74062. if (registeredPlugin) {
  74063. return registeredPlugin;
  74064. }
  74065. 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");
  74066. return SceneLoader._getDefaultPlugin();
  74067. };
  74068. SceneLoader._getPluginForDirectLoad = function (data) {
  74069. for (var extension in SceneLoader._registeredPlugins) {
  74070. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  74071. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  74072. return SceneLoader._registeredPlugins[extension];
  74073. }
  74074. }
  74075. return SceneLoader._getDefaultPlugin();
  74076. };
  74077. SceneLoader._getPluginForFilename = function (sceneFilename) {
  74078. var queryStringPosition = sceneFilename.indexOf("?");
  74079. if (queryStringPosition !== -1) {
  74080. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  74081. }
  74082. var dotPosition = sceneFilename.lastIndexOf(".");
  74083. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  74084. return SceneLoader._getPluginForExtension(extension);
  74085. };
  74086. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  74087. SceneLoader._getDirectLoad = function (sceneFilename) {
  74088. if (sceneFilename.substr(0, 5) === "data:") {
  74089. return sceneFilename.substr(5);
  74090. }
  74091. return null;
  74092. };
  74093. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  74094. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  74095. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  74096. var plugin;
  74097. if (registeredPlugin.plugin.createPlugin) {
  74098. plugin = registeredPlugin.plugin.createPlugin();
  74099. }
  74100. else {
  74101. plugin = registeredPlugin.plugin;
  74102. }
  74103. var useArrayBuffer = registeredPlugin.isBinary;
  74104. var database;
  74105. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  74106. var dataCallback = function (data, responseURL) {
  74107. if (scene.isDisposed) {
  74108. onError("Scene has been disposed");
  74109. return;
  74110. }
  74111. scene.database = database;
  74112. onSuccess(plugin, data, responseURL);
  74113. };
  74114. var request = null;
  74115. var pluginDisposed = false;
  74116. var onDisposeObservable = plugin.onDisposeObservable;
  74117. if (onDisposeObservable) {
  74118. onDisposeObservable.add(function () {
  74119. pluginDisposed = true;
  74120. if (request) {
  74121. request.abort();
  74122. request = null;
  74123. }
  74124. onDispose();
  74125. });
  74126. }
  74127. var manifestChecked = function () {
  74128. if (pluginDisposed) {
  74129. return;
  74130. }
  74131. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  74132. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  74133. } : undefined, database, useArrayBuffer, function (request, exception) {
  74134. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  74135. });
  74136. };
  74137. if (directLoad) {
  74138. dataCallback(directLoad);
  74139. return plugin;
  74140. }
  74141. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  74142. var engine = scene.getEngine();
  74143. var canUseOfflineSupport = engine.enableOfflineSupport;
  74144. if (canUseOfflineSupport) {
  74145. // Also check for exceptions
  74146. var exceptionFound = false;
  74147. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  74148. var regex = _a[_i];
  74149. if (regex.test(fileInfo.url)) {
  74150. exceptionFound = true;
  74151. break;
  74152. }
  74153. }
  74154. canUseOfflineSupport = !exceptionFound;
  74155. }
  74156. if (canUseOfflineSupport) {
  74157. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  74158. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  74159. }
  74160. else {
  74161. manifestChecked();
  74162. }
  74163. }
  74164. // Loading file from disk via input file or drag'n'drop
  74165. else {
  74166. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  74167. if (file) {
  74168. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  74169. }
  74170. else {
  74171. onError("Unable to find file named " + fileInfo.name);
  74172. }
  74173. }
  74174. return plugin;
  74175. };
  74176. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  74177. var url;
  74178. var name;
  74179. if (!sceneFilename) {
  74180. url = rootUrl;
  74181. name = BABYLON.Tools.GetFilename(rootUrl);
  74182. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  74183. }
  74184. else {
  74185. if (sceneFilename.substr(0, 1) === "/") {
  74186. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  74187. return null;
  74188. }
  74189. url = rootUrl + sceneFilename;
  74190. name = sceneFilename;
  74191. }
  74192. ;
  74193. return {
  74194. url: url,
  74195. rootUrl: rootUrl,
  74196. name: name
  74197. };
  74198. };
  74199. // Public functions
  74200. SceneLoader.GetPluginForExtension = function (extension) {
  74201. return SceneLoader._getPluginForExtension(extension).plugin;
  74202. };
  74203. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  74204. return !!SceneLoader._registeredPlugins[extension];
  74205. };
  74206. SceneLoader.RegisterPlugin = function (plugin) {
  74207. if (typeof plugin.extensions === "string") {
  74208. var extension = plugin.extensions;
  74209. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  74210. plugin: plugin,
  74211. isBinary: false
  74212. };
  74213. }
  74214. else {
  74215. var extensions = plugin.extensions;
  74216. Object.keys(extensions).forEach(function (extension) {
  74217. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  74218. plugin: plugin,
  74219. isBinary: extensions[extension].isBinary
  74220. };
  74221. });
  74222. }
  74223. };
  74224. /**
  74225. * Import meshes into a scene
  74226. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  74227. * @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)
  74228. * @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)
  74229. * @param scene the instance of BABYLON.Scene to append to
  74230. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  74231. * @param onProgress a callback with a progress event for each file being loaded
  74232. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74233. * @param pluginExtension the extension used to determine the plugin
  74234. * @returns The loaded plugin
  74235. */
  74236. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  74237. if (sceneFilename === void 0) { sceneFilename = ""; }
  74238. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74239. if (onSuccess === void 0) { onSuccess = null; }
  74240. if (onProgress === void 0) { onProgress = null; }
  74241. if (onError === void 0) { onError = null; }
  74242. if (pluginExtension === void 0) { pluginExtension = null; }
  74243. if (!scene) {
  74244. BABYLON.Tools.Error("No scene available to import mesh to");
  74245. return null;
  74246. }
  74247. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  74248. if (!fileInfo) {
  74249. return null;
  74250. }
  74251. var loadingToken = {};
  74252. scene._addPendingData(loadingToken);
  74253. var disposeHandler = function () {
  74254. scene._removePendingData(loadingToken);
  74255. };
  74256. var errorHandler = function (message, exception) {
  74257. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  74258. if (onError) {
  74259. onError(scene, errorMessage, exception);
  74260. }
  74261. else {
  74262. BABYLON.Tools.Error(errorMessage);
  74263. // should the exception be thrown?
  74264. }
  74265. disposeHandler();
  74266. };
  74267. var progressHandler = onProgress ? function (event) {
  74268. try {
  74269. onProgress(event);
  74270. }
  74271. catch (e) {
  74272. errorHandler("Error in onProgress callback", e);
  74273. }
  74274. } : undefined;
  74275. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  74276. scene.importedMeshesFiles.push(fileInfo.url);
  74277. if (onSuccess) {
  74278. try {
  74279. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  74280. }
  74281. catch (e) {
  74282. errorHandler("Error in onSuccess callback", e);
  74283. }
  74284. }
  74285. scene._removePendingData(loadingToken);
  74286. };
  74287. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  74288. if (plugin.rewriteRootURL) {
  74289. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  74290. }
  74291. if (plugin.importMesh) {
  74292. var syncedPlugin = plugin;
  74293. var meshes = new Array();
  74294. var particleSystems = new Array();
  74295. var skeletons = new Array();
  74296. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  74297. return;
  74298. }
  74299. scene.loadingPluginName = plugin.name;
  74300. successHandler(meshes, particleSystems, skeletons, []);
  74301. }
  74302. else {
  74303. var asyncedPlugin = plugin;
  74304. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  74305. scene.loadingPluginName = plugin.name;
  74306. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  74307. }).catch(function (error) {
  74308. errorHandler(error.message, error);
  74309. });
  74310. }
  74311. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  74312. };
  74313. /**
  74314. * Import meshes into a scene
  74315. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  74316. * @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)
  74317. * @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)
  74318. * @param scene the instance of BABYLON.Scene to append to
  74319. * @param onProgress a callback with a progress event for each file being loaded
  74320. * @param pluginExtension the extension used to determine the plugin
  74321. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  74322. */
  74323. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  74324. if (sceneFilename === void 0) { sceneFilename = ""; }
  74325. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74326. if (onProgress === void 0) { onProgress = null; }
  74327. if (pluginExtension === void 0) { pluginExtension = null; }
  74328. return new Promise(function (resolve, reject) {
  74329. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  74330. resolve({
  74331. meshes: meshes,
  74332. particleSystems: particleSystems,
  74333. skeletons: skeletons,
  74334. animationGroups: animationGroups
  74335. });
  74336. }, onProgress, function (scene, message, exception) {
  74337. reject(exception || new Error(message));
  74338. }, pluginExtension);
  74339. });
  74340. };
  74341. /**
  74342. * Load a scene
  74343. * @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)
  74344. * @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)
  74345. * @param engine is the instance of BABYLON.Engine to use to create the scene
  74346. * @param onSuccess a callback with the scene when import succeeds
  74347. * @param onProgress a callback with a progress event for each file being loaded
  74348. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74349. * @param pluginExtension the extension used to determine the plugin
  74350. * @returns The loaded plugin
  74351. */
  74352. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  74353. if (onSuccess === void 0) { onSuccess = null; }
  74354. if (onProgress === void 0) { onProgress = null; }
  74355. if (onError === void 0) { onError = null; }
  74356. if (pluginExtension === void 0) { pluginExtension = null; }
  74357. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  74358. };
  74359. /**
  74360. * Load a scene
  74361. * @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)
  74362. * @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)
  74363. * @param engine is the instance of BABYLON.Engine to use to create the scene
  74364. * @param onProgress a callback with a progress event for each file being loaded
  74365. * @param pluginExtension the extension used to determine the plugin
  74366. * @returns The loaded scene
  74367. */
  74368. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  74369. if (onProgress === void 0) { onProgress = null; }
  74370. if (pluginExtension === void 0) { pluginExtension = null; }
  74371. return new Promise(function (resolve, reject) {
  74372. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  74373. resolve(scene);
  74374. }, onProgress, function (scene, message, exception) {
  74375. reject(exception || new Error(message));
  74376. }, pluginExtension);
  74377. });
  74378. };
  74379. /**
  74380. * Append a scene
  74381. * @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)
  74382. * @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)
  74383. * @param scene is the instance of BABYLON.Scene to append to
  74384. * @param onSuccess a callback with the scene when import succeeds
  74385. * @param onProgress a callback with a progress event for each file being loaded
  74386. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74387. * @param pluginExtension the extension used to determine the plugin
  74388. * @returns The loaded plugin
  74389. */
  74390. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  74391. if (sceneFilename === void 0) { sceneFilename = ""; }
  74392. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74393. if (onSuccess === void 0) { onSuccess = null; }
  74394. if (onProgress === void 0) { onProgress = null; }
  74395. if (onError === void 0) { onError = null; }
  74396. if (pluginExtension === void 0) { pluginExtension = null; }
  74397. if (!scene) {
  74398. BABYLON.Tools.Error("No scene available to append to");
  74399. return null;
  74400. }
  74401. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  74402. if (!fileInfo) {
  74403. return null;
  74404. }
  74405. if (SceneLoader.ShowLoadingScreen) {
  74406. scene.getEngine().displayLoadingUI();
  74407. }
  74408. var loadingToken = {};
  74409. scene._addPendingData(loadingToken);
  74410. var disposeHandler = function () {
  74411. scene._removePendingData(loadingToken);
  74412. scene.getEngine().hideLoadingUI();
  74413. };
  74414. var errorHandler = function (message, exception) {
  74415. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  74416. if (onError) {
  74417. onError(scene, errorMessage, exception);
  74418. }
  74419. else {
  74420. BABYLON.Tools.Error(errorMessage);
  74421. // should the exception be thrown?
  74422. }
  74423. disposeHandler();
  74424. };
  74425. var progressHandler = onProgress ? function (event) {
  74426. try {
  74427. onProgress(event);
  74428. }
  74429. catch (e) {
  74430. errorHandler("Error in onProgress callback", e);
  74431. }
  74432. } : undefined;
  74433. var successHandler = function () {
  74434. if (onSuccess) {
  74435. try {
  74436. onSuccess(scene);
  74437. }
  74438. catch (e) {
  74439. errorHandler("Error in onSuccess callback", e);
  74440. }
  74441. }
  74442. scene._removePendingData(loadingToken);
  74443. };
  74444. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  74445. if (plugin.load) {
  74446. var syncedPlugin = plugin;
  74447. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  74448. return;
  74449. }
  74450. scene.loadingPluginName = plugin.name;
  74451. successHandler();
  74452. }
  74453. else {
  74454. var asyncedPlugin = plugin;
  74455. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  74456. scene.loadingPluginName = plugin.name;
  74457. successHandler();
  74458. }).catch(function (error) {
  74459. errorHandler(error.message, error);
  74460. });
  74461. }
  74462. if (SceneLoader.ShowLoadingScreen) {
  74463. scene.executeWhenReady(function () {
  74464. scene.getEngine().hideLoadingUI();
  74465. });
  74466. }
  74467. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  74468. };
  74469. /**
  74470. * Append a scene
  74471. * @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)
  74472. * @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)
  74473. * @param scene is the instance of BABYLON.Scene to append to
  74474. * @param onProgress a callback with a progress event for each file being loaded
  74475. * @param pluginExtension the extension used to determine the plugin
  74476. * @returns The given scene
  74477. */
  74478. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  74479. if (sceneFilename === void 0) { sceneFilename = ""; }
  74480. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74481. if (onProgress === void 0) { onProgress = null; }
  74482. if (pluginExtension === void 0) { pluginExtension = null; }
  74483. return new Promise(function (resolve, reject) {
  74484. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  74485. resolve(scene);
  74486. }, onProgress, function (scene, message, exception) {
  74487. reject(exception || new Error(message));
  74488. }, pluginExtension);
  74489. });
  74490. };
  74491. /**
  74492. * Load a scene into an asset container
  74493. * @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)
  74494. * @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)
  74495. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  74496. * @param onSuccess a callback with the scene when import succeeds
  74497. * @param onProgress a callback with a progress event for each file being loaded
  74498. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74499. * @param pluginExtension the extension used to determine the plugin
  74500. * @returns The loaded plugin
  74501. */
  74502. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  74503. if (sceneFilename === void 0) { sceneFilename = ""; }
  74504. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74505. if (onSuccess === void 0) { onSuccess = null; }
  74506. if (onProgress === void 0) { onProgress = null; }
  74507. if (onError === void 0) { onError = null; }
  74508. if (pluginExtension === void 0) { pluginExtension = null; }
  74509. if (!scene) {
  74510. BABYLON.Tools.Error("No scene available to load asset container to");
  74511. return null;
  74512. }
  74513. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  74514. if (!fileInfo) {
  74515. return null;
  74516. }
  74517. var loadingToken = {};
  74518. scene._addPendingData(loadingToken);
  74519. var disposeHandler = function () {
  74520. scene._removePendingData(loadingToken);
  74521. };
  74522. var errorHandler = function (message, exception) {
  74523. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  74524. if (onError) {
  74525. onError(scene, errorMessage, exception);
  74526. }
  74527. else {
  74528. BABYLON.Tools.Error(errorMessage);
  74529. // should the exception be thrown?
  74530. }
  74531. disposeHandler();
  74532. };
  74533. var progressHandler = onProgress ? function (event) {
  74534. try {
  74535. onProgress(event);
  74536. }
  74537. catch (e) {
  74538. errorHandler("Error in onProgress callback", e);
  74539. }
  74540. } : undefined;
  74541. var successHandler = function (assets) {
  74542. if (onSuccess) {
  74543. try {
  74544. onSuccess(assets);
  74545. }
  74546. catch (e) {
  74547. errorHandler("Error in onSuccess callback", e);
  74548. }
  74549. }
  74550. scene._removePendingData(loadingToken);
  74551. };
  74552. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  74553. if (plugin.loadAssetContainer) {
  74554. var syncedPlugin = plugin;
  74555. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  74556. if (!assetContainer) {
  74557. return;
  74558. }
  74559. scene.loadingPluginName = plugin.name;
  74560. successHandler(assetContainer);
  74561. }
  74562. else if (plugin.loadAssetContainerAsync) {
  74563. var asyncedPlugin = plugin;
  74564. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  74565. scene.loadingPluginName = plugin.name;
  74566. successHandler(assetContainer);
  74567. }).catch(function (error) {
  74568. errorHandler(error.message, error);
  74569. });
  74570. }
  74571. else {
  74572. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  74573. }
  74574. if (SceneLoader.ShowLoadingScreen) {
  74575. scene.executeWhenReady(function () {
  74576. scene.getEngine().hideLoadingUI();
  74577. });
  74578. }
  74579. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  74580. };
  74581. /**
  74582. * Load a scene into an asset container
  74583. * @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)
  74584. * @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)
  74585. * @param scene is the instance of BABYLON.Scene to append to
  74586. * @param onProgress a callback with a progress event for each file being loaded
  74587. * @param pluginExtension the extension used to determine the plugin
  74588. * @returns The loaded asset container
  74589. */
  74590. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  74591. if (sceneFilename === void 0) { sceneFilename = ""; }
  74592. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74593. if (onProgress === void 0) { onProgress = null; }
  74594. if (pluginExtension === void 0) { pluginExtension = null; }
  74595. return new Promise(function (resolve, reject) {
  74596. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  74597. resolve(assetContainer);
  74598. }, onProgress, function (scene, message, exception) {
  74599. reject(exception || new Error(message));
  74600. }, pluginExtension);
  74601. });
  74602. };
  74603. // Flags
  74604. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  74605. SceneLoader._ShowLoadingScreen = true;
  74606. SceneLoader._CleanBoneMatrixWeights = false;
  74607. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  74608. // Members
  74609. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  74610. SceneLoader._registeredPlugins = {};
  74611. return SceneLoader;
  74612. }());
  74613. BABYLON.SceneLoader = SceneLoader;
  74614. ;
  74615. })(BABYLON || (BABYLON = {}));
  74616. //# sourceMappingURL=babylon.sceneLoader.js.map
  74617. var BABYLON;
  74618. (function (BABYLON) {
  74619. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  74620. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  74621. var parsedMaterial = parsedData.materials[index];
  74622. if (parsedMaterial.id === id) {
  74623. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  74624. }
  74625. }
  74626. return null;
  74627. };
  74628. var isDescendantOf = function (mesh, names, hierarchyIds) {
  74629. for (var i in names) {
  74630. if (mesh.name === names[i]) {
  74631. hierarchyIds.push(mesh.id);
  74632. return true;
  74633. }
  74634. }
  74635. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  74636. hierarchyIds.push(mesh.id);
  74637. return true;
  74638. }
  74639. return false;
  74640. };
  74641. var logOperation = function (operation, producer) {
  74642. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  74643. };
  74644. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  74645. if (addToScene === void 0) { addToScene = false; }
  74646. var container = new BABYLON.AssetContainer(scene);
  74647. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74648. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74649. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74650. // and avoid problems with multiple concurrent .babylon loads.
  74651. var log = "importScene has failed JSON parse";
  74652. try {
  74653. var parsedData = JSON.parse(data);
  74654. log = "";
  74655. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  74656. var index;
  74657. var cache;
  74658. // Lights
  74659. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  74660. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  74661. var parsedLight = parsedData.lights[index];
  74662. var light = BABYLON.Light.Parse(parsedLight, scene);
  74663. if (light) {
  74664. container.lights.push(light);
  74665. log += (index === 0 ? "\n\tLights:" : "");
  74666. log += "\n\t\t" + light.toString(fullDetails);
  74667. }
  74668. }
  74669. }
  74670. // Animations
  74671. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  74672. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  74673. var parsedAnimation = parsedData.animations[index];
  74674. var animation = BABYLON.Animation.Parse(parsedAnimation);
  74675. scene.animations.push(animation);
  74676. container.animations.push(animation);
  74677. log += (index === 0 ? "\n\tAnimations:" : "");
  74678. log += "\n\t\t" + animation.toString(fullDetails);
  74679. }
  74680. }
  74681. // Materials
  74682. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  74683. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  74684. var parsedMaterial = parsedData.materials[index];
  74685. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  74686. container.materials.push(mat);
  74687. log += (index === 0 ? "\n\tMaterials:" : "");
  74688. log += "\n\t\t" + mat.toString(fullDetails);
  74689. }
  74690. }
  74691. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  74692. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  74693. var parsedMultiMaterial = parsedData.multiMaterials[index];
  74694. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  74695. container.multiMaterials.push(mmat);
  74696. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  74697. log += "\n\t\t" + mmat.toString(fullDetails);
  74698. }
  74699. }
  74700. // Morph targets
  74701. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  74702. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  74703. var managerData = _a[_i];
  74704. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  74705. }
  74706. }
  74707. // Skeletons
  74708. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  74709. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  74710. var parsedSkeleton = parsedData.skeletons[index];
  74711. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  74712. container.skeletons.push(skeleton);
  74713. log += (index === 0 ? "\n\tSkeletons:" : "");
  74714. log += "\n\t\t" + skeleton.toString(fullDetails);
  74715. }
  74716. }
  74717. // Geometries
  74718. var geometries = parsedData.geometries;
  74719. if (geometries !== undefined && geometries !== null) {
  74720. var addedGeometry = new Array();
  74721. // Boxes
  74722. var boxes = geometries.boxes;
  74723. if (boxes !== undefined && boxes !== null) {
  74724. for (index = 0, cache = boxes.length; index < cache; index++) {
  74725. var parsedBox = boxes[index];
  74726. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  74727. }
  74728. }
  74729. // Spheres
  74730. var spheres = geometries.spheres;
  74731. if (spheres !== undefined && spheres !== null) {
  74732. for (index = 0, cache = spheres.length; index < cache; index++) {
  74733. var parsedSphere = spheres[index];
  74734. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  74735. }
  74736. }
  74737. // Cylinders
  74738. var cylinders = geometries.cylinders;
  74739. if (cylinders !== undefined && cylinders !== null) {
  74740. for (index = 0, cache = cylinders.length; index < cache; index++) {
  74741. var parsedCylinder = cylinders[index];
  74742. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  74743. }
  74744. }
  74745. // Toruses
  74746. var toruses = geometries.toruses;
  74747. if (toruses !== undefined && toruses !== null) {
  74748. for (index = 0, cache = toruses.length; index < cache; index++) {
  74749. var parsedTorus = toruses[index];
  74750. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  74751. }
  74752. }
  74753. // Grounds
  74754. var grounds = geometries.grounds;
  74755. if (grounds !== undefined && grounds !== null) {
  74756. for (index = 0, cache = grounds.length; index < cache; index++) {
  74757. var parsedGround = grounds[index];
  74758. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  74759. }
  74760. }
  74761. // Planes
  74762. var planes = geometries.planes;
  74763. if (planes !== undefined && planes !== null) {
  74764. for (index = 0, cache = planes.length; index < cache; index++) {
  74765. var parsedPlane = planes[index];
  74766. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  74767. }
  74768. }
  74769. // TorusKnots
  74770. var torusKnots = geometries.torusKnots;
  74771. if (torusKnots !== undefined && torusKnots !== null) {
  74772. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  74773. var parsedTorusKnot = torusKnots[index];
  74774. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  74775. }
  74776. }
  74777. // VertexData
  74778. var vertexData = geometries.vertexData;
  74779. if (vertexData !== undefined && vertexData !== null) {
  74780. for (index = 0, cache = vertexData.length; index < cache; index++) {
  74781. var parsedVertexData = vertexData[index];
  74782. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  74783. }
  74784. }
  74785. addedGeometry.forEach(function (g) {
  74786. if (g) {
  74787. container.geometries.push(g);
  74788. }
  74789. });
  74790. }
  74791. // Transform nodes
  74792. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  74793. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  74794. var parsedTransformNode = parsedData.transformNodes[index];
  74795. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  74796. container.transformNodes.push(node);
  74797. }
  74798. }
  74799. // Meshes
  74800. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  74801. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  74802. var parsedMesh = parsedData.meshes[index];
  74803. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  74804. container.meshes.push(mesh);
  74805. log += (index === 0 ? "\n\tMeshes:" : "");
  74806. log += "\n\t\t" + mesh.toString(fullDetails);
  74807. }
  74808. }
  74809. // Cameras
  74810. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  74811. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  74812. var parsedCamera = parsedData.cameras[index];
  74813. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  74814. container.cameras.push(camera);
  74815. log += (index === 0 ? "\n\tCameras:" : "");
  74816. log += "\n\t\t" + camera.toString(fullDetails);
  74817. }
  74818. }
  74819. // Animation Groups
  74820. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  74821. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  74822. var parsedAnimationGroup = parsedData.animationGroups[index];
  74823. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  74824. container.animationGroups.push(animationGroup);
  74825. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  74826. log += "\n\t\t" + animationGroup.toString(fullDetails);
  74827. }
  74828. }
  74829. // Browsing all the graph to connect the dots
  74830. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  74831. var camera = scene.cameras[index];
  74832. if (camera._waitingParentId) {
  74833. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  74834. camera._waitingParentId = null;
  74835. }
  74836. }
  74837. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  74838. var light_1 = scene.lights[index];
  74839. if (light_1 && light_1._waitingParentId) {
  74840. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  74841. light_1._waitingParentId = null;
  74842. }
  74843. }
  74844. // Connect parents & children and parse actions
  74845. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  74846. var transformNode = scene.transformNodes[index];
  74847. if (transformNode._waitingParentId) {
  74848. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  74849. transformNode._waitingParentId = null;
  74850. }
  74851. }
  74852. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74853. var mesh = scene.meshes[index];
  74854. if (mesh._waitingParentId) {
  74855. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  74856. mesh._waitingParentId = null;
  74857. }
  74858. }
  74859. // freeze world matrix application
  74860. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74861. var currentMesh = scene.meshes[index];
  74862. if (currentMesh._waitingFreezeWorldMatrix) {
  74863. currentMesh.freezeWorldMatrix();
  74864. currentMesh._waitingFreezeWorldMatrix = null;
  74865. }
  74866. else {
  74867. currentMesh.computeWorldMatrix(true);
  74868. }
  74869. }
  74870. // Lights exclusions / inclusions
  74871. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  74872. var light_2 = scene.lights[index];
  74873. // Excluded check
  74874. if (light_2._excludedMeshesIds.length > 0) {
  74875. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  74876. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  74877. if (excludedMesh) {
  74878. light_2.excludedMeshes.push(excludedMesh);
  74879. }
  74880. }
  74881. light_2._excludedMeshesIds = [];
  74882. }
  74883. // Included check
  74884. if (light_2._includedOnlyMeshesIds.length > 0) {
  74885. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  74886. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  74887. if (includedOnlyMesh) {
  74888. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  74889. }
  74890. }
  74891. light_2._includedOnlyMeshesIds = [];
  74892. }
  74893. }
  74894. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  74895. // Actions (scene) Done last as it can access other objects.
  74896. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74897. var mesh = scene.meshes[index];
  74898. if (mesh._waitingActions) {
  74899. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  74900. mesh._waitingActions = null;
  74901. }
  74902. }
  74903. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  74904. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  74905. }
  74906. if (!addToScene) {
  74907. container.removeAllFromScene();
  74908. }
  74909. }
  74910. catch (err) {
  74911. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  74912. if (onError) {
  74913. onError(msg, err);
  74914. }
  74915. else {
  74916. BABYLON.Tools.Log(msg);
  74917. throw err;
  74918. }
  74919. }
  74920. finally {
  74921. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  74922. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  74923. }
  74924. }
  74925. return container;
  74926. };
  74927. BABYLON.SceneLoader.RegisterPlugin({
  74928. name: "babylon.js",
  74929. extensions: ".babylon",
  74930. canDirectLoad: function (data) {
  74931. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  74932. return true;
  74933. }
  74934. return false;
  74935. },
  74936. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  74937. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74938. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74939. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74940. // and avoid problems with multiple concurrent .babylon loads.
  74941. var log = "importMesh has failed JSON parse";
  74942. try {
  74943. var parsedData = JSON.parse(data);
  74944. log = "";
  74945. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  74946. if (!meshesNames) {
  74947. meshesNames = null;
  74948. }
  74949. else if (!Array.isArray(meshesNames)) {
  74950. meshesNames = [meshesNames];
  74951. }
  74952. var hierarchyIds = new Array();
  74953. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  74954. var loadedSkeletonsIds = [];
  74955. var loadedMaterialsIds = [];
  74956. var index;
  74957. var cache;
  74958. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  74959. var parsedMesh = parsedData.meshes[index];
  74960. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  74961. if (meshesNames !== null) {
  74962. // Remove found mesh name from list.
  74963. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  74964. }
  74965. //Geometry?
  74966. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  74967. //does the file contain geometries?
  74968. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  74969. //find the correct geometry and add it to the scene
  74970. var found = false;
  74971. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  74972. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  74973. return;
  74974. }
  74975. else {
  74976. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  74977. if (parsedGeometryData.id === parsedMesh.geometryId) {
  74978. switch (geometryType) {
  74979. case "boxes":
  74980. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  74981. break;
  74982. case "spheres":
  74983. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  74984. break;
  74985. case "cylinders":
  74986. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  74987. break;
  74988. case "toruses":
  74989. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  74990. break;
  74991. case "grounds":
  74992. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  74993. break;
  74994. case "planes":
  74995. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  74996. break;
  74997. case "torusKnots":
  74998. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  74999. break;
  75000. case "vertexData":
  75001. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  75002. break;
  75003. }
  75004. found = true;
  75005. }
  75006. });
  75007. }
  75008. });
  75009. if (found === false) {
  75010. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  75011. }
  75012. }
  75013. }
  75014. // Material ?
  75015. if (parsedMesh.materialId) {
  75016. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  75017. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  75018. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  75019. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  75020. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  75021. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  75022. var subMatId = parsedMultiMaterial.materials[matIndex];
  75023. loadedMaterialsIds.push(subMatId);
  75024. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  75025. if (mat) {
  75026. log += "\n\tMaterial " + mat.toString(fullDetails);
  75027. }
  75028. }
  75029. loadedMaterialsIds.push(parsedMultiMaterial.id);
  75030. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  75031. if (mmat) {
  75032. materialFound = true;
  75033. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  75034. }
  75035. break;
  75036. }
  75037. }
  75038. }
  75039. if (materialFound === false) {
  75040. loadedMaterialsIds.push(parsedMesh.materialId);
  75041. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  75042. if (!mat) {
  75043. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  75044. }
  75045. else {
  75046. log += "\n\tMaterial " + mat.toString(fullDetails);
  75047. }
  75048. }
  75049. }
  75050. // Skeleton ?
  75051. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  75052. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  75053. if (skeletonAlreadyLoaded === false) {
  75054. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  75055. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  75056. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  75057. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  75058. skeletons.push(skeleton);
  75059. loadedSkeletonsIds.push(parsedSkeleton.id);
  75060. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  75061. }
  75062. }
  75063. }
  75064. }
  75065. // Morph targets ?
  75066. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  75067. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  75068. var managerData = _a[_i];
  75069. BABYLON.MorphTargetManager.Parse(managerData, scene);
  75070. }
  75071. }
  75072. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  75073. meshes.push(mesh);
  75074. log += "\n\tMesh " + mesh.toString(fullDetails);
  75075. }
  75076. }
  75077. // Connecting parents
  75078. var currentMesh;
  75079. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  75080. currentMesh = scene.meshes[index];
  75081. if (currentMesh._waitingParentId) {
  75082. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  75083. currentMesh._waitingParentId = null;
  75084. }
  75085. }
  75086. // freeze and compute world matrix application
  75087. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  75088. currentMesh = scene.meshes[index];
  75089. if (currentMesh._waitingFreezeWorldMatrix) {
  75090. currentMesh.freezeWorldMatrix();
  75091. currentMesh._waitingFreezeWorldMatrix = null;
  75092. }
  75093. else {
  75094. currentMesh.computeWorldMatrix(true);
  75095. }
  75096. }
  75097. }
  75098. // Particles
  75099. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  75100. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  75101. if (parser) {
  75102. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  75103. var parsedParticleSystem = parsedData.particleSystems[index];
  75104. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  75105. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  75106. }
  75107. }
  75108. }
  75109. }
  75110. return true;
  75111. }
  75112. catch (err) {
  75113. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  75114. if (onError) {
  75115. onError(msg, err);
  75116. }
  75117. else {
  75118. BABYLON.Tools.Log(msg);
  75119. throw err;
  75120. }
  75121. }
  75122. finally {
  75123. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  75124. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  75125. }
  75126. }
  75127. return false;
  75128. },
  75129. load: function (scene, data, rootUrl, onError) {
  75130. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  75131. // when SceneLoader.debugLogging = true (default), or exception encountered.
  75132. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  75133. // and avoid problems with multiple concurrent .babylon loads.
  75134. var log = "importScene has failed JSON parse";
  75135. try {
  75136. var parsedData = JSON.parse(data);
  75137. log = "";
  75138. // Scene
  75139. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  75140. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  75141. }
  75142. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  75143. scene.autoClear = parsedData.autoClear;
  75144. }
  75145. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  75146. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  75147. }
  75148. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  75149. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  75150. }
  75151. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  75152. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  75153. }
  75154. // Fog
  75155. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  75156. scene.fogMode = parsedData.fogMode;
  75157. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  75158. scene.fogStart = parsedData.fogStart;
  75159. scene.fogEnd = parsedData.fogEnd;
  75160. scene.fogDensity = parsedData.fogDensity;
  75161. log += "\tFog mode for scene: ";
  75162. switch (scene.fogMode) {
  75163. // getters not compiling, so using hardcoded
  75164. case 1:
  75165. log += "exp\n";
  75166. break;
  75167. case 2:
  75168. log += "exp2\n";
  75169. break;
  75170. case 3:
  75171. log += "linear\n";
  75172. break;
  75173. }
  75174. }
  75175. //Physics
  75176. if (parsedData.physicsEnabled) {
  75177. var physicsPlugin;
  75178. if (parsedData.physicsEngine === "cannon") {
  75179. physicsPlugin = new BABYLON.CannonJSPlugin();
  75180. }
  75181. else if (parsedData.physicsEngine === "oimo") {
  75182. physicsPlugin = new BABYLON.OimoJSPlugin();
  75183. }
  75184. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  75185. //else - default engine, which is currently oimo
  75186. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  75187. scene.enablePhysics(physicsGravity, physicsPlugin);
  75188. }
  75189. // Metadata
  75190. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  75191. scene.metadata = parsedData.metadata;
  75192. }
  75193. //collisions, if defined. otherwise, default is true
  75194. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  75195. scene.collisionsEnabled = parsedData.collisionsEnabled;
  75196. }
  75197. scene.workerCollisions = !!parsedData.workerCollisions;
  75198. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  75199. if (!container) {
  75200. return false;
  75201. }
  75202. if (parsedData.autoAnimate) {
  75203. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  75204. }
  75205. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  75206. scene.setActiveCameraByID(parsedData.activeCameraID);
  75207. }
  75208. // Environment texture
  75209. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  75210. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  75211. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  75212. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  75213. if (parsedData.environmentTextureRotationY) {
  75214. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  75215. }
  75216. scene.environmentTexture = hdrTexture;
  75217. }
  75218. else {
  75219. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  75220. if (parsedData.environmentTextureRotationY) {
  75221. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  75222. }
  75223. scene.environmentTexture = cubeTexture;
  75224. }
  75225. if (parsedData.createDefaultSkybox === true) {
  75226. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  75227. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  75228. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  75229. }
  75230. }
  75231. // Finish
  75232. return true;
  75233. }
  75234. catch (err) {
  75235. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  75236. if (onError) {
  75237. onError(msg, err);
  75238. }
  75239. else {
  75240. BABYLON.Tools.Log(msg);
  75241. throw err;
  75242. }
  75243. }
  75244. finally {
  75245. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  75246. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  75247. }
  75248. }
  75249. return false;
  75250. },
  75251. loadAssetContainer: function (scene, data, rootUrl, onError) {
  75252. var container = loadAssetContainer(scene, data, rootUrl, onError);
  75253. return container;
  75254. }
  75255. });
  75256. })(BABYLON || (BABYLON = {}));
  75257. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  75258. var BABYLON;
  75259. (function (BABYLON) {
  75260. /**
  75261. * Class used to help managing file picking and drag'n'drop
  75262. */
  75263. var FilesInput = /** @class */ (function () {
  75264. /**
  75265. * Creates a new FilesInput
  75266. * @param engine defines the rendering engine
  75267. * @param scene defines the hosting scene
  75268. * @param sceneLoadedCallback callback called when scene is loaded
  75269. * @param progressCallback callback called to track progress
  75270. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  75271. * @param textureLoadingCallback callback called when a texture is loading
  75272. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  75273. * @param onReloadCallback callback called when a reload is requested
  75274. * @param errorCallback callback call if an error occurs
  75275. */
  75276. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  75277. /**
  75278. * Callback called when a file is processed
  75279. */
  75280. this.onProcessFileCallback = function () { return true; };
  75281. this._engine = engine;
  75282. this._currentScene = scene;
  75283. this._sceneLoadedCallback = sceneLoadedCallback;
  75284. this._progressCallback = progressCallback;
  75285. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  75286. this._textureLoadingCallback = textureLoadingCallback;
  75287. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  75288. this._onReloadCallback = onReloadCallback;
  75289. this._errorCallback = errorCallback;
  75290. }
  75291. /**
  75292. * Calls this function to listen to drag'n'drop events on a specific DOM element
  75293. * @param elementToMonitor defines the DOM element to track
  75294. */
  75295. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  75296. var _this = this;
  75297. if (elementToMonitor) {
  75298. this._elementToMonitor = elementToMonitor;
  75299. this._dragEnterHandler = function (e) { _this.drag(e); };
  75300. this._dragOverHandler = function (e) { _this.drag(e); };
  75301. this._dropHandler = function (e) { _this.drop(e); };
  75302. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  75303. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  75304. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  75305. }
  75306. };
  75307. /**
  75308. * Release all associated resources
  75309. */
  75310. FilesInput.prototype.dispose = function () {
  75311. if (!this._elementToMonitor) {
  75312. return;
  75313. }
  75314. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  75315. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  75316. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  75317. };
  75318. FilesInput.prototype.renderFunction = function () {
  75319. if (this._additionalRenderLoopLogicCallback) {
  75320. this._additionalRenderLoopLogicCallback();
  75321. }
  75322. if (this._currentScene) {
  75323. if (this._textureLoadingCallback) {
  75324. var remaining = this._currentScene.getWaitingItemsCount();
  75325. if (remaining > 0) {
  75326. this._textureLoadingCallback(remaining);
  75327. }
  75328. }
  75329. this._currentScene.render();
  75330. }
  75331. };
  75332. FilesInput.prototype.drag = function (e) {
  75333. e.stopPropagation();
  75334. e.preventDefault();
  75335. };
  75336. FilesInput.prototype.drop = function (eventDrop) {
  75337. eventDrop.stopPropagation();
  75338. eventDrop.preventDefault();
  75339. this.loadFiles(eventDrop);
  75340. };
  75341. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  75342. var _this = this;
  75343. var reader = folder.createReader();
  75344. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  75345. reader.readEntries(function (entries) {
  75346. remaining.count += entries.length;
  75347. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  75348. var entry = entries_1[_i];
  75349. if (entry.isFile) {
  75350. entry.file(function (file) {
  75351. file.correctName = relativePath + file.name;
  75352. files.push(file);
  75353. if (--remaining.count === 0) {
  75354. callback();
  75355. }
  75356. });
  75357. }
  75358. else if (entry.isDirectory) {
  75359. _this._traverseFolder(entry, files, remaining, callback);
  75360. }
  75361. }
  75362. if (--remaining.count) {
  75363. callback();
  75364. }
  75365. });
  75366. };
  75367. FilesInput.prototype._processFiles = function (files) {
  75368. for (var i = 0; i < files.length; i++) {
  75369. var name = files[i].correctName.toLowerCase();
  75370. var extension = name.split('.').pop();
  75371. if (!this.onProcessFileCallback(files[i], name, extension)) {
  75372. continue;
  75373. }
  75374. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  75375. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  75376. this._sceneFileToLoad = files[i];
  75377. }
  75378. FilesInput.FilesToLoad[name] = files[i];
  75379. }
  75380. };
  75381. /**
  75382. * Load files from a drop event
  75383. * @param event defines the drop event to use as source
  75384. */
  75385. FilesInput.prototype.loadFiles = function (event) {
  75386. var _this = this;
  75387. // Handling data transfer via drag'n'drop
  75388. if (event && event.dataTransfer && event.dataTransfer.files) {
  75389. this._filesToLoad = event.dataTransfer.files;
  75390. }
  75391. // Handling files from input files
  75392. if (event && event.target && event.target.files) {
  75393. this._filesToLoad = event.target.files;
  75394. }
  75395. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  75396. return;
  75397. }
  75398. if (this._startingProcessingFilesCallback) {
  75399. this._startingProcessingFilesCallback(this._filesToLoad);
  75400. }
  75401. if (this._filesToLoad && this._filesToLoad.length > 0) {
  75402. var files_1 = new Array();
  75403. var folders = [];
  75404. var items = event.dataTransfer ? event.dataTransfer.items : null;
  75405. for (var i = 0; i < this._filesToLoad.length; i++) {
  75406. var fileToLoad = this._filesToLoad[i];
  75407. var name_1 = fileToLoad.name.toLowerCase();
  75408. var entry = void 0;
  75409. fileToLoad.correctName = name_1;
  75410. if (items) {
  75411. var item = items[i];
  75412. if (item.getAsEntry) {
  75413. entry = item.getAsEntry();
  75414. }
  75415. else if (item.webkitGetAsEntry) {
  75416. entry = item.webkitGetAsEntry();
  75417. }
  75418. }
  75419. if (!entry) {
  75420. files_1.push(fileToLoad);
  75421. }
  75422. else {
  75423. if (entry.isDirectory) {
  75424. folders.push(entry);
  75425. }
  75426. else {
  75427. files_1.push(fileToLoad);
  75428. }
  75429. }
  75430. }
  75431. if (folders.length === 0) {
  75432. this._processFiles(files_1);
  75433. this._processReload();
  75434. }
  75435. else {
  75436. var remaining = { count: folders.length };
  75437. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  75438. var folder = folders_1[_i];
  75439. this._traverseFolder(folder, files_1, remaining, function () {
  75440. _this._processFiles(files_1);
  75441. if (remaining.count === 0) {
  75442. _this._processReload();
  75443. }
  75444. });
  75445. }
  75446. }
  75447. }
  75448. };
  75449. FilesInput.prototype._processReload = function () {
  75450. if (this._onReloadCallback) {
  75451. this._onReloadCallback(this._sceneFileToLoad);
  75452. }
  75453. else {
  75454. this.reload();
  75455. }
  75456. };
  75457. /**
  75458. * Reload the current scene from the loaded files
  75459. */
  75460. FilesInput.prototype.reload = function () {
  75461. var _this = this;
  75462. // If a scene file has been provided
  75463. if (this._sceneFileToLoad) {
  75464. if (this._currentScene) {
  75465. if (BABYLON.Tools.errorsCount > 0) {
  75466. BABYLON.Tools.ClearLogCache();
  75467. }
  75468. this._engine.stopRenderLoop();
  75469. }
  75470. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  75471. if (_this._progressCallback) {
  75472. _this._progressCallback(progress);
  75473. }
  75474. }).then(function (scene) {
  75475. if (_this._currentScene) {
  75476. _this._currentScene.dispose();
  75477. }
  75478. _this._currentScene = scene;
  75479. if (_this._sceneLoadedCallback) {
  75480. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  75481. }
  75482. // Wait for textures and shaders to be ready
  75483. _this._currentScene.executeWhenReady(function () {
  75484. _this._engine.runRenderLoop(function () {
  75485. _this.renderFunction();
  75486. });
  75487. });
  75488. }).catch(function (error) {
  75489. if (_this._errorCallback) {
  75490. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  75491. }
  75492. });
  75493. }
  75494. else {
  75495. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  75496. }
  75497. };
  75498. /**
  75499. * List of files ready to be loaded
  75500. */
  75501. FilesInput.FilesToLoad = {};
  75502. return FilesInput;
  75503. }());
  75504. BABYLON.FilesInput = FilesInput;
  75505. })(BABYLON || (BABYLON = {}));
  75506. //# sourceMappingURL=babylon.filesInput.js.map
  75507. var BABYLON;
  75508. (function (BABYLON) {
  75509. /**
  75510. * Class used to store custom tags
  75511. */
  75512. var Tags = /** @class */ (function () {
  75513. function Tags() {
  75514. }
  75515. /**
  75516. * Adds support for tags on the given object
  75517. * @param obj defines the object to use
  75518. */
  75519. Tags.EnableFor = function (obj) {
  75520. obj._tags = obj._tags || {};
  75521. obj.hasTags = function () {
  75522. return Tags.HasTags(obj);
  75523. };
  75524. obj.addTags = function (tagsString) {
  75525. return Tags.AddTagsTo(obj, tagsString);
  75526. };
  75527. obj.removeTags = function (tagsString) {
  75528. return Tags.RemoveTagsFrom(obj, tagsString);
  75529. };
  75530. obj.matchesTagsQuery = function (tagsQuery) {
  75531. return Tags.MatchesQuery(obj, tagsQuery);
  75532. };
  75533. };
  75534. /**
  75535. * Removes tags support
  75536. * @param obj defines the object to use
  75537. */
  75538. Tags.DisableFor = function (obj) {
  75539. delete obj._tags;
  75540. delete obj.hasTags;
  75541. delete obj.addTags;
  75542. delete obj.removeTags;
  75543. delete obj.matchesTagsQuery;
  75544. };
  75545. /**
  75546. * Gets a boolean indicating if the given object has tags
  75547. * @param obj defines the object to use
  75548. * @returns a boolean
  75549. */
  75550. Tags.HasTags = function (obj) {
  75551. if (!obj._tags) {
  75552. return false;
  75553. }
  75554. return !BABYLON.Tools.IsEmpty(obj._tags);
  75555. };
  75556. /**
  75557. * Gets the tags available on a given object
  75558. * @param obj defines the object to use
  75559. * @param asString defines if the tags must be returned as a string instead of an array of strings
  75560. * @returns the tags
  75561. */
  75562. Tags.GetTags = function (obj, asString) {
  75563. if (asString === void 0) { asString = true; }
  75564. if (!obj._tags) {
  75565. return null;
  75566. }
  75567. if (asString) {
  75568. var tagsArray = [];
  75569. for (var tag in obj._tags) {
  75570. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  75571. tagsArray.push(tag);
  75572. }
  75573. }
  75574. return tagsArray.join(" ");
  75575. }
  75576. else {
  75577. return obj._tags;
  75578. }
  75579. };
  75580. /**
  75581. * Adds tags to an object
  75582. * @param obj defines the object to use
  75583. * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
  75584. * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
  75585. */
  75586. Tags.AddTagsTo = function (obj, tagsString) {
  75587. if (!tagsString) {
  75588. return;
  75589. }
  75590. if (typeof tagsString !== "string") {
  75591. return;
  75592. }
  75593. var tags = tagsString.split(" ");
  75594. tags.forEach(function (tag, index, array) {
  75595. Tags._AddTagTo(obj, tag);
  75596. });
  75597. };
  75598. /**
  75599. * @hidden
  75600. */
  75601. Tags._AddTagTo = function (obj, tag) {
  75602. tag = tag.trim();
  75603. if (tag === "" || tag === "true" || tag === "false") {
  75604. return;
  75605. }
  75606. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  75607. return;
  75608. }
  75609. Tags.EnableFor(obj);
  75610. obj._tags[tag] = true;
  75611. };
  75612. /**
  75613. * Removes specific tags from a specific object
  75614. * @param obj defines the object to use
  75615. * @param tagsString defines the tags to remove
  75616. */
  75617. Tags.RemoveTagsFrom = function (obj, tagsString) {
  75618. if (!Tags.HasTags(obj)) {
  75619. return;
  75620. }
  75621. var tags = tagsString.split(" ");
  75622. for (var t in tags) {
  75623. Tags._RemoveTagFrom(obj, tags[t]);
  75624. }
  75625. };
  75626. /**
  75627. * @hidden
  75628. */
  75629. Tags._RemoveTagFrom = function (obj, tag) {
  75630. delete obj._tags[tag];
  75631. };
  75632. /**
  75633. * Defines if tags hosted on an object match a given query
  75634. * @param obj defines the object to use
  75635. * @param tagsQuery defines the tag query
  75636. * @returns a boolean
  75637. */
  75638. Tags.MatchesQuery = function (obj, tagsQuery) {
  75639. if (tagsQuery === undefined) {
  75640. return true;
  75641. }
  75642. if (tagsQuery === "") {
  75643. return Tags.HasTags(obj);
  75644. }
  75645. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  75646. };
  75647. return Tags;
  75648. }());
  75649. BABYLON.Tags = Tags;
  75650. })(BABYLON || (BABYLON = {}));
  75651. //# sourceMappingURL=babylon.tags.js.map
  75652. var BABYLON;
  75653. (function (BABYLON) {
  75654. /**
  75655. * Class used to evalaute queries containing `and` and `or` operators
  75656. */
  75657. var AndOrNotEvaluator = /** @class */ (function () {
  75658. function AndOrNotEvaluator() {
  75659. }
  75660. /**
  75661. * Evaluate a query
  75662. * @param query defines the query to evaluate
  75663. * @param evaluateCallback defines the callback used to filter result
  75664. * @returns true if the query matches
  75665. */
  75666. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  75667. if (!query.match(/\([^\(\)]*\)/g)) {
  75668. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  75669. }
  75670. else {
  75671. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  75672. // remove parenthesis
  75673. r = r.slice(1, r.length - 1);
  75674. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  75675. });
  75676. }
  75677. if (query === "true") {
  75678. return true;
  75679. }
  75680. if (query === "false") {
  75681. return false;
  75682. }
  75683. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  75684. };
  75685. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  75686. evaluateCallback = evaluateCallback || (function (r) {
  75687. return r === "true" ? true : false;
  75688. });
  75689. var result;
  75690. var or = parenthesisContent.split("||");
  75691. for (var i in or) {
  75692. if (or.hasOwnProperty(i)) {
  75693. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  75694. var and = ori.split("&&");
  75695. if (and.length > 1) {
  75696. for (var j = 0; j < and.length; ++j) {
  75697. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  75698. if (andj !== "true" && andj !== "false") {
  75699. if (andj[0] === "!") {
  75700. result = !evaluateCallback(andj.substring(1));
  75701. }
  75702. else {
  75703. result = evaluateCallback(andj);
  75704. }
  75705. }
  75706. else {
  75707. result = andj === "true" ? true : false;
  75708. }
  75709. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  75710. ori = "false";
  75711. break;
  75712. }
  75713. }
  75714. }
  75715. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  75716. result = true;
  75717. break;
  75718. }
  75719. // result equals false (or undefined)
  75720. if (ori !== "true" && ori !== "false") {
  75721. if (ori[0] === "!") {
  75722. result = !evaluateCallback(ori.substring(1));
  75723. }
  75724. else {
  75725. result = evaluateCallback(ori);
  75726. }
  75727. }
  75728. else {
  75729. result = ori === "true" ? true : false;
  75730. }
  75731. }
  75732. }
  75733. // the whole parenthesis scope is replaced by 'true' or 'false'
  75734. return result ? "true" : "false";
  75735. };
  75736. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  75737. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  75738. // remove whitespaces
  75739. r = r.replace(/[\s]/g, function () { return ""; });
  75740. return r.length % 2 ? "!" : "";
  75741. });
  75742. booleanString = booleanString.trim();
  75743. if (booleanString === "!true") {
  75744. booleanString = "false";
  75745. }
  75746. else if (booleanString === "!false") {
  75747. booleanString = "true";
  75748. }
  75749. return booleanString;
  75750. };
  75751. return AndOrNotEvaluator;
  75752. }());
  75753. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  75754. })(BABYLON || (BABYLON = {}));
  75755. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  75756. var BABYLON;
  75757. (function (BABYLON) {
  75758. /**
  75759. * Class used to enable access to IndexedDB
  75760. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  75761. */
  75762. var Database = /** @class */ (function () {
  75763. /**
  75764. * Creates a new Database
  75765. * @param urlToScene defines the url to load the scene
  75766. * @param callbackManifestChecked defines the callback to use when manifest is checked
  75767. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  75768. */
  75769. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  75770. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  75771. var _this = this;
  75772. // Handling various flavors of prefixed version of IndexedDB
  75773. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  75774. this.callbackManifestChecked = callbackManifestChecked;
  75775. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  75776. this.db = null;
  75777. this._enableSceneOffline = false;
  75778. this._enableTexturesOffline = false;
  75779. this.manifestVersionFound = 0;
  75780. this.mustUpdateRessources = false;
  75781. this.hasReachedQuota = false;
  75782. if (!Database.IDBStorageEnabled) {
  75783. this.callbackManifestChecked(true);
  75784. }
  75785. else {
  75786. if (disableManifestCheck) {
  75787. this._enableSceneOffline = true;
  75788. this._enableTexturesOffline = true;
  75789. this.manifestVersionFound = 1;
  75790. BABYLON.Tools.SetImmediate(function () {
  75791. _this.callbackManifestChecked(true);
  75792. });
  75793. }
  75794. else {
  75795. this._checkManifestFile();
  75796. }
  75797. }
  75798. }
  75799. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  75800. /**
  75801. * Gets a boolean indicating if scene must be saved in the database
  75802. */
  75803. get: function () {
  75804. return this._enableSceneOffline;
  75805. },
  75806. enumerable: true,
  75807. configurable: true
  75808. });
  75809. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  75810. /**
  75811. * Gets a boolean indicating if textures must be saved in the database
  75812. */
  75813. get: function () {
  75814. return this._enableTexturesOffline;
  75815. },
  75816. enumerable: true,
  75817. configurable: true
  75818. });
  75819. Database.prototype._checkManifestFile = function () {
  75820. var _this = this;
  75821. var noManifestFile = function () {
  75822. _this._enableSceneOffline = false;
  75823. _this._enableTexturesOffline = false;
  75824. _this.callbackManifestChecked(false);
  75825. };
  75826. var timeStampUsed = false;
  75827. var manifestURL = this.currentSceneUrl + ".manifest";
  75828. var xhr = new XMLHttpRequest();
  75829. if (navigator.onLine) {
  75830. // Adding a timestamp to by-pass browsers' cache
  75831. timeStampUsed = true;
  75832. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  75833. }
  75834. xhr.open("GET", manifestURL, true);
  75835. xhr.addEventListener("load", function () {
  75836. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  75837. try {
  75838. var manifestFile = JSON.parse(xhr.response);
  75839. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  75840. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  75841. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  75842. _this.manifestVersionFound = manifestFile.version;
  75843. }
  75844. if (_this.callbackManifestChecked) {
  75845. _this.callbackManifestChecked(true);
  75846. }
  75847. }
  75848. catch (ex) {
  75849. noManifestFile();
  75850. }
  75851. }
  75852. else {
  75853. noManifestFile();
  75854. }
  75855. }, false);
  75856. xhr.addEventListener("error", function (event) {
  75857. if (timeStampUsed) {
  75858. timeStampUsed = false;
  75859. // Let's retry without the timeStamp
  75860. // It could fail when coupled with HTML5 Offline API
  75861. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  75862. xhr.open("GET", retryManifestURL, true);
  75863. xhr.send();
  75864. }
  75865. else {
  75866. noManifestFile();
  75867. }
  75868. }, false);
  75869. try {
  75870. xhr.send();
  75871. }
  75872. catch (ex) {
  75873. BABYLON.Tools.Error("Error on XHR send request.");
  75874. this.callbackManifestChecked(false);
  75875. }
  75876. };
  75877. /**
  75878. * Open the database and make it available
  75879. * @param successCallback defines the callback to call on success
  75880. * @param errorCallback defines the callback to call on error
  75881. */
  75882. Database.prototype.openAsync = function (successCallback, errorCallback) {
  75883. var _this = this;
  75884. var handleError = function () {
  75885. _this.isSupported = false;
  75886. if (errorCallback)
  75887. errorCallback();
  75888. };
  75889. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  75890. // Your browser doesn't support IndexedDB
  75891. this.isSupported = false;
  75892. if (errorCallback)
  75893. errorCallback();
  75894. }
  75895. else {
  75896. // If the DB hasn't been opened or created yet
  75897. if (!this.db) {
  75898. this.hasReachedQuota = false;
  75899. this.isSupported = true;
  75900. var request = this.idbFactory.open("babylonjs", 1);
  75901. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  75902. request.onerror = function (event) {
  75903. handleError();
  75904. };
  75905. // executes when a version change transaction cannot complete due to other active transactions
  75906. request.onblocked = function (event) {
  75907. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  75908. handleError();
  75909. };
  75910. // DB has been opened successfully
  75911. request.onsuccess = function (event) {
  75912. _this.db = request.result;
  75913. successCallback();
  75914. };
  75915. // Initialization of the DB. Creating Scenes & Textures stores
  75916. request.onupgradeneeded = function (event) {
  75917. _this.db = (event.target).result;
  75918. if (_this.db) {
  75919. try {
  75920. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  75921. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  75922. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  75923. }
  75924. catch (ex) {
  75925. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  75926. handleError();
  75927. }
  75928. }
  75929. };
  75930. }
  75931. // DB has already been created and opened
  75932. else {
  75933. if (successCallback)
  75934. successCallback();
  75935. }
  75936. }
  75937. };
  75938. /**
  75939. * Loads an image from the database
  75940. * @param url defines the url to load from
  75941. * @param image defines the target DOM image
  75942. */
  75943. Database.prototype.loadImageFromDB = function (url, image) {
  75944. var _this = this;
  75945. var completeURL = Database._ReturnFullUrlLocation(url);
  75946. var saveAndLoadImage = function () {
  75947. if (!_this.hasReachedQuota && _this.db !== null) {
  75948. // the texture is not yet in the DB, let's try to save it
  75949. _this._saveImageIntoDBAsync(completeURL, image);
  75950. }
  75951. // If the texture is not in the DB and we've reached the DB quota limit
  75952. // let's load it directly from the web
  75953. else {
  75954. image.src = url;
  75955. }
  75956. };
  75957. if (!this.mustUpdateRessources) {
  75958. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  75959. }
  75960. // First time we're download the images or update requested in the manifest file by a version change
  75961. else {
  75962. saveAndLoadImage();
  75963. }
  75964. };
  75965. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  75966. if (this.isSupported && this.db !== null) {
  75967. var texture;
  75968. var transaction = this.db.transaction(["textures"]);
  75969. transaction.onabort = function (event) {
  75970. image.src = url;
  75971. };
  75972. transaction.oncomplete = function (event) {
  75973. var blobTextureURL;
  75974. if (texture) {
  75975. var URL = window.URL || window.webkitURL;
  75976. blobTextureURL = URL.createObjectURL(texture.data);
  75977. image.onerror = function () {
  75978. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  75979. image.src = url;
  75980. };
  75981. image.src = blobTextureURL;
  75982. }
  75983. else {
  75984. notInDBCallback();
  75985. }
  75986. };
  75987. var getRequest = transaction.objectStore("textures").get(url);
  75988. getRequest.onsuccess = function (event) {
  75989. texture = (event.target).result;
  75990. };
  75991. getRequest.onerror = function (event) {
  75992. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  75993. image.src = url;
  75994. };
  75995. }
  75996. else {
  75997. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75998. image.src = url;
  75999. }
  76000. };
  76001. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  76002. var _this = this;
  76003. if (this.isSupported) {
  76004. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  76005. var generateBlobUrl = function () {
  76006. var blobTextureURL;
  76007. if (blob) {
  76008. var URL = window.URL || window.webkitURL;
  76009. try {
  76010. blobTextureURL = URL.createObjectURL(blob);
  76011. }
  76012. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  76013. catch (ex) {
  76014. blobTextureURL = URL.createObjectURL(blob);
  76015. }
  76016. }
  76017. if (blobTextureURL) {
  76018. image.src = blobTextureURL;
  76019. }
  76020. };
  76021. if (Database.IsUASupportingBlobStorage) { // Create XHR
  76022. var xhr = new XMLHttpRequest(), blob;
  76023. xhr.open("GET", url, true);
  76024. xhr.responseType = "blob";
  76025. xhr.addEventListener("load", function () {
  76026. if (xhr.status === 200 && _this.db) {
  76027. // Blob as response (XHR2)
  76028. blob = xhr.response;
  76029. var transaction = _this.db.transaction(["textures"], "readwrite");
  76030. // the transaction could abort because of a QuotaExceededError error
  76031. transaction.onabort = function (event) {
  76032. try {
  76033. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  76034. var srcElement = (event.srcElement || event.target);
  76035. var error = srcElement.error;
  76036. if (error && error.name === "QuotaExceededError") {
  76037. _this.hasReachedQuota = true;
  76038. }
  76039. }
  76040. catch (ex) { }
  76041. generateBlobUrl();
  76042. };
  76043. transaction.oncomplete = function (event) {
  76044. generateBlobUrl();
  76045. };
  76046. var newTexture = { textureUrl: url, data: blob };
  76047. try {
  76048. // Put the blob into the dabase
  76049. var addRequest = transaction.objectStore("textures").put(newTexture);
  76050. addRequest.onsuccess = function (event) {
  76051. };
  76052. addRequest.onerror = function (event) {
  76053. generateBlobUrl();
  76054. };
  76055. }
  76056. catch (ex) {
  76057. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  76058. if (ex.code === 25) {
  76059. Database.IsUASupportingBlobStorage = false;
  76060. }
  76061. image.src = url;
  76062. }
  76063. }
  76064. else {
  76065. image.src = url;
  76066. }
  76067. }, false);
  76068. xhr.addEventListener("error", function (event) {
  76069. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  76070. image.src = url;
  76071. }, false);
  76072. xhr.send();
  76073. }
  76074. else {
  76075. image.src = url;
  76076. }
  76077. }
  76078. else {
  76079. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  76080. image.src = url;
  76081. }
  76082. };
  76083. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  76084. var _this = this;
  76085. var updateVersion = function () {
  76086. // the version is not yet in the DB or we need to update it
  76087. _this._saveVersionIntoDBAsync(url, versionLoaded);
  76088. };
  76089. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  76090. };
  76091. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  76092. var _this = this;
  76093. if (this.isSupported && this.db) {
  76094. var version;
  76095. try {
  76096. var transaction = this.db.transaction(["versions"]);
  76097. transaction.oncomplete = function (event) {
  76098. if (version) {
  76099. // If the version in the JSON file is different from the version in DB
  76100. if (_this.manifestVersionFound !== version.data) {
  76101. _this.mustUpdateRessources = true;
  76102. updateInDBCallback();
  76103. }
  76104. else {
  76105. callback(version.data);
  76106. }
  76107. }
  76108. // version was not found in DB
  76109. else {
  76110. _this.mustUpdateRessources = true;
  76111. updateInDBCallback();
  76112. }
  76113. };
  76114. transaction.onabort = function (event) {
  76115. callback(-1);
  76116. };
  76117. var getRequest = transaction.objectStore("versions").get(url);
  76118. getRequest.onsuccess = function (event) {
  76119. version = (event.target).result;
  76120. };
  76121. getRequest.onerror = function (event) {
  76122. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  76123. callback(-1);
  76124. };
  76125. }
  76126. catch (ex) {
  76127. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  76128. callback(-1);
  76129. }
  76130. }
  76131. else {
  76132. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  76133. callback(-1);
  76134. }
  76135. };
  76136. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  76137. var _this = this;
  76138. if (this.isSupported && !this.hasReachedQuota && this.db) {
  76139. try {
  76140. // Open a transaction to the database
  76141. var transaction = this.db.transaction(["versions"], "readwrite");
  76142. // the transaction could abort because of a QuotaExceededError error
  76143. transaction.onabort = function (event) {
  76144. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  76145. var error = event.srcElement['error'];
  76146. if (error && error.name === "QuotaExceededError") {
  76147. _this.hasReachedQuota = true;
  76148. }
  76149. }
  76150. catch (ex) { }
  76151. callback(-1);
  76152. };
  76153. transaction.oncomplete = function (event) {
  76154. callback(_this.manifestVersionFound);
  76155. };
  76156. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  76157. // Put the scene into the database
  76158. var addRequest = transaction.objectStore("versions").put(newVersion);
  76159. addRequest.onsuccess = function (event) {
  76160. };
  76161. addRequest.onerror = function (event) {
  76162. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  76163. };
  76164. }
  76165. catch (ex) {
  76166. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  76167. callback(-1);
  76168. }
  76169. }
  76170. else {
  76171. callback(-1);
  76172. }
  76173. };
  76174. /**
  76175. * Loads a file from database
  76176. * @param url defines the URL to load from
  76177. * @param sceneLoaded defines a callback to call on success
  76178. * @param progressCallBack defines a callback to call when progress changed
  76179. * @param errorCallback defines a callback to call on error
  76180. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  76181. */
  76182. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  76183. var _this = this;
  76184. var completeUrl = Database._ReturnFullUrlLocation(url);
  76185. var saveAndLoadFile = function () {
  76186. // the scene is not yet in the DB, let's try to save it
  76187. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  76188. };
  76189. this._checkVersionFromDB(completeUrl, function (version) {
  76190. if (version !== -1) {
  76191. if (!_this.mustUpdateRessources) {
  76192. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  76193. }
  76194. else {
  76195. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  76196. }
  76197. }
  76198. else {
  76199. if (errorCallback) {
  76200. errorCallback();
  76201. }
  76202. }
  76203. });
  76204. };
  76205. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  76206. if (this.isSupported && this.db) {
  76207. var targetStore;
  76208. if (url.indexOf(".babylon") !== -1) {
  76209. targetStore = "scenes";
  76210. }
  76211. else {
  76212. targetStore = "textures";
  76213. }
  76214. var file;
  76215. var transaction = this.db.transaction([targetStore]);
  76216. transaction.oncomplete = function (event) {
  76217. if (file) {
  76218. callback(file.data);
  76219. }
  76220. // file was not found in DB
  76221. else {
  76222. notInDBCallback();
  76223. }
  76224. };
  76225. transaction.onabort = function (event) {
  76226. notInDBCallback();
  76227. };
  76228. var getRequest = transaction.objectStore(targetStore).get(url);
  76229. getRequest.onsuccess = function (event) {
  76230. file = (event.target).result;
  76231. };
  76232. getRequest.onerror = function (event) {
  76233. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  76234. notInDBCallback();
  76235. };
  76236. }
  76237. else {
  76238. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  76239. callback();
  76240. }
  76241. };
  76242. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  76243. var _this = this;
  76244. if (this.isSupported) {
  76245. var targetStore;
  76246. if (url.indexOf(".babylon") !== -1) {
  76247. targetStore = "scenes";
  76248. }
  76249. else {
  76250. targetStore = "textures";
  76251. }
  76252. // Create XHR
  76253. var xhr = new XMLHttpRequest();
  76254. var fileData;
  76255. xhr.open("GET", url + "?" + Date.now(), true);
  76256. if (useArrayBuffer) {
  76257. xhr.responseType = "arraybuffer";
  76258. }
  76259. if (progressCallback) {
  76260. xhr.onprogress = progressCallback;
  76261. }
  76262. xhr.addEventListener("load", function () {
  76263. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  76264. // Blob as response (XHR2)
  76265. //fileData = xhr.responseText;
  76266. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  76267. if (!_this.hasReachedQuota && _this.db) {
  76268. // Open a transaction to the database
  76269. var transaction = _this.db.transaction([targetStore], "readwrite");
  76270. // the transaction could abort because of a QuotaExceededError error
  76271. transaction.onabort = function (event) {
  76272. try {
  76273. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  76274. var error = event.srcElement['error'];
  76275. if (error && error.name === "QuotaExceededError") {
  76276. _this.hasReachedQuota = true;
  76277. }
  76278. }
  76279. catch (ex) { }
  76280. callback(fileData);
  76281. };
  76282. transaction.oncomplete = function (event) {
  76283. callback(fileData);
  76284. };
  76285. var newFile;
  76286. if (targetStore === "scenes") {
  76287. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  76288. }
  76289. else {
  76290. newFile = { textureUrl: url, data: fileData };
  76291. }
  76292. try {
  76293. // Put the scene into the database
  76294. var addRequest = transaction.objectStore(targetStore).put(newFile);
  76295. addRequest.onsuccess = function (event) {
  76296. };
  76297. addRequest.onerror = function (event) {
  76298. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  76299. };
  76300. }
  76301. catch (ex) {
  76302. callback(fileData);
  76303. }
  76304. }
  76305. else {
  76306. callback(fileData);
  76307. }
  76308. }
  76309. else {
  76310. if (xhr.status >= 400 && errorCallback) {
  76311. errorCallback(xhr);
  76312. }
  76313. else {
  76314. callback();
  76315. }
  76316. }
  76317. }, false);
  76318. xhr.addEventListener("error", function (event) {
  76319. BABYLON.Tools.Error("error on XHR request.");
  76320. callback();
  76321. }, false);
  76322. xhr.send();
  76323. }
  76324. else {
  76325. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  76326. callback();
  76327. }
  76328. };
  76329. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  76330. Database.IsUASupportingBlobStorage = true;
  76331. /** Gets a boolean indicating if Database storate is enabled */
  76332. Database.IDBStorageEnabled = true;
  76333. Database._ParseURL = function (url) {
  76334. var a = document.createElement('a');
  76335. a.href = url;
  76336. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  76337. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  76338. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  76339. return absLocation;
  76340. };
  76341. Database._ReturnFullUrlLocation = function (url) {
  76342. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  76343. return (Database._ParseURL(window.location.href) + url);
  76344. }
  76345. else {
  76346. return url;
  76347. }
  76348. };
  76349. return Database;
  76350. }());
  76351. BABYLON.Database = Database;
  76352. })(BABYLON || (BABYLON = {}));
  76353. //# sourceMappingURL=babylon.database.js.map
  76354. var BABYLON;
  76355. (function (BABYLON) {
  76356. var FresnelParameters = /** @class */ (function () {
  76357. function FresnelParameters() {
  76358. this._isEnabled = true;
  76359. this.leftColor = BABYLON.Color3.White();
  76360. this.rightColor = BABYLON.Color3.Black();
  76361. this.bias = 0;
  76362. this.power = 1;
  76363. }
  76364. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  76365. get: function () {
  76366. return this._isEnabled;
  76367. },
  76368. set: function (value) {
  76369. if (this._isEnabled === value) {
  76370. return;
  76371. }
  76372. this._isEnabled = value;
  76373. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  76374. },
  76375. enumerable: true,
  76376. configurable: true
  76377. });
  76378. FresnelParameters.prototype.clone = function () {
  76379. var newFresnelParameters = new FresnelParameters();
  76380. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  76381. return newFresnelParameters;
  76382. };
  76383. FresnelParameters.prototype.serialize = function () {
  76384. var serializationObject = {};
  76385. serializationObject.isEnabled = this.isEnabled;
  76386. serializationObject.leftColor = this.leftColor.asArray();
  76387. serializationObject.rightColor = this.rightColor.asArray();
  76388. serializationObject.bias = this.bias;
  76389. serializationObject.power = this.power;
  76390. return serializationObject;
  76391. };
  76392. FresnelParameters.Parse = function (parsedFresnelParameters) {
  76393. var fresnelParameters = new FresnelParameters();
  76394. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  76395. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  76396. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  76397. fresnelParameters.bias = parsedFresnelParameters.bias;
  76398. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  76399. return fresnelParameters;
  76400. };
  76401. return FresnelParameters;
  76402. }());
  76403. BABYLON.FresnelParameters = FresnelParameters;
  76404. })(BABYLON || (BABYLON = {}));
  76405. //# sourceMappingURL=babylon.fresnelParameters.js.map
  76406. var BABYLON;
  76407. (function (BABYLON) {
  76408. var MultiMaterial = /** @class */ (function (_super) {
  76409. __extends(MultiMaterial, _super);
  76410. function MultiMaterial(name, scene) {
  76411. var _this = _super.call(this, name, scene, true) || this;
  76412. scene.multiMaterials.push(_this);
  76413. _this.subMaterials = new Array();
  76414. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  76415. return _this;
  76416. }
  76417. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  76418. get: function () {
  76419. return this._subMaterials;
  76420. },
  76421. set: function (value) {
  76422. this._subMaterials = value;
  76423. this._hookArray(value);
  76424. },
  76425. enumerable: true,
  76426. configurable: true
  76427. });
  76428. MultiMaterial.prototype._hookArray = function (array) {
  76429. var _this = this;
  76430. var oldPush = array.push;
  76431. array.push = function () {
  76432. var items = [];
  76433. for (var _i = 0; _i < arguments.length; _i++) {
  76434. items[_i] = arguments[_i];
  76435. }
  76436. var result = oldPush.apply(array, items);
  76437. _this._markAllSubMeshesAsTexturesDirty();
  76438. return result;
  76439. };
  76440. var oldSplice = array.splice;
  76441. array.splice = function (index, deleteCount) {
  76442. var deleted = oldSplice.apply(array, [index, deleteCount]);
  76443. _this._markAllSubMeshesAsTexturesDirty();
  76444. return deleted;
  76445. };
  76446. };
  76447. // Properties
  76448. MultiMaterial.prototype.getSubMaterial = function (index) {
  76449. if (index < 0 || index >= this.subMaterials.length) {
  76450. return this.getScene().defaultMaterial;
  76451. }
  76452. return this.subMaterials[index];
  76453. };
  76454. MultiMaterial.prototype.getActiveTextures = function () {
  76455. var _a;
  76456. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  76457. if (subMaterial) {
  76458. return subMaterial.getActiveTextures();
  76459. }
  76460. else {
  76461. return [];
  76462. }
  76463. }));
  76464. };
  76465. // Methods
  76466. MultiMaterial.prototype.getClassName = function () {
  76467. return "MultiMaterial";
  76468. };
  76469. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  76470. for (var index = 0; index < this.subMaterials.length; index++) {
  76471. var subMaterial = this.subMaterials[index];
  76472. if (subMaterial) {
  76473. if (subMaterial.storeEffectOnSubMeshes) {
  76474. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  76475. return false;
  76476. }
  76477. continue;
  76478. }
  76479. if (!subMaterial.isReady(mesh)) {
  76480. return false;
  76481. }
  76482. }
  76483. }
  76484. return true;
  76485. };
  76486. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  76487. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  76488. for (var index = 0; index < this.subMaterials.length; index++) {
  76489. var subMaterial = null;
  76490. var current = this.subMaterials[index];
  76491. if (cloneChildren && current) {
  76492. subMaterial = current.clone(name + "-" + current.name);
  76493. }
  76494. else {
  76495. subMaterial = this.subMaterials[index];
  76496. }
  76497. newMultiMaterial.subMaterials.push(subMaterial);
  76498. }
  76499. return newMultiMaterial;
  76500. };
  76501. MultiMaterial.prototype.serialize = function () {
  76502. var serializationObject = {};
  76503. serializationObject.name = this.name;
  76504. serializationObject.id = this.id;
  76505. if (BABYLON.Tags) {
  76506. serializationObject.tags = BABYLON.Tags.GetTags(this);
  76507. }
  76508. serializationObject.materials = [];
  76509. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  76510. var subMat = this.subMaterials[matIndex];
  76511. if (subMat) {
  76512. serializationObject.materials.push(subMat.id);
  76513. }
  76514. else {
  76515. serializationObject.materials.push(null);
  76516. }
  76517. }
  76518. return serializationObject;
  76519. };
  76520. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  76521. var scene = this.getScene();
  76522. if (!scene) {
  76523. return;
  76524. }
  76525. var index = scene.multiMaterials.indexOf(this);
  76526. if (index >= 0) {
  76527. scene.multiMaterials.splice(index, 1);
  76528. }
  76529. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  76530. };
  76531. return MultiMaterial;
  76532. }(BABYLON.Material));
  76533. BABYLON.MultiMaterial = MultiMaterial;
  76534. })(BABYLON || (BABYLON = {}));
  76535. //# sourceMappingURL=babylon.multiMaterial.js.map
  76536. var BABYLON;
  76537. (function (BABYLON) {
  76538. /**
  76539. * Manage the touch inputs to control the movement of a free camera.
  76540. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  76541. */
  76542. var FreeCameraTouchInput = /** @class */ (function () {
  76543. function FreeCameraTouchInput() {
  76544. /**
  76545. * Defines the touch sensibility for rotation.
  76546. * The higher the faster.
  76547. */
  76548. this.touchAngularSensibility = 200000.0;
  76549. /**
  76550. * Defines the touch sensibility for move.
  76551. * The higher the faster.
  76552. */
  76553. this.touchMoveSensibility = 250.0;
  76554. this._offsetX = null;
  76555. this._offsetY = null;
  76556. this._pointerPressed = new Array();
  76557. }
  76558. /**
  76559. * Attach the input controls to a specific dom element to get the input from.
  76560. * @param element Defines the element the controls should be listened from
  76561. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  76562. */
  76563. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  76564. var _this = this;
  76565. var previousPosition = null;
  76566. if (this._pointerInput === undefined) {
  76567. this._onLostFocus = function (evt) {
  76568. _this._offsetX = null;
  76569. _this._offsetY = null;
  76570. };
  76571. this._pointerInput = function (p, s) {
  76572. var evt = p.event;
  76573. if (evt.pointerType === "mouse") {
  76574. return;
  76575. }
  76576. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  76577. if (!noPreventDefault) {
  76578. evt.preventDefault();
  76579. }
  76580. _this._pointerPressed.push(evt.pointerId);
  76581. if (_this._pointerPressed.length !== 1) {
  76582. return;
  76583. }
  76584. previousPosition = {
  76585. x: evt.clientX,
  76586. y: evt.clientY
  76587. };
  76588. }
  76589. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  76590. if (!noPreventDefault) {
  76591. evt.preventDefault();
  76592. }
  76593. var index = _this._pointerPressed.indexOf(evt.pointerId);
  76594. if (index === -1) {
  76595. return;
  76596. }
  76597. _this._pointerPressed.splice(index, 1);
  76598. if (index != 0) {
  76599. return;
  76600. }
  76601. previousPosition = null;
  76602. _this._offsetX = null;
  76603. _this._offsetY = null;
  76604. }
  76605. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  76606. if (!noPreventDefault) {
  76607. evt.preventDefault();
  76608. }
  76609. if (!previousPosition) {
  76610. return;
  76611. }
  76612. var index = _this._pointerPressed.indexOf(evt.pointerId);
  76613. if (index != 0) {
  76614. return;
  76615. }
  76616. _this._offsetX = evt.clientX - previousPosition.x;
  76617. _this._offsetY = -(evt.clientY - previousPosition.y);
  76618. }
  76619. };
  76620. }
  76621. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  76622. if (this._onLostFocus) {
  76623. element.addEventListener("blur", this._onLostFocus);
  76624. }
  76625. };
  76626. /**
  76627. * Detach the current controls from the specified dom element.
  76628. * @param element Defines the element to stop listening the inputs from
  76629. */
  76630. FreeCameraTouchInput.prototype.detachControl = function (element) {
  76631. if (this._pointerInput && element) {
  76632. if (this._observer) {
  76633. this.camera.getScene().onPointerObservable.remove(this._observer);
  76634. this._observer = null;
  76635. }
  76636. if (this._onLostFocus) {
  76637. element.removeEventListener("blur", this._onLostFocus);
  76638. this._onLostFocus = null;
  76639. }
  76640. this._pointerPressed = [];
  76641. this._offsetX = null;
  76642. this._offsetY = null;
  76643. }
  76644. };
  76645. /**
  76646. * Update the current camera state depending on the inputs that have been used this frame.
  76647. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  76648. */
  76649. FreeCameraTouchInput.prototype.checkInputs = function () {
  76650. if (this._offsetX && this._offsetY) {
  76651. var camera = this.camera;
  76652. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  76653. if (this._pointerPressed.length > 1) {
  76654. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  76655. }
  76656. else {
  76657. var speed = camera._computeLocalCameraSpeed();
  76658. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  76659. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  76660. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  76661. }
  76662. }
  76663. };
  76664. /**
  76665. * Gets the class name of the current intput.
  76666. * @returns the class name
  76667. */
  76668. FreeCameraTouchInput.prototype.getClassName = function () {
  76669. return "FreeCameraTouchInput";
  76670. };
  76671. /**
  76672. * Get the friendly name associated with the input class.
  76673. * @returns the input friendly name
  76674. */
  76675. FreeCameraTouchInput.prototype.getSimpleName = function () {
  76676. return "touch";
  76677. };
  76678. __decorate([
  76679. BABYLON.serialize()
  76680. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  76681. __decorate([
  76682. BABYLON.serialize()
  76683. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  76684. return FreeCameraTouchInput;
  76685. }());
  76686. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  76687. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  76688. })(BABYLON || (BABYLON = {}));
  76689. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  76690. var BABYLON;
  76691. (function (BABYLON) {
  76692. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  76693. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  76694. });
  76695. /**
  76696. * This represents a FPS type of camera controlled by touch.
  76697. * This is like a universal camera minus the Gamepad controls.
  76698. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  76699. */
  76700. var TouchCamera = /** @class */ (function (_super) {
  76701. __extends(TouchCamera, _super);
  76702. /**
  76703. * Instantiates a new touch camera.
  76704. * This represents a FPS type of camera controlled by touch.
  76705. * This is like a universal camera minus the Gamepad controls.
  76706. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  76707. * @param name Define the name of the camera in the scene
  76708. * @param position Define the start position of the camera in the scene
  76709. * @param scene Define the scene the camera belongs to
  76710. */
  76711. function TouchCamera(name, position, scene) {
  76712. var _this = _super.call(this, name, position, scene) || this;
  76713. _this.inputs.addTouch();
  76714. _this._setupInputs();
  76715. return _this;
  76716. }
  76717. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  76718. /**
  76719. * Defines the touch sensibility for rotation.
  76720. * The higher the faster.
  76721. */
  76722. get: function () {
  76723. var touch = this.inputs.attached["touch"];
  76724. if (touch)
  76725. return touch.touchAngularSensibility;
  76726. return 0;
  76727. },
  76728. set: function (value) {
  76729. var touch = this.inputs.attached["touch"];
  76730. if (touch)
  76731. touch.touchAngularSensibility = value;
  76732. },
  76733. enumerable: true,
  76734. configurable: true
  76735. });
  76736. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  76737. /**
  76738. * Defines the touch sensibility for move.
  76739. * The higher the faster.
  76740. */
  76741. get: function () {
  76742. var touch = this.inputs.attached["touch"];
  76743. if (touch)
  76744. return touch.touchMoveSensibility;
  76745. return 0;
  76746. },
  76747. set: function (value) {
  76748. var touch = this.inputs.attached["touch"];
  76749. if (touch)
  76750. touch.touchMoveSensibility = value;
  76751. },
  76752. enumerable: true,
  76753. configurable: true
  76754. });
  76755. /**
  76756. * Gets the current object class name.
  76757. * @return the class name
  76758. */
  76759. TouchCamera.prototype.getClassName = function () {
  76760. return "TouchCamera";
  76761. };
  76762. /** @hidden */
  76763. TouchCamera.prototype._setupInputs = function () {
  76764. var mouse = this.inputs.attached["mouse"];
  76765. if (mouse) {
  76766. mouse.touchEnabled = false;
  76767. }
  76768. };
  76769. return TouchCamera;
  76770. }(BABYLON.FreeCamera));
  76771. BABYLON.TouchCamera = TouchCamera;
  76772. })(BABYLON || (BABYLON = {}));
  76773. //# sourceMappingURL=babylon.touchCamera.js.map
  76774. var BABYLON;
  76775. (function (BABYLON) {
  76776. var ProceduralTexture = /** @class */ (function (_super) {
  76777. __extends(ProceduralTexture, _super);
  76778. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  76779. if (fallbackTexture === void 0) { fallbackTexture = null; }
  76780. if (generateMipMaps === void 0) { generateMipMaps = true; }
  76781. if (isCube === void 0) { isCube = false; }
  76782. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  76783. _this.isCube = isCube;
  76784. _this.isEnabled = true;
  76785. _this._currentRefreshId = -1;
  76786. _this._refreshRate = 1;
  76787. /**
  76788. * Event raised when the texture is generated
  76789. */
  76790. _this.onGeneratedObservable = new BABYLON.Observable();
  76791. _this._vertexBuffers = {};
  76792. _this._uniforms = new Array();
  76793. _this._samplers = new Array();
  76794. /** @hidden */
  76795. _this._textures = {};
  76796. _this._floats = {};
  76797. _this._ints = {};
  76798. _this._floatsArrays = {};
  76799. _this._colors3 = {};
  76800. _this._colors4 = {};
  76801. _this._vectors2 = {};
  76802. _this._vectors3 = {};
  76803. _this._matrices = {};
  76804. _this._fallbackTextureUsed = false;
  76805. _this._cachedDefines = "";
  76806. _this._contentUpdateId = -1;
  76807. scene = _this.getScene();
  76808. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  76809. if (!component) {
  76810. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  76811. scene._addComponent(component);
  76812. }
  76813. scene.proceduralTextures.push(_this);
  76814. _this._engine = scene.getEngine();
  76815. _this.name = name;
  76816. _this.isRenderTarget = true;
  76817. _this._size = size;
  76818. _this._generateMipMaps = generateMipMaps;
  76819. _this.setFragment(fragment);
  76820. _this._fallbackTexture = fallbackTexture;
  76821. if (isCube) {
  76822. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  76823. _this.setFloat("face", 0);
  76824. }
  76825. else {
  76826. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  76827. }
  76828. // VBO
  76829. var vertices = [];
  76830. vertices.push(1, 1);
  76831. vertices.push(-1, 1);
  76832. vertices.push(-1, -1);
  76833. vertices.push(1, -1);
  76834. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76835. _this._createIndexBuffer();
  76836. return _this;
  76837. }
  76838. /**
  76839. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  76840. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  76841. */
  76842. ProceduralTexture.prototype.getContent = function () {
  76843. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  76844. return this._contentData;
  76845. }
  76846. this._contentData = this.readPixels(0, 0, this._contentData);
  76847. this._contentUpdateId = this._currentRefreshId;
  76848. return this._contentData;
  76849. };
  76850. ProceduralTexture.prototype._createIndexBuffer = function () {
  76851. var engine = this._engine;
  76852. // Indices
  76853. var indices = [];
  76854. indices.push(0);
  76855. indices.push(1);
  76856. indices.push(2);
  76857. indices.push(0);
  76858. indices.push(2);
  76859. indices.push(3);
  76860. this._indexBuffer = engine.createIndexBuffer(indices);
  76861. };
  76862. /** @hidden */
  76863. ProceduralTexture.prototype._rebuild = function () {
  76864. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76865. if (vb) {
  76866. vb._rebuild();
  76867. }
  76868. this._createIndexBuffer();
  76869. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  76870. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  76871. }
  76872. };
  76873. ProceduralTexture.prototype.reset = function () {
  76874. if (this._effect === undefined) {
  76875. return;
  76876. }
  76877. var engine = this._engine;
  76878. engine._releaseEffect(this._effect);
  76879. };
  76880. ProceduralTexture.prototype._getDefines = function () {
  76881. return "";
  76882. };
  76883. ProceduralTexture.prototype.isReady = function () {
  76884. var _this = this;
  76885. var engine = this._engine;
  76886. var shaders;
  76887. if (!this._fragment) {
  76888. return false;
  76889. }
  76890. if (this._fallbackTextureUsed) {
  76891. return true;
  76892. }
  76893. var defines = this._getDefines();
  76894. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  76895. return true;
  76896. }
  76897. if (this._fragment.fragmentElement !== undefined) {
  76898. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  76899. }
  76900. else {
  76901. shaders = { vertex: "procedural", fragment: this._fragment };
  76902. }
  76903. this._cachedDefines = defines;
  76904. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  76905. _this.releaseInternalTexture();
  76906. if (_this._fallbackTexture) {
  76907. _this._texture = _this._fallbackTexture._texture;
  76908. if (_this._texture) {
  76909. _this._texture.incrementReferences();
  76910. }
  76911. }
  76912. _this._fallbackTextureUsed = true;
  76913. });
  76914. return this._effect.isReady();
  76915. };
  76916. ProceduralTexture.prototype.resetRefreshCounter = function () {
  76917. this._currentRefreshId = -1;
  76918. };
  76919. ProceduralTexture.prototype.setFragment = function (fragment) {
  76920. this._fragment = fragment;
  76921. };
  76922. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  76923. get: function () {
  76924. return this._refreshRate;
  76925. },
  76926. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  76927. set: function (value) {
  76928. this._refreshRate = value;
  76929. this.resetRefreshCounter();
  76930. },
  76931. enumerable: true,
  76932. configurable: true
  76933. });
  76934. /** @hidden */
  76935. ProceduralTexture.prototype._shouldRender = function () {
  76936. if (!this.isEnabled || !this.isReady() || !this._texture) {
  76937. if (this._texture) {
  76938. this._texture.isReady = false;
  76939. }
  76940. return false;
  76941. }
  76942. if (this._fallbackTextureUsed) {
  76943. return false;
  76944. }
  76945. if (this._currentRefreshId === -1) { // At least render once
  76946. this._currentRefreshId = 1;
  76947. return true;
  76948. }
  76949. if (this.refreshRate === this._currentRefreshId) {
  76950. this._currentRefreshId = 1;
  76951. return true;
  76952. }
  76953. this._currentRefreshId++;
  76954. return false;
  76955. };
  76956. ProceduralTexture.prototype.getRenderSize = function () {
  76957. return this._size;
  76958. };
  76959. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  76960. if (this._fallbackTextureUsed) {
  76961. return;
  76962. }
  76963. this.releaseInternalTexture();
  76964. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  76965. // Update properties
  76966. this._size = size;
  76967. this._generateMipMaps = generateMipMaps;
  76968. };
  76969. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  76970. if (this._uniforms.indexOf(uniformName) === -1) {
  76971. this._uniforms.push(uniformName);
  76972. }
  76973. };
  76974. ProceduralTexture.prototype.setTexture = function (name, texture) {
  76975. if (this._samplers.indexOf(name) === -1) {
  76976. this._samplers.push(name);
  76977. }
  76978. this._textures[name] = texture;
  76979. return this;
  76980. };
  76981. ProceduralTexture.prototype.setFloat = function (name, value) {
  76982. this._checkUniform(name);
  76983. this._floats[name] = value;
  76984. return this;
  76985. };
  76986. /**
  76987. * Set the value of an uniform to an integer value
  76988. * @param name defines the name of the uniform
  76989. * @param value defines the value to set
  76990. * @returns the current procedural texture
  76991. */
  76992. ProceduralTexture.prototype.setInt = function (name, value) {
  76993. this._checkUniform(name);
  76994. this._ints[name] = value;
  76995. return this;
  76996. };
  76997. ProceduralTexture.prototype.setFloats = function (name, value) {
  76998. this._checkUniform(name);
  76999. this._floatsArrays[name] = value;
  77000. return this;
  77001. };
  77002. ProceduralTexture.prototype.setColor3 = function (name, value) {
  77003. this._checkUniform(name);
  77004. this._colors3[name] = value;
  77005. return this;
  77006. };
  77007. ProceduralTexture.prototype.setColor4 = function (name, value) {
  77008. this._checkUniform(name);
  77009. this._colors4[name] = value;
  77010. return this;
  77011. };
  77012. ProceduralTexture.prototype.setVector2 = function (name, value) {
  77013. this._checkUniform(name);
  77014. this._vectors2[name] = value;
  77015. return this;
  77016. };
  77017. ProceduralTexture.prototype.setVector3 = function (name, value) {
  77018. this._checkUniform(name);
  77019. this._vectors3[name] = value;
  77020. return this;
  77021. };
  77022. ProceduralTexture.prototype.setMatrix = function (name, value) {
  77023. this._checkUniform(name);
  77024. this._matrices[name] = value;
  77025. return this;
  77026. };
  77027. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  77028. var scene = this.getScene();
  77029. if (!scene) {
  77030. return;
  77031. }
  77032. var engine = this._engine;
  77033. // Render
  77034. engine.enableEffect(this._effect);
  77035. engine.setState(false);
  77036. // Texture
  77037. for (var name in this._textures) {
  77038. this._effect.setTexture(name, this._textures[name]);
  77039. }
  77040. // Float
  77041. for (name in this._ints) {
  77042. this._effect.setInt(name, this._ints[name]);
  77043. }
  77044. // Float
  77045. for (name in this._floats) {
  77046. this._effect.setFloat(name, this._floats[name]);
  77047. }
  77048. // Floats
  77049. for (name in this._floatsArrays) {
  77050. this._effect.setArray(name, this._floatsArrays[name]);
  77051. }
  77052. // Color3
  77053. for (name in this._colors3) {
  77054. this._effect.setColor3(name, this._colors3[name]);
  77055. }
  77056. // Color4
  77057. for (name in this._colors4) {
  77058. var color = this._colors4[name];
  77059. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  77060. }
  77061. // Vector2
  77062. for (name in this._vectors2) {
  77063. this._effect.setVector2(name, this._vectors2[name]);
  77064. }
  77065. // Vector3
  77066. for (name in this._vectors3) {
  77067. this._effect.setVector3(name, this._vectors3[name]);
  77068. }
  77069. // Matrix
  77070. for (name in this._matrices) {
  77071. this._effect.setMatrix(name, this._matrices[name]);
  77072. }
  77073. if (!this._texture) {
  77074. return;
  77075. }
  77076. if (this.isCube) {
  77077. for (var face = 0; face < 6; face++) {
  77078. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  77079. // VBOs
  77080. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  77081. this._effect.setFloat("face", face);
  77082. // Clear
  77083. engine.clear(scene.clearColor, true, true, true);
  77084. // Draw order
  77085. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77086. // Mipmaps
  77087. if (face === 5) {
  77088. engine.generateMipMapsForCubemap(this._texture);
  77089. }
  77090. }
  77091. }
  77092. else {
  77093. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  77094. // VBOs
  77095. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  77096. // Clear
  77097. engine.clear(scene.clearColor, true, true, true);
  77098. // Draw order
  77099. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77100. }
  77101. // Unbind
  77102. engine.unBindFramebuffer(this._texture, this.isCube);
  77103. if (this.onGenerated) {
  77104. this.onGenerated();
  77105. }
  77106. this.onGeneratedObservable.notifyObservers(this);
  77107. };
  77108. ProceduralTexture.prototype.clone = function () {
  77109. var textureSize = this.getSize();
  77110. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  77111. // Base texture
  77112. newTexture.hasAlpha = this.hasAlpha;
  77113. newTexture.level = this.level;
  77114. // RenderTarget Texture
  77115. newTexture.coordinatesMode = this.coordinatesMode;
  77116. return newTexture;
  77117. };
  77118. ProceduralTexture.prototype.dispose = function () {
  77119. var scene = this.getScene();
  77120. if (!scene) {
  77121. return;
  77122. }
  77123. var index = scene.proceduralTextures.indexOf(this);
  77124. if (index >= 0) {
  77125. scene.proceduralTextures.splice(index, 1);
  77126. }
  77127. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77128. if (vertexBuffer) {
  77129. vertexBuffer.dispose();
  77130. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77131. }
  77132. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  77133. this._indexBuffer = null;
  77134. }
  77135. _super.prototype.dispose.call(this);
  77136. };
  77137. __decorate([
  77138. BABYLON.serialize()
  77139. ], ProceduralTexture.prototype, "_size", void 0);
  77140. __decorate([
  77141. BABYLON.serialize()
  77142. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  77143. __decorate([
  77144. BABYLON.serialize()
  77145. ], ProceduralTexture.prototype, "isEnabled", void 0);
  77146. __decorate([
  77147. BABYLON.serialize()
  77148. ], ProceduralTexture.prototype, "refreshRate", null);
  77149. return ProceduralTexture;
  77150. }(BABYLON.Texture));
  77151. BABYLON.ProceduralTexture = ProceduralTexture;
  77152. })(BABYLON || (BABYLON = {}));
  77153. //# sourceMappingURL=babylon.proceduralTexture.js.map
  77154. var BABYLON;
  77155. (function (BABYLON) {
  77156. /**
  77157. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  77158. * in a given scene.
  77159. */
  77160. var ProceduralTextureSceneComponent = /** @class */ (function () {
  77161. /**
  77162. * Creates a new instance of the component for the given scene
  77163. * @param scene Defines the scene to register the component in
  77164. */
  77165. function ProceduralTextureSceneComponent(scene) {
  77166. /**
  77167. * The component name helpfull to identify the component in the list of scene components.
  77168. */
  77169. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  77170. this.scene = scene;
  77171. this.scene.proceduralTextures = new Array();
  77172. scene.layers = new Array();
  77173. }
  77174. /**
  77175. * Registers the component in a given scene
  77176. */
  77177. ProceduralTextureSceneComponent.prototype.register = function () {
  77178. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  77179. };
  77180. /**
  77181. * Rebuilds the elements related to this component in case of
  77182. * context lost for instance.
  77183. */
  77184. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  77185. // Nothing to do here.
  77186. };
  77187. /**
  77188. * Disposes the component and the associated ressources.
  77189. */
  77190. ProceduralTextureSceneComponent.prototype.dispose = function () {
  77191. // Nothing to do here.
  77192. };
  77193. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  77194. if (this.scene.proceduralTexturesEnabled) {
  77195. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  77196. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  77197. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  77198. if (proceduralTexture._shouldRender()) {
  77199. proceduralTexture.render();
  77200. }
  77201. }
  77202. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  77203. }
  77204. };
  77205. return ProceduralTextureSceneComponent;
  77206. }());
  77207. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  77208. })(BABYLON || (BABYLON = {}));
  77209. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  77210. var BABYLON;
  77211. (function (BABYLON) {
  77212. var CustomProceduralTexture = /** @class */ (function (_super) {
  77213. __extends(CustomProceduralTexture, _super);
  77214. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  77215. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  77216. _this._animate = true;
  77217. _this._time = 0;
  77218. _this._texturePath = texturePath;
  77219. //Try to load json
  77220. _this.loadJson(texturePath);
  77221. _this.refreshRate = 1;
  77222. return _this;
  77223. }
  77224. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  77225. var _this = this;
  77226. var noConfigFile = function () {
  77227. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  77228. try {
  77229. _this.setFragment(_this._texturePath);
  77230. }
  77231. catch (ex) {
  77232. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  77233. }
  77234. };
  77235. var configFileUrl = jsonUrl + "/config.json";
  77236. var xhr = new XMLHttpRequest();
  77237. xhr.open("GET", configFileUrl, true);
  77238. xhr.addEventListener("load", function () {
  77239. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  77240. try {
  77241. _this._config = JSON.parse(xhr.response);
  77242. _this.updateShaderUniforms();
  77243. _this.updateTextures();
  77244. _this.setFragment(_this._texturePath + "/custom");
  77245. _this._animate = _this._config.animate;
  77246. _this.refreshRate = _this._config.refreshrate;
  77247. }
  77248. catch (ex) {
  77249. noConfigFile();
  77250. }
  77251. }
  77252. else {
  77253. noConfigFile();
  77254. }
  77255. }, false);
  77256. xhr.addEventListener("error", function () {
  77257. noConfigFile();
  77258. }, false);
  77259. try {
  77260. xhr.send();
  77261. }
  77262. catch (ex) {
  77263. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  77264. }
  77265. };
  77266. CustomProceduralTexture.prototype.isReady = function () {
  77267. if (!_super.prototype.isReady.call(this)) {
  77268. return false;
  77269. }
  77270. for (var name in this._textures) {
  77271. var texture = this._textures[name];
  77272. if (!texture.isReady()) {
  77273. return false;
  77274. }
  77275. }
  77276. return true;
  77277. };
  77278. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  77279. var scene = this.getScene();
  77280. if (this._animate && scene) {
  77281. this._time += scene.getAnimationRatio() * 0.03;
  77282. this.updateShaderUniforms();
  77283. }
  77284. _super.prototype.render.call(this, useCameraPostProcess);
  77285. };
  77286. CustomProceduralTexture.prototype.updateTextures = function () {
  77287. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  77288. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  77289. }
  77290. };
  77291. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  77292. if (this._config) {
  77293. for (var j = 0; j < this._config.uniforms.length; j++) {
  77294. var uniform = this._config.uniforms[j];
  77295. switch (uniform.type) {
  77296. case "float":
  77297. this.setFloat(uniform.name, uniform.value);
  77298. break;
  77299. case "color3":
  77300. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  77301. break;
  77302. case "color4":
  77303. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  77304. break;
  77305. case "vector2":
  77306. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  77307. break;
  77308. case "vector3":
  77309. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  77310. break;
  77311. }
  77312. }
  77313. }
  77314. this.setFloat("time", this._time);
  77315. };
  77316. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  77317. get: function () {
  77318. return this._animate;
  77319. },
  77320. set: function (value) {
  77321. this._animate = value;
  77322. },
  77323. enumerable: true,
  77324. configurable: true
  77325. });
  77326. return CustomProceduralTexture;
  77327. }(BABYLON.ProceduralTexture));
  77328. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  77329. })(BABYLON || (BABYLON = {}));
  77330. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  77331. var BABYLON;
  77332. (function (BABYLON) {
  77333. /**
  77334. * Manage the gamepad inputs to control a free camera.
  77335. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  77336. */
  77337. var FreeCameraGamepadInput = /** @class */ (function () {
  77338. function FreeCameraGamepadInput() {
  77339. /**
  77340. * Defines the gamepad rotation sensiblity.
  77341. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  77342. */
  77343. this.gamepadAngularSensibility = 200;
  77344. /**
  77345. * Defines the gamepad move sensiblity.
  77346. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  77347. */
  77348. this.gamepadMoveSensibility = 40;
  77349. this._cameraTransform = BABYLON.Matrix.Identity();
  77350. this._deltaTransform = BABYLON.Vector3.Zero();
  77351. this._vector3 = BABYLON.Vector3.Zero();
  77352. this._vector2 = BABYLON.Vector2.Zero();
  77353. }
  77354. /**
  77355. * Attach the input controls to a specific dom element to get the input from.
  77356. * @param element Defines the element the controls should be listened from
  77357. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  77358. */
  77359. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  77360. var _this = this;
  77361. var manager = this.camera.getScene().gamepadManager;
  77362. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  77363. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  77364. // prioritize XBOX gamepads.
  77365. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  77366. _this.gamepad = gamepad;
  77367. }
  77368. }
  77369. });
  77370. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  77371. if (_this.gamepad === gamepad) {
  77372. _this.gamepad = null;
  77373. }
  77374. });
  77375. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  77376. };
  77377. /**
  77378. * Detach the current controls from the specified dom element.
  77379. * @param element Defines the element to stop listening the inputs from
  77380. */
  77381. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  77382. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  77383. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  77384. this.gamepad = null;
  77385. };
  77386. /**
  77387. * Update the current camera state depending on the inputs that have been used this frame.
  77388. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  77389. */
  77390. FreeCameraGamepadInput.prototype.checkInputs = function () {
  77391. if (this.gamepad && this.gamepad.leftStick) {
  77392. var camera = this.camera;
  77393. var LSValues = this.gamepad.leftStick;
  77394. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  77395. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  77396. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  77397. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  77398. var RSValues = this.gamepad.rightStick;
  77399. if (RSValues) {
  77400. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  77401. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  77402. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  77403. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  77404. }
  77405. else {
  77406. RSValues = { x: 0, y: 0 };
  77407. }
  77408. if (!camera.rotationQuaternion) {
  77409. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  77410. }
  77411. else {
  77412. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  77413. }
  77414. var speed = camera._computeLocalCameraSpeed() * 50.0;
  77415. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  77416. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  77417. camera.cameraDirection.addInPlace(this._deltaTransform);
  77418. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  77419. camera.cameraRotation.addInPlace(this._vector2);
  77420. }
  77421. };
  77422. /**
  77423. * Gets the class name of the current intput.
  77424. * @returns the class name
  77425. */
  77426. FreeCameraGamepadInput.prototype.getClassName = function () {
  77427. return "FreeCameraGamepadInput";
  77428. };
  77429. /**
  77430. * Get the friendly name associated with the input class.
  77431. * @returns the input friendly name
  77432. */
  77433. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  77434. return "gamepad";
  77435. };
  77436. __decorate([
  77437. BABYLON.serialize()
  77438. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  77439. __decorate([
  77440. BABYLON.serialize()
  77441. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  77442. return FreeCameraGamepadInput;
  77443. }());
  77444. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  77445. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  77446. })(BABYLON || (BABYLON = {}));
  77447. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  77448. var BABYLON;
  77449. (function (BABYLON) {
  77450. /**
  77451. * Manage the gamepad inputs to control an arc rotate camera.
  77452. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  77453. */
  77454. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  77455. function ArcRotateCameraGamepadInput() {
  77456. /**
  77457. * Defines the gamepad rotation sensiblity.
  77458. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  77459. */
  77460. this.gamepadRotationSensibility = 80;
  77461. /**
  77462. * Defines the gamepad move sensiblity.
  77463. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  77464. */
  77465. this.gamepadMoveSensibility = 40;
  77466. }
  77467. /**
  77468. * Attach the input controls to a specific dom element to get the input from.
  77469. * @param element Defines the element the controls should be listened from
  77470. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  77471. */
  77472. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  77473. var _this = this;
  77474. var manager = this.camera.getScene().gamepadManager;
  77475. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  77476. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  77477. // prioritize XBOX gamepads.
  77478. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  77479. _this.gamepad = gamepad;
  77480. }
  77481. }
  77482. });
  77483. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  77484. if (_this.gamepad === gamepad) {
  77485. _this.gamepad = null;
  77486. }
  77487. });
  77488. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  77489. };
  77490. /**
  77491. * Detach the current controls from the specified dom element.
  77492. * @param element Defines the element to stop listening the inputs from
  77493. */
  77494. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  77495. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  77496. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  77497. this.gamepad = null;
  77498. };
  77499. /**
  77500. * Update the current camera state depending on the inputs that have been used this frame.
  77501. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  77502. */
  77503. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  77504. if (this.gamepad) {
  77505. var camera = this.camera;
  77506. var RSValues = this.gamepad.rightStick;
  77507. if (RSValues) {
  77508. if (RSValues.x != 0) {
  77509. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  77510. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  77511. camera.inertialAlphaOffset += normalizedRX;
  77512. }
  77513. }
  77514. if (RSValues.y != 0) {
  77515. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  77516. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  77517. camera.inertialBetaOffset += normalizedRY;
  77518. }
  77519. }
  77520. }
  77521. var LSValues = this.gamepad.leftStick;
  77522. if (LSValues && LSValues.y != 0) {
  77523. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  77524. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  77525. this.camera.inertialRadiusOffset -= normalizedLY;
  77526. }
  77527. }
  77528. }
  77529. };
  77530. /**
  77531. * Gets the class name of the current intput.
  77532. * @returns the class name
  77533. */
  77534. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  77535. return "ArcRotateCameraGamepadInput";
  77536. };
  77537. /**
  77538. * Get the friendly name associated with the input class.
  77539. * @returns the input friendly name
  77540. */
  77541. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  77542. return "gamepad";
  77543. };
  77544. __decorate([
  77545. BABYLON.serialize()
  77546. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  77547. __decorate([
  77548. BABYLON.serialize()
  77549. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  77550. return ArcRotateCameraGamepadInput;
  77551. }());
  77552. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  77553. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  77554. })(BABYLON || (BABYLON = {}));
  77555. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  77556. var BABYLON;
  77557. (function (BABYLON) {
  77558. /**
  77559. * Manager for handling gamepads
  77560. */
  77561. var GamepadManager = /** @class */ (function () {
  77562. /**
  77563. * Initializes the gamepad manager
  77564. * @param _scene BabylonJS scene
  77565. */
  77566. function GamepadManager(_scene) {
  77567. var _this = this;
  77568. this._scene = _scene;
  77569. this._babylonGamepads = [];
  77570. this._oneGamepadConnected = false;
  77571. /** @hidden */
  77572. this._isMonitoring = false;
  77573. /**
  77574. * observable to be triggered when the gamepad controller has been disconnected
  77575. */
  77576. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  77577. if (!BABYLON.Tools.IsWindowObjectExist()) {
  77578. this._gamepadEventSupported = false;
  77579. }
  77580. else {
  77581. this._gamepadEventSupported = 'GamepadEvent' in window;
  77582. this._gamepadSupport = (navigator.getGamepads ||
  77583. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  77584. }
  77585. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  77586. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  77587. for (var i in _this._babylonGamepads) {
  77588. var gamepad = _this._babylonGamepads[i];
  77589. if (gamepad && gamepad._isConnected) {
  77590. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  77591. }
  77592. }
  77593. });
  77594. this._onGamepadConnectedEvent = function (evt) {
  77595. var gamepad = evt.gamepad;
  77596. if (gamepad.index in _this._babylonGamepads) {
  77597. if (_this._babylonGamepads[gamepad.index].isConnected) {
  77598. return;
  77599. }
  77600. }
  77601. var newGamepad;
  77602. if (_this._babylonGamepads[gamepad.index]) {
  77603. newGamepad = _this._babylonGamepads[gamepad.index];
  77604. newGamepad.browserGamepad = gamepad;
  77605. newGamepad._isConnected = true;
  77606. }
  77607. else {
  77608. newGamepad = _this._addNewGamepad(gamepad);
  77609. }
  77610. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  77611. _this._startMonitoringGamepads();
  77612. };
  77613. this._onGamepadDisconnectedEvent = function (evt) {
  77614. var gamepad = evt.gamepad;
  77615. // Remove the gamepad from the list of gamepads to monitor.
  77616. for (var i in _this._babylonGamepads) {
  77617. if (_this._babylonGamepads[i].index === gamepad.index) {
  77618. var disconnectedGamepad = _this._babylonGamepads[i];
  77619. disconnectedGamepad._isConnected = false;
  77620. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  77621. break;
  77622. }
  77623. }
  77624. };
  77625. if (this._gamepadSupport) {
  77626. //first add already-connected gamepads
  77627. this._updateGamepadObjects();
  77628. if (this._babylonGamepads.length) {
  77629. this._startMonitoringGamepads();
  77630. }
  77631. // Checking if the gamepad connected event is supported (like in Firefox)
  77632. if (this._gamepadEventSupported) {
  77633. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  77634. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  77635. }
  77636. else {
  77637. this._startMonitoringGamepads();
  77638. }
  77639. }
  77640. }
  77641. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  77642. /**
  77643. * The gamepads in the game pad manager
  77644. */
  77645. get: function () {
  77646. return this._babylonGamepads;
  77647. },
  77648. enumerable: true,
  77649. configurable: true
  77650. });
  77651. /**
  77652. * Get the gamepad controllers based on type
  77653. * @param type The type of gamepad controller
  77654. * @returns Nullable gamepad
  77655. */
  77656. GamepadManager.prototype.getGamepadByType = function (type) {
  77657. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  77658. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  77659. var gamepad = _a[_i];
  77660. if (gamepad && gamepad.type === type) {
  77661. return gamepad;
  77662. }
  77663. }
  77664. return null;
  77665. };
  77666. /**
  77667. * Disposes the gamepad manager
  77668. */
  77669. GamepadManager.prototype.dispose = function () {
  77670. if (this._gamepadEventSupported) {
  77671. if (this._onGamepadConnectedEvent) {
  77672. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  77673. }
  77674. if (this._onGamepadDisconnectedEvent) {
  77675. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  77676. }
  77677. this._onGamepadConnectedEvent = null;
  77678. this._onGamepadDisconnectedEvent = null;
  77679. }
  77680. this._babylonGamepads.forEach(function (gamepad) {
  77681. gamepad.dispose();
  77682. });
  77683. this.onGamepadConnectedObservable.clear();
  77684. this.onGamepadDisconnectedObservable.clear();
  77685. this._oneGamepadConnected = false;
  77686. this._stopMonitoringGamepads();
  77687. this._babylonGamepads = [];
  77688. };
  77689. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  77690. if (!this._oneGamepadConnected) {
  77691. this._oneGamepadConnected = true;
  77692. }
  77693. var newGamepad;
  77694. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  77695. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  77696. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  77697. }
  77698. // if pose is supported, use the (WebVR) pose enabled controller
  77699. else if (gamepad.pose) {
  77700. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  77701. }
  77702. else {
  77703. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  77704. }
  77705. this._babylonGamepads[newGamepad.index] = newGamepad;
  77706. return newGamepad;
  77707. };
  77708. GamepadManager.prototype._startMonitoringGamepads = function () {
  77709. if (!this._isMonitoring) {
  77710. this._isMonitoring = true;
  77711. //back-comp
  77712. if (!this._scene) {
  77713. this._checkGamepadsStatus();
  77714. }
  77715. }
  77716. };
  77717. GamepadManager.prototype._stopMonitoringGamepads = function () {
  77718. this._isMonitoring = false;
  77719. };
  77720. /** @hidden */
  77721. GamepadManager.prototype._checkGamepadsStatus = function () {
  77722. var _this = this;
  77723. // Hack to be compatible Chrome
  77724. this._updateGamepadObjects();
  77725. for (var i in this._babylonGamepads) {
  77726. var gamepad = this._babylonGamepads[i];
  77727. if (!gamepad || !gamepad.isConnected) {
  77728. continue;
  77729. }
  77730. gamepad.update();
  77731. }
  77732. if (this._isMonitoring && !this._scene) {
  77733. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  77734. }
  77735. };
  77736. // This function is called only on Chrome, which does not properly support
  77737. // connection/disconnection events and forces you to recopy again the gamepad object
  77738. GamepadManager.prototype._updateGamepadObjects = function () {
  77739. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  77740. for (var i = 0; i < gamepads.length; i++) {
  77741. var gamepad = gamepads[i];
  77742. if (gamepad) {
  77743. if (!this._babylonGamepads[gamepad.index]) {
  77744. var newGamepad = this._addNewGamepad(gamepad);
  77745. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  77746. }
  77747. else {
  77748. // Forced to copy again this object for Chrome for unknown reason
  77749. this._babylonGamepads[i].browserGamepad = gamepad;
  77750. if (!this._babylonGamepads[i].isConnected) {
  77751. this._babylonGamepads[i]._isConnected = true;
  77752. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  77753. }
  77754. }
  77755. }
  77756. }
  77757. };
  77758. return GamepadManager;
  77759. }());
  77760. BABYLON.GamepadManager = GamepadManager;
  77761. })(BABYLON || (BABYLON = {}));
  77762. //# sourceMappingURL=babylon.gamepadManager.js.map
  77763. var BABYLON;
  77764. (function (BABYLON) {
  77765. /**
  77766. * Represents a gamepad control stick position
  77767. */
  77768. var StickValues = /** @class */ (function () {
  77769. /**
  77770. * Initializes the gamepad x and y control stick values
  77771. * @param x The x component of the gamepad control stick value
  77772. * @param y The y component of the gamepad control stick value
  77773. */
  77774. function StickValues(
  77775. /**
  77776. * The x component of the control stick
  77777. */
  77778. x,
  77779. /**
  77780. * The y component of the control stick
  77781. */
  77782. y) {
  77783. this.x = x;
  77784. this.y = y;
  77785. }
  77786. return StickValues;
  77787. }());
  77788. BABYLON.StickValues = StickValues;
  77789. /**
  77790. * Represents a gamepad
  77791. */
  77792. var Gamepad = /** @class */ (function () {
  77793. /**
  77794. * Initializes the gamepad
  77795. * @param id The id of the gamepad
  77796. * @param index The index of the gamepad
  77797. * @param browserGamepad The browser gamepad
  77798. * @param leftStickX The x component of the left joystick
  77799. * @param leftStickY The y component of the left joystick
  77800. * @param rightStickX The x component of the right joystick
  77801. * @param rightStickY The y component of the right joystick
  77802. */
  77803. function Gamepad(
  77804. /**
  77805. * The id of the gamepad
  77806. */
  77807. id,
  77808. /**
  77809. * The index of the gamepad
  77810. */
  77811. index,
  77812. /**
  77813. * The browser gamepad
  77814. */
  77815. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  77816. if (leftStickX === void 0) { leftStickX = 0; }
  77817. if (leftStickY === void 0) { leftStickY = 1; }
  77818. if (rightStickX === void 0) { rightStickX = 2; }
  77819. if (rightStickY === void 0) { rightStickY = 3; }
  77820. this.id = id;
  77821. this.index = index;
  77822. this.browserGamepad = browserGamepad;
  77823. this._leftStick = { x: 0, y: 0 };
  77824. this._rightStick = { x: 0, y: 0 };
  77825. /** @hidden */
  77826. this._isConnected = true;
  77827. /**
  77828. * Specifies whether the left control stick should be Y-inverted
  77829. */
  77830. this._invertLeftStickY = false;
  77831. this.type = Gamepad.GAMEPAD;
  77832. this._leftStickAxisX = leftStickX;
  77833. this._leftStickAxisY = leftStickY;
  77834. this._rightStickAxisX = rightStickX;
  77835. this._rightStickAxisY = rightStickY;
  77836. if (this.browserGamepad.axes.length >= 2) {
  77837. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  77838. }
  77839. if (this.browserGamepad.axes.length >= 4) {
  77840. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  77841. }
  77842. }
  77843. Object.defineProperty(Gamepad.prototype, "isConnected", {
  77844. /**
  77845. * Specifies if the gamepad has been connected
  77846. */
  77847. get: function () {
  77848. return this._isConnected;
  77849. },
  77850. enumerable: true,
  77851. configurable: true
  77852. });
  77853. /**
  77854. * Callback triggered when the left joystick has changed
  77855. * @param callback
  77856. */
  77857. Gamepad.prototype.onleftstickchanged = function (callback) {
  77858. this._onleftstickchanged = callback;
  77859. };
  77860. /**
  77861. * Callback triggered when the right joystick has changed
  77862. * @param callback
  77863. */
  77864. Gamepad.prototype.onrightstickchanged = function (callback) {
  77865. this._onrightstickchanged = callback;
  77866. };
  77867. Object.defineProperty(Gamepad.prototype, "leftStick", {
  77868. /**
  77869. * Gets the left joystick
  77870. */
  77871. get: function () {
  77872. return this._leftStick;
  77873. },
  77874. /**
  77875. * Sets the left joystick values
  77876. */
  77877. set: function (newValues) {
  77878. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  77879. this._onleftstickchanged(newValues);
  77880. }
  77881. this._leftStick = newValues;
  77882. },
  77883. enumerable: true,
  77884. configurable: true
  77885. });
  77886. Object.defineProperty(Gamepad.prototype, "rightStick", {
  77887. /**
  77888. * Gets the right joystick
  77889. */
  77890. get: function () {
  77891. return this._rightStick;
  77892. },
  77893. /**
  77894. * Sets the right joystick value
  77895. */
  77896. set: function (newValues) {
  77897. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  77898. this._onrightstickchanged(newValues);
  77899. }
  77900. this._rightStick = newValues;
  77901. },
  77902. enumerable: true,
  77903. configurable: true
  77904. });
  77905. /**
  77906. * Updates the gamepad joystick positions
  77907. */
  77908. Gamepad.prototype.update = function () {
  77909. if (this._leftStick) {
  77910. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  77911. if (this._invertLeftStickY) {
  77912. this.leftStick.y *= -1;
  77913. }
  77914. }
  77915. if (this._rightStick) {
  77916. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  77917. }
  77918. };
  77919. /**
  77920. * Disposes the gamepad
  77921. */
  77922. Gamepad.prototype.dispose = function () {
  77923. };
  77924. /**
  77925. * Represents a gamepad controller
  77926. */
  77927. Gamepad.GAMEPAD = 0;
  77928. /**
  77929. * Represents a generic controller
  77930. */
  77931. Gamepad.GENERIC = 1;
  77932. /**
  77933. * Represents an XBox controller
  77934. */
  77935. Gamepad.XBOX = 2;
  77936. /**
  77937. * Represents a pose-enabled controller
  77938. */
  77939. Gamepad.POSE_ENABLED = 3;
  77940. return Gamepad;
  77941. }());
  77942. BABYLON.Gamepad = Gamepad;
  77943. /**
  77944. * Represents a generic gamepad
  77945. */
  77946. var GenericPad = /** @class */ (function (_super) {
  77947. __extends(GenericPad, _super);
  77948. /**
  77949. * Initializes the generic gamepad
  77950. * @param id The id of the generic gamepad
  77951. * @param index The index of the generic gamepad
  77952. * @param browserGamepad The browser gamepad
  77953. */
  77954. function GenericPad(id, index, browserGamepad) {
  77955. var _this = _super.call(this, id, index, browserGamepad) || this;
  77956. /**
  77957. * Observable triggered when a button has been pressed
  77958. */
  77959. _this.onButtonDownObservable = new BABYLON.Observable();
  77960. /**
  77961. * Observable triggered when a button has been released
  77962. */
  77963. _this.onButtonUpObservable = new BABYLON.Observable();
  77964. _this.type = Gamepad.GENERIC;
  77965. _this._buttons = new Array(browserGamepad.buttons.length);
  77966. return _this;
  77967. }
  77968. /**
  77969. * Callback triggered when a button has been pressed
  77970. * @param callback Called when a button has been pressed
  77971. */
  77972. GenericPad.prototype.onbuttondown = function (callback) {
  77973. this._onbuttondown = callback;
  77974. };
  77975. /**
  77976. * Callback triggered when a button has been released
  77977. * @param callback Called when a button has been released
  77978. */
  77979. GenericPad.prototype.onbuttonup = function (callback) {
  77980. this._onbuttonup = callback;
  77981. };
  77982. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  77983. if (newValue !== currentValue) {
  77984. if (newValue === 1) {
  77985. if (this._onbuttondown) {
  77986. this._onbuttondown(buttonIndex);
  77987. }
  77988. this.onButtonDownObservable.notifyObservers(buttonIndex);
  77989. }
  77990. if (newValue === 0) {
  77991. if (this._onbuttonup) {
  77992. this._onbuttonup(buttonIndex);
  77993. }
  77994. this.onButtonUpObservable.notifyObservers(buttonIndex);
  77995. }
  77996. }
  77997. return newValue;
  77998. };
  77999. /**
  78000. * Updates the generic gamepad
  78001. */
  78002. GenericPad.prototype.update = function () {
  78003. _super.prototype.update.call(this);
  78004. for (var index = 0; index < this._buttons.length; index++) {
  78005. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  78006. }
  78007. };
  78008. /**
  78009. * Disposes the generic gamepad
  78010. */
  78011. GenericPad.prototype.dispose = function () {
  78012. _super.prototype.dispose.call(this);
  78013. this.onButtonDownObservable.clear();
  78014. this.onButtonUpObservable.clear();
  78015. };
  78016. return GenericPad;
  78017. }(Gamepad));
  78018. BABYLON.GenericPad = GenericPad;
  78019. })(BABYLON || (BABYLON = {}));
  78020. //# sourceMappingURL=babylon.gamepad.js.map
  78021. var BABYLON;
  78022. (function (BABYLON) {
  78023. /**
  78024. * Defines supported buttons for XBox360 compatible gamepads
  78025. */
  78026. var Xbox360Button;
  78027. (function (Xbox360Button) {
  78028. /** A */
  78029. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  78030. /** B */
  78031. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  78032. /** X */
  78033. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  78034. /** Y */
  78035. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  78036. /** Start */
  78037. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  78038. /** Back */
  78039. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  78040. /** Left button */
  78041. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  78042. /** Right button */
  78043. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  78044. /** Left stick */
  78045. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  78046. /** Right stick */
  78047. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  78048. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  78049. /** Defines values for XBox360 DPad */
  78050. var Xbox360Dpad;
  78051. (function (Xbox360Dpad) {
  78052. /** Up */
  78053. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  78054. /** Down */
  78055. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  78056. /** Left */
  78057. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  78058. /** Right */
  78059. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  78060. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  78061. /**
  78062. * Defines a XBox360 gamepad
  78063. */
  78064. var Xbox360Pad = /** @class */ (function (_super) {
  78065. __extends(Xbox360Pad, _super);
  78066. /**
  78067. * Creates a new XBox360 gamepad object
  78068. * @param id defines the id of this gamepad
  78069. * @param index defines its index
  78070. * @param gamepad defines the internal HTML gamepad object
  78071. * @param xboxOne defines if it is a XBox One gamepad
  78072. */
  78073. function Xbox360Pad(id, index, gamepad, xboxOne) {
  78074. if (xboxOne === void 0) { xboxOne = false; }
  78075. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  78076. _this._leftTrigger = 0;
  78077. _this._rightTrigger = 0;
  78078. /** Observable raised when a button is pressed */
  78079. _this.onButtonDownObservable = new BABYLON.Observable();
  78080. /** Observable raised when a button is released */
  78081. _this.onButtonUpObservable = new BABYLON.Observable();
  78082. /** Observable raised when a pad is pressed */
  78083. _this.onPadDownObservable = new BABYLON.Observable();
  78084. /** Observable raised when a pad is released */
  78085. _this.onPadUpObservable = new BABYLON.Observable();
  78086. _this._buttonA = 0;
  78087. _this._buttonB = 0;
  78088. _this._buttonX = 0;
  78089. _this._buttonY = 0;
  78090. _this._buttonBack = 0;
  78091. _this._buttonStart = 0;
  78092. _this._buttonLB = 0;
  78093. _this._buttonRB = 0;
  78094. _this._buttonLeftStick = 0;
  78095. _this._buttonRightStick = 0;
  78096. _this._dPadUp = 0;
  78097. _this._dPadDown = 0;
  78098. _this._dPadLeft = 0;
  78099. _this._dPadRight = 0;
  78100. _this._isXboxOnePad = false;
  78101. _this.type = BABYLON.Gamepad.XBOX;
  78102. _this._isXboxOnePad = xboxOne;
  78103. return _this;
  78104. }
  78105. /**
  78106. * Defines the callback to call when left trigger is pressed
  78107. * @param callback defines the callback to use
  78108. */
  78109. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  78110. this._onlefttriggerchanged = callback;
  78111. };
  78112. /**
  78113. * Defines the callback to call when right trigger is pressed
  78114. * @param callback defines the callback to use
  78115. */
  78116. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  78117. this._onrighttriggerchanged = callback;
  78118. };
  78119. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  78120. /**
  78121. * Gets the left trigger value
  78122. */
  78123. get: function () {
  78124. return this._leftTrigger;
  78125. },
  78126. /**
  78127. * Sets the left trigger value
  78128. */
  78129. set: function (newValue) {
  78130. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  78131. this._onlefttriggerchanged(newValue);
  78132. }
  78133. this._leftTrigger = newValue;
  78134. },
  78135. enumerable: true,
  78136. configurable: true
  78137. });
  78138. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  78139. /**
  78140. * Gets the right trigger value
  78141. */
  78142. get: function () {
  78143. return this._rightTrigger;
  78144. },
  78145. /**
  78146. * Sets the right trigger value
  78147. */
  78148. set: function (newValue) {
  78149. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  78150. this._onrighttriggerchanged(newValue);
  78151. }
  78152. this._rightTrigger = newValue;
  78153. },
  78154. enumerable: true,
  78155. configurable: true
  78156. });
  78157. /**
  78158. * Defines the callback to call when a button is pressed
  78159. * @param callback defines the callback to use
  78160. */
  78161. Xbox360Pad.prototype.onbuttondown = function (callback) {
  78162. this._onbuttondown = callback;
  78163. };
  78164. /**
  78165. * Defines the callback to call when a button is released
  78166. * @param callback defines the callback to use
  78167. */
  78168. Xbox360Pad.prototype.onbuttonup = function (callback) {
  78169. this._onbuttonup = callback;
  78170. };
  78171. /**
  78172. * Defines the callback to call when a pad is pressed
  78173. * @param callback defines the callback to use
  78174. */
  78175. Xbox360Pad.prototype.ondpaddown = function (callback) {
  78176. this._ondpaddown = callback;
  78177. };
  78178. /**
  78179. * Defines the callback to call when a pad is released
  78180. * @param callback defines the callback to use
  78181. */
  78182. Xbox360Pad.prototype.ondpadup = function (callback) {
  78183. this._ondpadup = callback;
  78184. };
  78185. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  78186. if (newValue !== currentValue) {
  78187. if (newValue === 1) {
  78188. if (this._onbuttondown) {
  78189. this._onbuttondown(buttonType);
  78190. }
  78191. this.onButtonDownObservable.notifyObservers(buttonType);
  78192. }
  78193. if (newValue === 0) {
  78194. if (this._onbuttonup) {
  78195. this._onbuttonup(buttonType);
  78196. }
  78197. this.onButtonUpObservable.notifyObservers(buttonType);
  78198. }
  78199. }
  78200. return newValue;
  78201. };
  78202. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  78203. if (newValue !== currentValue) {
  78204. if (newValue === 1) {
  78205. if (this._ondpaddown) {
  78206. this._ondpaddown(buttonType);
  78207. }
  78208. this.onPadDownObservable.notifyObservers(buttonType);
  78209. }
  78210. if (newValue === 0) {
  78211. if (this._ondpadup) {
  78212. this._ondpadup(buttonType);
  78213. }
  78214. this.onPadUpObservable.notifyObservers(buttonType);
  78215. }
  78216. }
  78217. return newValue;
  78218. };
  78219. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  78220. /**
  78221. * Gets the value of the `A` button
  78222. */
  78223. get: function () {
  78224. return this._buttonA;
  78225. },
  78226. /**
  78227. * Sets the value of the `A` button
  78228. */
  78229. set: function (value) {
  78230. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  78231. },
  78232. enumerable: true,
  78233. configurable: true
  78234. });
  78235. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  78236. /**
  78237. * Gets the value of the `B` button
  78238. */
  78239. get: function () {
  78240. return this._buttonB;
  78241. },
  78242. /**
  78243. * Sets the value of the `B` button
  78244. */
  78245. set: function (value) {
  78246. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  78247. },
  78248. enumerable: true,
  78249. configurable: true
  78250. });
  78251. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  78252. /**
  78253. * Gets the value of the `X` button
  78254. */
  78255. get: function () {
  78256. return this._buttonX;
  78257. },
  78258. /**
  78259. * Sets the value of the `X` button
  78260. */
  78261. set: function (value) {
  78262. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  78263. },
  78264. enumerable: true,
  78265. configurable: true
  78266. });
  78267. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  78268. /**
  78269. * Gets the value of the `Y` button
  78270. */
  78271. get: function () {
  78272. return this._buttonY;
  78273. },
  78274. /**
  78275. * Sets the value of the `Y` button
  78276. */
  78277. set: function (value) {
  78278. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  78279. },
  78280. enumerable: true,
  78281. configurable: true
  78282. });
  78283. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  78284. /**
  78285. * Gets the value of the `Start` button
  78286. */
  78287. get: function () {
  78288. return this._buttonStart;
  78289. },
  78290. /**
  78291. * Sets the value of the `Start` button
  78292. */
  78293. set: function (value) {
  78294. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  78295. },
  78296. enumerable: true,
  78297. configurable: true
  78298. });
  78299. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  78300. /**
  78301. * Gets the value of the `Back` button
  78302. */
  78303. get: function () {
  78304. return this._buttonBack;
  78305. },
  78306. /**
  78307. * Sets the value of the `Back` button
  78308. */
  78309. set: function (value) {
  78310. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  78311. },
  78312. enumerable: true,
  78313. configurable: true
  78314. });
  78315. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  78316. /**
  78317. * Gets the value of the `Left` button
  78318. */
  78319. get: function () {
  78320. return this._buttonLB;
  78321. },
  78322. /**
  78323. * Sets the value of the `Left` button
  78324. */
  78325. set: function (value) {
  78326. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  78327. },
  78328. enumerable: true,
  78329. configurable: true
  78330. });
  78331. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  78332. /**
  78333. * Gets the value of the `Right` button
  78334. */
  78335. get: function () {
  78336. return this._buttonRB;
  78337. },
  78338. /**
  78339. * Sets the value of the `Right` button
  78340. */
  78341. set: function (value) {
  78342. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  78343. },
  78344. enumerable: true,
  78345. configurable: true
  78346. });
  78347. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  78348. /**
  78349. * Gets the value of the Left joystick
  78350. */
  78351. get: function () {
  78352. return this._buttonLeftStick;
  78353. },
  78354. /**
  78355. * Sets the value of the Left joystick
  78356. */
  78357. set: function (value) {
  78358. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  78359. },
  78360. enumerable: true,
  78361. configurable: true
  78362. });
  78363. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  78364. /**
  78365. * Gets the value of the Right joystick
  78366. */
  78367. get: function () {
  78368. return this._buttonRightStick;
  78369. },
  78370. /**
  78371. * Sets the value of the Right joystick
  78372. */
  78373. set: function (value) {
  78374. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  78375. },
  78376. enumerable: true,
  78377. configurable: true
  78378. });
  78379. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  78380. /**
  78381. * Gets the value of D-pad up
  78382. */
  78383. get: function () {
  78384. return this._dPadUp;
  78385. },
  78386. /**
  78387. * Sets the value of D-pad up
  78388. */
  78389. set: function (value) {
  78390. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  78391. },
  78392. enumerable: true,
  78393. configurable: true
  78394. });
  78395. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  78396. /**
  78397. * Gets the value of D-pad down
  78398. */
  78399. get: function () {
  78400. return this._dPadDown;
  78401. },
  78402. /**
  78403. * Sets the value of D-pad down
  78404. */
  78405. set: function (value) {
  78406. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  78407. },
  78408. enumerable: true,
  78409. configurable: true
  78410. });
  78411. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  78412. /**
  78413. * Gets the value of D-pad left
  78414. */
  78415. get: function () {
  78416. return this._dPadLeft;
  78417. },
  78418. /**
  78419. * Sets the value of D-pad left
  78420. */
  78421. set: function (value) {
  78422. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  78423. },
  78424. enumerable: true,
  78425. configurable: true
  78426. });
  78427. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  78428. /**
  78429. * Gets the value of D-pad right
  78430. */
  78431. get: function () {
  78432. return this._dPadRight;
  78433. },
  78434. /**
  78435. * Sets the value of D-pad right
  78436. */
  78437. set: function (value) {
  78438. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  78439. },
  78440. enumerable: true,
  78441. configurable: true
  78442. });
  78443. /**
  78444. * Force the gamepad to synchronize with device values
  78445. */
  78446. Xbox360Pad.prototype.update = function () {
  78447. _super.prototype.update.call(this);
  78448. if (this._isXboxOnePad) {
  78449. this.buttonA = this.browserGamepad.buttons[0].value;
  78450. this.buttonB = this.browserGamepad.buttons[1].value;
  78451. this.buttonX = this.browserGamepad.buttons[2].value;
  78452. this.buttonY = this.browserGamepad.buttons[3].value;
  78453. this.buttonLB = this.browserGamepad.buttons[4].value;
  78454. this.buttonRB = this.browserGamepad.buttons[5].value;
  78455. this.leftTrigger = this.browserGamepad.axes[2];
  78456. this.rightTrigger = this.browserGamepad.axes[5];
  78457. this.buttonBack = this.browserGamepad.buttons[9].value;
  78458. this.buttonStart = this.browserGamepad.buttons[8].value;
  78459. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  78460. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  78461. this.dPadUp = this.browserGamepad.buttons[11].value;
  78462. this.dPadDown = this.browserGamepad.buttons[12].value;
  78463. this.dPadLeft = this.browserGamepad.buttons[13].value;
  78464. this.dPadRight = this.browserGamepad.buttons[14].value;
  78465. }
  78466. else {
  78467. this.buttonA = this.browserGamepad.buttons[0].value;
  78468. this.buttonB = this.browserGamepad.buttons[1].value;
  78469. this.buttonX = this.browserGamepad.buttons[2].value;
  78470. this.buttonY = this.browserGamepad.buttons[3].value;
  78471. this.buttonLB = this.browserGamepad.buttons[4].value;
  78472. this.buttonRB = this.browserGamepad.buttons[5].value;
  78473. this.leftTrigger = this.browserGamepad.buttons[6].value;
  78474. this.rightTrigger = this.browserGamepad.buttons[7].value;
  78475. this.buttonBack = this.browserGamepad.buttons[8].value;
  78476. this.buttonStart = this.browserGamepad.buttons[9].value;
  78477. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  78478. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  78479. this.dPadUp = this.browserGamepad.buttons[12].value;
  78480. this.dPadDown = this.browserGamepad.buttons[13].value;
  78481. this.dPadLeft = this.browserGamepad.buttons[14].value;
  78482. this.dPadRight = this.browserGamepad.buttons[15].value;
  78483. }
  78484. };
  78485. /**
  78486. * Disposes the gamepad
  78487. */
  78488. Xbox360Pad.prototype.dispose = function () {
  78489. _super.prototype.dispose.call(this);
  78490. this.onButtonDownObservable.clear();
  78491. this.onButtonUpObservable.clear();
  78492. this.onPadDownObservable.clear();
  78493. this.onPadUpObservable.clear();
  78494. };
  78495. return Xbox360Pad;
  78496. }(BABYLON.Gamepad));
  78497. BABYLON.Xbox360Pad = Xbox360Pad;
  78498. })(BABYLON || (BABYLON = {}));
  78499. //# sourceMappingURL=babylon.xboxGamepad.js.map
  78500. var BABYLON;
  78501. (function (BABYLON) {
  78502. /**
  78503. * Defines the types of pose enabled controllers that are supported
  78504. */
  78505. var PoseEnabledControllerType;
  78506. (function (PoseEnabledControllerType) {
  78507. /**
  78508. * HTC Vive
  78509. */
  78510. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  78511. /**
  78512. * Oculus Rift
  78513. */
  78514. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  78515. /**
  78516. * Windows mixed reality
  78517. */
  78518. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  78519. /**
  78520. * Samsung gear VR
  78521. */
  78522. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  78523. /**
  78524. * Google Daydream
  78525. */
  78526. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  78527. /**
  78528. * Generic
  78529. */
  78530. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  78531. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  78532. /**
  78533. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  78534. */
  78535. var PoseEnabledControllerHelper = /** @class */ (function () {
  78536. function PoseEnabledControllerHelper() {
  78537. }
  78538. /**
  78539. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  78540. * @param vrGamepad the gamepad to initialized
  78541. * @returns a vr controller of the type the gamepad identified as
  78542. */
  78543. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  78544. // Oculus Touch
  78545. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  78546. return new BABYLON.OculusTouchController(vrGamepad);
  78547. }
  78548. // Windows Mixed Reality controllers
  78549. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  78550. return new BABYLON.WindowsMotionController(vrGamepad);
  78551. }
  78552. // HTC Vive
  78553. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  78554. return new BABYLON.ViveController(vrGamepad);
  78555. }
  78556. // Samsung/Oculus Gear VR or Oculus Go
  78557. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  78558. return new BABYLON.GearVRController(vrGamepad);
  78559. }
  78560. // Google Daydream
  78561. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  78562. return new BABYLON.DaydreamController(vrGamepad);
  78563. }
  78564. // Generic
  78565. else {
  78566. return new BABYLON.GenericController(vrGamepad);
  78567. }
  78568. };
  78569. return PoseEnabledControllerHelper;
  78570. }());
  78571. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  78572. /**
  78573. * Defines the PoseEnabledController object that contains state of a vr capable controller
  78574. */
  78575. var PoseEnabledController = /** @class */ (function (_super) {
  78576. __extends(PoseEnabledController, _super);
  78577. /**
  78578. * Creates a new PoseEnabledController from a gamepad
  78579. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  78580. */
  78581. function PoseEnabledController(browserGamepad) {
  78582. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  78583. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  78584. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  78585. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  78586. /**
  78587. * The device position in babylon space
  78588. */
  78589. _this.devicePosition = BABYLON.Vector3.Zero();
  78590. /**
  78591. * The device rotation in babylon space
  78592. */
  78593. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  78594. /**
  78595. * The scale factor of the device in babylon space
  78596. */
  78597. _this.deviceScaleFactor = 1;
  78598. // Used to convert 6dof controllers to 3dof
  78599. _this._trackPosition = true;
  78600. _this._maxRotationDistFromHeadset = Math.PI / 5;
  78601. _this._draggedRoomRotation = 0;
  78602. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  78603. /**
  78604. * Internal, matrix used to convert room space to babylon space
  78605. * @hidden
  78606. */
  78607. _this._deviceToWorld = BABYLON.Matrix.Identity();
  78608. /**
  78609. * Node to be used when casting a ray from the controller
  78610. * @hidden
  78611. */
  78612. _this._pointingPoseNode = null;
  78613. _this._workingMatrix = BABYLON.Matrix.Identity();
  78614. /**
  78615. * @hidden
  78616. */
  78617. _this._meshAttachedObservable = new BABYLON.Observable();
  78618. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  78619. _this.controllerType = PoseEnabledControllerType.GENERIC;
  78620. _this.position = BABYLON.Vector3.Zero();
  78621. _this.rotationQuaternion = new BABYLON.Quaternion();
  78622. _this._calculatedPosition = BABYLON.Vector3.Zero();
  78623. _this._calculatedRotation = new BABYLON.Quaternion();
  78624. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  78625. return _this;
  78626. }
  78627. /**
  78628. * @hidden
  78629. */
  78630. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  78631. if (this._trackPosition) {
  78632. this._calculatedPosition.copyFrom(fixedPosition);
  78633. this._trackPosition = false;
  78634. }
  78635. };
  78636. /**
  78637. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  78638. */
  78639. PoseEnabledController.prototype.update = function () {
  78640. _super.prototype.update.call(this);
  78641. this._updatePoseAndMesh();
  78642. };
  78643. /**
  78644. * Updates only the pose device and mesh without doing any button event checking
  78645. */
  78646. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  78647. var pose = this.browserGamepad.pose;
  78648. this.updateFromDevice(pose);
  78649. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  78650. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  78651. camera._computeDevicePosition();
  78652. this._deviceToWorld.setTranslation(camera.devicePosition);
  78653. if (camera.deviceRotationQuaternion) {
  78654. var camera = camera;
  78655. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  78656. // Find the radian distance away that the headset is from the controllers rotation
  78657. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  78658. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  78659. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  78660. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  78661. this._draggedRoomRotation += rotationAmount;
  78662. // Rotate controller around headset
  78663. var sin = Math.sin(-rotationAmount);
  78664. var cos = Math.cos(-rotationAmount);
  78665. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  78666. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  78667. }
  78668. }
  78669. }
  78670. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  78671. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  78672. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  78673. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  78674. if (this._mesh) {
  78675. this._mesh.position.copyFrom(this.devicePosition);
  78676. if (this._mesh.rotationQuaternion) {
  78677. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  78678. }
  78679. }
  78680. };
  78681. /**
  78682. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  78683. * @param poseData raw pose fromthe device
  78684. */
  78685. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  78686. if (poseData) {
  78687. this.rawPose = poseData;
  78688. if (poseData.position) {
  78689. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  78690. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  78691. this._deviceRoomPosition.z *= -1;
  78692. }
  78693. if (this._trackPosition) {
  78694. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  78695. }
  78696. this._calculatedPosition.addInPlace(this.position);
  78697. }
  78698. var pose = this.rawPose;
  78699. if (poseData.orientation && pose.orientation) {
  78700. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  78701. if (this._mesh) {
  78702. if (this._mesh.getScene().useRightHandedSystem) {
  78703. this._deviceRoomRotationQuaternion.z *= -1;
  78704. this._deviceRoomRotationQuaternion.w *= -1;
  78705. }
  78706. else {
  78707. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  78708. }
  78709. }
  78710. // if the camera is set, rotate to the camera's rotation
  78711. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  78712. }
  78713. }
  78714. };
  78715. /**
  78716. * Attaches a mesh to the controller
  78717. * @param mesh the mesh to be attached
  78718. */
  78719. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  78720. if (this._mesh) {
  78721. this._mesh.parent = null;
  78722. }
  78723. this._mesh = mesh;
  78724. if (this._poseControlledCamera) {
  78725. this._mesh.parent = this._poseControlledCamera;
  78726. }
  78727. if (!this._mesh.rotationQuaternion) {
  78728. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  78729. }
  78730. // 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
  78731. this._updatePoseAndMesh();
  78732. if (this._pointingPoseNode) {
  78733. var parents = [];
  78734. var obj = this._pointingPoseNode;
  78735. while (obj.parent) {
  78736. parents.push(obj.parent);
  78737. obj = obj.parent;
  78738. }
  78739. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  78740. }
  78741. this._meshAttachedObservable.notifyObservers(mesh);
  78742. };
  78743. /**
  78744. * Attaches the controllers mesh to a camera
  78745. * @param camera the camera the mesh should be attached to
  78746. */
  78747. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  78748. this._poseControlledCamera = camera;
  78749. if (this._mesh) {
  78750. this._mesh.parent = this._poseControlledCamera;
  78751. }
  78752. };
  78753. /**
  78754. * Disposes of the controller
  78755. */
  78756. PoseEnabledController.prototype.dispose = function () {
  78757. if (this._mesh) {
  78758. this._mesh.dispose();
  78759. }
  78760. this._mesh = null;
  78761. _super.prototype.dispose.call(this);
  78762. };
  78763. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  78764. /**
  78765. * The mesh that is attached to the controller
  78766. */
  78767. get: function () {
  78768. return this._mesh;
  78769. },
  78770. enumerable: true,
  78771. configurable: true
  78772. });
  78773. /**
  78774. * Gets the ray of the controller in the direction the controller is pointing
  78775. * @param length the length the resulting ray should be
  78776. * @returns a ray in the direction the controller is pointing
  78777. */
  78778. PoseEnabledController.prototype.getForwardRay = function (length) {
  78779. if (length === void 0) { length = 100; }
  78780. if (!this.mesh) {
  78781. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  78782. }
  78783. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  78784. var origin = m.getTranslation();
  78785. var forward = new BABYLON.Vector3(0, 0, -1);
  78786. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  78787. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  78788. return new BABYLON.Ray(origin, direction, length);
  78789. };
  78790. /**
  78791. * Name of the child mesh that can be used to cast a ray from the controller
  78792. */
  78793. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  78794. return PoseEnabledController;
  78795. }(BABYLON.Gamepad));
  78796. BABYLON.PoseEnabledController = PoseEnabledController;
  78797. })(BABYLON || (BABYLON = {}));
  78798. //# sourceMappingURL=babylon.poseEnabledController.js.map
  78799. var BABYLON;
  78800. (function (BABYLON) {
  78801. /**
  78802. * Defines the WebVRController object that represents controllers tracked in 3D space
  78803. */
  78804. var WebVRController = /** @class */ (function (_super) {
  78805. __extends(WebVRController, _super);
  78806. /**
  78807. * Creates a new WebVRController from a gamepad
  78808. * @param vrGamepad the gamepad that the WebVRController should be created from
  78809. */
  78810. function WebVRController(vrGamepad) {
  78811. var _this = _super.call(this, vrGamepad) || this;
  78812. // Observables
  78813. /**
  78814. * Fired when the trigger state has changed
  78815. */
  78816. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  78817. /**
  78818. * Fired when the main button state has changed
  78819. */
  78820. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  78821. /**
  78822. * Fired when the secondary button state has changed
  78823. */
  78824. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  78825. /**
  78826. * Fired when the pad state has changed
  78827. */
  78828. _this.onPadStateChangedObservable = new BABYLON.Observable();
  78829. /**
  78830. * Fired when controllers stick values have changed
  78831. */
  78832. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  78833. /**
  78834. * X and Y axis corrisponding to the controllers joystick
  78835. */
  78836. _this.pad = { x: 0, y: 0 };
  78837. // avoid GC, store state in a tmp object
  78838. _this._changes = {
  78839. pressChanged: false,
  78840. touchChanged: false,
  78841. valueChanged: false,
  78842. changed: false
  78843. };
  78844. _this._buttons = new Array(vrGamepad.buttons.length);
  78845. _this.hand = vrGamepad.hand;
  78846. return _this;
  78847. }
  78848. /**
  78849. * Fired when a controller button's state has changed
  78850. * @param callback the callback containing the button that was modified
  78851. */
  78852. WebVRController.prototype.onButtonStateChange = function (callback) {
  78853. this._onButtonStateChange = callback;
  78854. };
  78855. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  78856. /**
  78857. * The default controller model for the controller
  78858. */
  78859. get: function () {
  78860. return this._defaultModel;
  78861. },
  78862. enumerable: true,
  78863. configurable: true
  78864. });
  78865. /**
  78866. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  78867. */
  78868. WebVRController.prototype.update = function () {
  78869. _super.prototype.update.call(this);
  78870. for (var index = 0; index < this._buttons.length; index++) {
  78871. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  78872. }
  78873. ;
  78874. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  78875. this.pad.x = this.leftStick.x;
  78876. this.pad.y = this.leftStick.y;
  78877. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  78878. }
  78879. };
  78880. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  78881. if (!newState) {
  78882. newState = {
  78883. pressed: false,
  78884. touched: false,
  78885. value: 0
  78886. };
  78887. }
  78888. if (!currentState) {
  78889. this._buttons[buttonIndex] = {
  78890. pressed: newState.pressed,
  78891. touched: newState.touched,
  78892. value: newState.value
  78893. };
  78894. return;
  78895. }
  78896. this._checkChanges(newState, currentState);
  78897. if (this._changes.changed) {
  78898. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  78899. this._handleButtonChange(buttonIndex, newState, this._changes);
  78900. }
  78901. this._buttons[buttonIndex].pressed = newState.pressed;
  78902. this._buttons[buttonIndex].touched = newState.touched;
  78903. // oculus triggers are never 0, thou not touched.
  78904. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  78905. };
  78906. WebVRController.prototype._checkChanges = function (newState, currentState) {
  78907. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  78908. this._changes.touchChanged = newState.touched !== currentState.touched;
  78909. this._changes.valueChanged = newState.value !== currentState.value;
  78910. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  78911. return this._changes;
  78912. };
  78913. /**
  78914. * Disposes of th webVRCOntroller
  78915. */
  78916. WebVRController.prototype.dispose = function () {
  78917. _super.prototype.dispose.call(this);
  78918. this.onTriggerStateChangedObservable.clear();
  78919. this.onMainButtonStateChangedObservable.clear();
  78920. this.onSecondaryButtonStateChangedObservable.clear();
  78921. this.onPadStateChangedObservable.clear();
  78922. this.onPadValuesChangedObservable.clear();
  78923. };
  78924. return WebVRController;
  78925. }(BABYLON.PoseEnabledController));
  78926. BABYLON.WebVRController = WebVRController;
  78927. })(BABYLON || (BABYLON = {}));
  78928. //# sourceMappingURL=babylon.webVRController.js.map
  78929. var BABYLON;
  78930. (function (BABYLON) {
  78931. /**
  78932. * Oculus Touch Controller
  78933. */
  78934. var OculusTouchController = /** @class */ (function (_super) {
  78935. __extends(OculusTouchController, _super);
  78936. /**
  78937. * Creates a new OculusTouchController from a gamepad
  78938. * @param vrGamepad the gamepad that the controller should be created from
  78939. */
  78940. function OculusTouchController(vrGamepad) {
  78941. var _this = _super.call(this, vrGamepad) || this;
  78942. /**
  78943. * Fired when the secondary trigger on this controller is modified
  78944. */
  78945. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  78946. /**
  78947. * Fired when the thumb rest on this controller is modified
  78948. */
  78949. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  78950. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  78951. return _this;
  78952. }
  78953. /**
  78954. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78955. * @param scene scene in which to add meshes
  78956. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78957. */
  78958. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78959. var _this = this;
  78960. var meshName;
  78961. // Hand
  78962. if (this.hand === 'left') {
  78963. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  78964. }
  78965. else { // Right is the default if no hand is specified
  78966. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  78967. }
  78968. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  78969. /*
  78970. Parent Mesh name: oculus_touch_left
  78971. - body
  78972. - trigger
  78973. - thumbstick
  78974. - grip
  78975. - button_y
  78976. - button_x
  78977. - button_enter
  78978. */
  78979. _this._defaultModel = newMeshes[1];
  78980. _this.attachToMesh(_this._defaultModel);
  78981. if (meshLoaded) {
  78982. meshLoaded(_this._defaultModel);
  78983. }
  78984. });
  78985. };
  78986. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  78987. /**
  78988. * Fired when the A button on this controller is modified
  78989. */
  78990. get: function () {
  78991. if (this.hand === 'right') {
  78992. return this.onMainButtonStateChangedObservable;
  78993. }
  78994. else {
  78995. throw new Error('No A button on left hand');
  78996. }
  78997. },
  78998. enumerable: true,
  78999. configurable: true
  79000. });
  79001. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  79002. /**
  79003. * Fired when the B button on this controller is modified
  79004. */
  79005. get: function () {
  79006. if (this.hand === 'right') {
  79007. return this.onSecondaryButtonStateChangedObservable;
  79008. }
  79009. else {
  79010. throw new Error('No B button on left hand');
  79011. }
  79012. },
  79013. enumerable: true,
  79014. configurable: true
  79015. });
  79016. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  79017. /**
  79018. * Fired when the X button on this controller is modified
  79019. */
  79020. get: function () {
  79021. if (this.hand === 'left') {
  79022. return this.onMainButtonStateChangedObservable;
  79023. }
  79024. else {
  79025. throw new Error('No X button on right hand');
  79026. }
  79027. },
  79028. enumerable: true,
  79029. configurable: true
  79030. });
  79031. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  79032. /**
  79033. * Fired when the Y button on this controller is modified
  79034. */
  79035. get: function () {
  79036. if (this.hand === 'left') {
  79037. return this.onSecondaryButtonStateChangedObservable;
  79038. }
  79039. else {
  79040. throw new Error('No Y button on right hand');
  79041. }
  79042. },
  79043. enumerable: true,
  79044. configurable: true
  79045. });
  79046. /**
  79047. * Called once for each button that changed state since the last frame
  79048. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  79049. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  79050. * 2) secondary trigger (same)
  79051. * 3) A (right) X (left), touch, pressed = value
  79052. * 4) B / Y
  79053. * 5) thumb rest
  79054. * @param buttonIdx Which button index changed
  79055. * @param state New state of the button
  79056. * @param changes Which properties on the state changed since last frame
  79057. */
  79058. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79059. var notifyObject = state; //{ state: state, changes: changes };
  79060. var triggerDirection = this.hand === 'right' ? -1 : 1;
  79061. switch (buttonIdx) {
  79062. case 0:
  79063. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  79064. return;
  79065. case 1: // index trigger
  79066. if (this._defaultModel) {
  79067. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  79068. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  79069. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  79070. }
  79071. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  79072. return;
  79073. case 2: // secondary trigger
  79074. if (this._defaultModel) {
  79075. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  79076. }
  79077. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  79078. return;
  79079. case 3:
  79080. if (this._defaultModel) {
  79081. if (notifyObject.pressed) {
  79082. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  79083. }
  79084. else {
  79085. (this._defaultModel.getChildren()[1]).position.y = 0;
  79086. }
  79087. }
  79088. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  79089. return;
  79090. case 4:
  79091. if (this._defaultModel) {
  79092. if (notifyObject.pressed) {
  79093. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  79094. }
  79095. else {
  79096. (this._defaultModel.getChildren()[2]).position.y = 0;
  79097. }
  79098. }
  79099. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  79100. return;
  79101. case 5:
  79102. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  79103. return;
  79104. }
  79105. };
  79106. /**
  79107. * Base Url for the controller model.
  79108. */
  79109. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  79110. /**
  79111. * File name for the left controller model.
  79112. */
  79113. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  79114. /**
  79115. * File name for the right controller model.
  79116. */
  79117. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  79118. return OculusTouchController;
  79119. }(BABYLON.WebVRController));
  79120. BABYLON.OculusTouchController = OculusTouchController;
  79121. })(BABYLON || (BABYLON = {}));
  79122. //# sourceMappingURL=babylon.oculusTouchController.js.map
  79123. var BABYLON;
  79124. (function (BABYLON) {
  79125. /**
  79126. * Vive Controller
  79127. */
  79128. var ViveController = /** @class */ (function (_super) {
  79129. __extends(ViveController, _super);
  79130. /**
  79131. * Creates a new ViveController from a gamepad
  79132. * @param vrGamepad the gamepad that the controller should be created from
  79133. */
  79134. function ViveController(vrGamepad) {
  79135. var _this = _super.call(this, vrGamepad) || this;
  79136. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  79137. _this._invertLeftStickY = true;
  79138. return _this;
  79139. }
  79140. /**
  79141. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79142. * @param scene scene in which to add meshes
  79143. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79144. */
  79145. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  79146. var _this = this;
  79147. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  79148. /*
  79149. Parent Mesh name: ViveWand
  79150. - body
  79151. - r_gripper
  79152. - l_gripper
  79153. - menu_button
  79154. - system_button
  79155. - trackpad
  79156. - trigger
  79157. - LED
  79158. */
  79159. _this._defaultModel = newMeshes[1];
  79160. _this.attachToMesh(_this._defaultModel);
  79161. if (meshLoaded) {
  79162. meshLoaded(_this._defaultModel);
  79163. }
  79164. });
  79165. };
  79166. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  79167. /**
  79168. * Fired when the left button on this controller is modified
  79169. */
  79170. get: function () {
  79171. return this.onMainButtonStateChangedObservable;
  79172. },
  79173. enumerable: true,
  79174. configurable: true
  79175. });
  79176. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  79177. /**
  79178. * Fired when the right button on this controller is modified
  79179. */
  79180. get: function () {
  79181. return this.onMainButtonStateChangedObservable;
  79182. },
  79183. enumerable: true,
  79184. configurable: true
  79185. });
  79186. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  79187. /**
  79188. * Fired when the menu button on this controller is modified
  79189. */
  79190. get: function () {
  79191. return this.onSecondaryButtonStateChangedObservable;
  79192. },
  79193. enumerable: true,
  79194. configurable: true
  79195. });
  79196. /**
  79197. * Called once for each button that changed state since the last frame
  79198. * Vive mapping:
  79199. * 0: touchpad
  79200. * 1: trigger
  79201. * 2: left AND right buttons
  79202. * 3: menu button
  79203. * @param buttonIdx Which button index changed
  79204. * @param state New state of the button
  79205. * @param changes Which properties on the state changed since last frame
  79206. */
  79207. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79208. var notifyObject = state; //{ state: state, changes: changes };
  79209. switch (buttonIdx) {
  79210. case 0:
  79211. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  79212. return;
  79213. case 1: // index trigger
  79214. if (this._defaultModel) {
  79215. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  79216. }
  79217. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  79218. return;
  79219. case 2: // left AND right button
  79220. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  79221. return;
  79222. case 3:
  79223. if (this._defaultModel) {
  79224. if (notifyObject.pressed) {
  79225. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  79226. }
  79227. else {
  79228. (this._defaultModel.getChildren()[2]).position.y = 0;
  79229. }
  79230. }
  79231. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  79232. return;
  79233. }
  79234. };
  79235. /**
  79236. * Base Url for the controller model.
  79237. */
  79238. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  79239. /**
  79240. * File name for the controller model.
  79241. */
  79242. ViveController.MODEL_FILENAME = 'wand.babylon';
  79243. return ViveController;
  79244. }(BABYLON.WebVRController));
  79245. BABYLON.ViveController = ViveController;
  79246. })(BABYLON || (BABYLON = {}));
  79247. //# sourceMappingURL=babylon.viveController.js.map
  79248. var BABYLON;
  79249. (function (BABYLON) {
  79250. /**
  79251. * Generic Controller
  79252. */
  79253. var GenericController = /** @class */ (function (_super) {
  79254. __extends(GenericController, _super);
  79255. /**
  79256. * Creates a new GenericController from a gamepad
  79257. * @param vrGamepad the gamepad that the controller should be created from
  79258. */
  79259. function GenericController(vrGamepad) {
  79260. return _super.call(this, vrGamepad) || this;
  79261. }
  79262. /**
  79263. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79264. * @param scene scene in which to add meshes
  79265. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79266. */
  79267. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  79268. var _this = this;
  79269. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  79270. _this._defaultModel = newMeshes[1];
  79271. _this.attachToMesh(_this._defaultModel);
  79272. if (meshLoaded) {
  79273. meshLoaded(_this._defaultModel);
  79274. }
  79275. });
  79276. };
  79277. /**
  79278. * Called once for each button that changed state since the last frame
  79279. * @param buttonIdx Which button index changed
  79280. * @param state New state of the button
  79281. * @param changes Which properties on the state changed since last frame
  79282. */
  79283. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79284. console.log("Button id: " + buttonIdx + "state: ");
  79285. console.dir(state);
  79286. };
  79287. /**
  79288. * Base Url for the controller model.
  79289. */
  79290. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  79291. /**
  79292. * File name for the controller model.
  79293. */
  79294. GenericController.MODEL_FILENAME = 'generic.babylon';
  79295. return GenericController;
  79296. }(BABYLON.WebVRController));
  79297. BABYLON.GenericController = GenericController;
  79298. })(BABYLON || (BABYLON = {}));
  79299. //# sourceMappingURL=babylon.genericController.js.map
  79300. var BABYLON;
  79301. (function (BABYLON) {
  79302. /**
  79303. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  79304. */
  79305. var LoadedMeshInfo = /** @class */ (function () {
  79306. function LoadedMeshInfo() {
  79307. /**
  79308. * Map of the button meshes contained in the controller
  79309. */
  79310. this.buttonMeshes = {};
  79311. /**
  79312. * Map of the axis meshes contained in the controller
  79313. */
  79314. this.axisMeshes = {};
  79315. }
  79316. return LoadedMeshInfo;
  79317. }());
  79318. /**
  79319. * Defines the WindowsMotionController object that the state of the windows motion controller
  79320. */
  79321. var WindowsMotionController = /** @class */ (function (_super) {
  79322. __extends(WindowsMotionController, _super);
  79323. /**
  79324. * Creates a new WindowsMotionController from a gamepad
  79325. * @param vrGamepad the gamepad that the controller should be created from
  79326. */
  79327. function WindowsMotionController(vrGamepad) {
  79328. var _this = _super.call(this, vrGamepad) || this;
  79329. _this._mapping = {
  79330. // Semantic button names
  79331. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  79332. // A mapping of the button name to glTF model node name
  79333. // that should be transformed by button value.
  79334. buttonMeshNames: {
  79335. 'trigger': 'SELECT',
  79336. 'menu': 'MENU',
  79337. 'grip': 'GRASP',
  79338. 'thumbstick': 'THUMBSTICK_PRESS',
  79339. 'trackpad': 'TOUCHPAD_PRESS'
  79340. },
  79341. // This mapping is used to translate from the Motion Controller to Babylon semantics
  79342. buttonObservableNames: {
  79343. 'trigger': 'onTriggerStateChangedObservable',
  79344. 'menu': 'onSecondaryButtonStateChangedObservable',
  79345. 'grip': 'onMainButtonStateChangedObservable',
  79346. 'thumbstick': 'onPadStateChangedObservable',
  79347. 'trackpad': 'onTrackpadChangedObservable'
  79348. },
  79349. // A mapping of the axis name to glTF model node name
  79350. // that should be transformed by axis value.
  79351. // This array mirrors the browserGamepad.axes array, such that
  79352. // the mesh corresponding to axis 0 is in this array index 0.
  79353. axisMeshNames: [
  79354. 'THUMBSTICK_X',
  79355. 'THUMBSTICK_Y',
  79356. 'TOUCHPAD_TOUCH_X',
  79357. 'TOUCHPAD_TOUCH_Y'
  79358. ],
  79359. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  79360. };
  79361. /**
  79362. * Fired when the trackpad on this controller is clicked
  79363. */
  79364. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  79365. /**
  79366. * Fired when the trackpad on this controller is modified
  79367. */
  79368. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  79369. /**
  79370. * The current x and y values of this controller's trackpad
  79371. */
  79372. _this.trackpad = { x: 0, y: 0 };
  79373. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  79374. _this._loadedMeshInfo = null;
  79375. return _this;
  79376. }
  79377. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  79378. /**
  79379. * Fired when the trigger on this controller is modified
  79380. */
  79381. get: function () {
  79382. return this.onTriggerStateChangedObservable;
  79383. },
  79384. enumerable: true,
  79385. configurable: true
  79386. });
  79387. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  79388. /**
  79389. * Fired when the menu button on this controller is modified
  79390. */
  79391. get: function () {
  79392. return this.onSecondaryButtonStateChangedObservable;
  79393. },
  79394. enumerable: true,
  79395. configurable: true
  79396. });
  79397. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  79398. /**
  79399. * Fired when the grip button on this controller is modified
  79400. */
  79401. get: function () {
  79402. return this.onMainButtonStateChangedObservable;
  79403. },
  79404. enumerable: true,
  79405. configurable: true
  79406. });
  79407. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  79408. /**
  79409. * Fired when the thumbstick button on this controller is modified
  79410. */
  79411. get: function () {
  79412. return this.onPadStateChangedObservable;
  79413. },
  79414. enumerable: true,
  79415. configurable: true
  79416. });
  79417. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  79418. /**
  79419. * Fired when the touchpad button on this controller is modified
  79420. */
  79421. get: function () {
  79422. return this.onTrackpadChangedObservable;
  79423. },
  79424. enumerable: true,
  79425. configurable: true
  79426. });
  79427. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  79428. /**
  79429. * Fired when the touchpad values on this controller are modified
  79430. */
  79431. get: function () {
  79432. return this.onTrackpadValuesChangedObservable;
  79433. },
  79434. enumerable: true,
  79435. configurable: true
  79436. });
  79437. WindowsMotionController.prototype._updateTrackpad = function () {
  79438. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  79439. this.trackpad.x = this.browserGamepad["axes"][2];
  79440. this.trackpad.y = this.browserGamepad["axes"][3];
  79441. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  79442. }
  79443. };
  79444. /**
  79445. * Called once per frame by the engine.
  79446. */
  79447. WindowsMotionController.prototype.update = function () {
  79448. _super.prototype.update.call(this);
  79449. if (this.browserGamepad.axes) {
  79450. this._updateTrackpad();
  79451. // Only need to animate axes if there is a loaded mesh
  79452. if (this._loadedMeshInfo) {
  79453. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  79454. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  79455. }
  79456. }
  79457. }
  79458. };
  79459. /**
  79460. * Called once for each button that changed state since the last frame
  79461. * @param buttonIdx Which button index changed
  79462. * @param state New state of the button
  79463. * @param changes Which properties on the state changed since last frame
  79464. */
  79465. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79466. var buttonName = this._mapping.buttons[buttonIdx];
  79467. if (!buttonName) {
  79468. return;
  79469. }
  79470. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  79471. this._updateTrackpad();
  79472. // Only emit events for buttons that we know how to map from index to name
  79473. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  79474. if (observable) {
  79475. observable.notifyObservers(state);
  79476. }
  79477. this._lerpButtonTransform(buttonName, state.value);
  79478. };
  79479. /**
  79480. * Moves the buttons on the controller mesh based on their current state
  79481. * @param buttonName the name of the button to move
  79482. * @param buttonValue the value of the button which determines the buttons new position
  79483. */
  79484. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  79485. // If there is no loaded mesh, there is nothing to transform.
  79486. if (!this._loadedMeshInfo) {
  79487. return;
  79488. }
  79489. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  79490. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  79491. return;
  79492. }
  79493. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  79494. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  79495. };
  79496. /**
  79497. * Moves the axis on the controller mesh based on its current state
  79498. * @param axis the index of the axis
  79499. * @param axisValue the value of the axis which determines the meshes new position
  79500. * @hidden
  79501. */
  79502. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  79503. if (!this._loadedMeshInfo) {
  79504. return;
  79505. }
  79506. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  79507. if (!meshInfo) {
  79508. return;
  79509. }
  79510. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  79511. return;
  79512. }
  79513. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  79514. var lerpValue = axisValue * 0.5 + 0.5;
  79515. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  79516. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  79517. };
  79518. /**
  79519. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79520. * @param scene scene in which to add meshes
  79521. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79522. */
  79523. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  79524. var _this = this;
  79525. if (forceDefault === void 0) { forceDefault = false; }
  79526. var path;
  79527. var filename;
  79528. // Checking if GLB loader is present
  79529. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  79530. // Determine the device specific folder based on the ID suffix
  79531. var device = 'default';
  79532. if (this.id && !forceDefault) {
  79533. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  79534. device = ((match && match[0]) || device);
  79535. }
  79536. // Hand
  79537. if (this.hand === 'left') {
  79538. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  79539. }
  79540. else { // Right is the default if no hand is specified
  79541. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  79542. }
  79543. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  79544. }
  79545. else {
  79546. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  79547. path = BABYLON.GenericController.MODEL_BASE_URL;
  79548. filename = BABYLON.GenericController.MODEL_FILENAME;
  79549. }
  79550. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  79551. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  79552. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  79553. if (!_this._loadedMeshInfo) {
  79554. return;
  79555. }
  79556. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  79557. _this.attachToMesh(_this._defaultModel);
  79558. if (meshLoaded) {
  79559. meshLoaded(_this._defaultModel);
  79560. }
  79561. }, null, function (scene, message) {
  79562. BABYLON.Tools.Log(message);
  79563. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  79564. if (!forceDefault) {
  79565. _this.initControllerMesh(scene, meshLoaded, true);
  79566. }
  79567. });
  79568. };
  79569. /**
  79570. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  79571. * can be transformed by button presses and axes values, based on this._mapping.
  79572. *
  79573. * @param scene scene in which the meshes exist
  79574. * @param meshes list of meshes that make up the controller model to process
  79575. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  79576. */
  79577. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  79578. var loadedMeshInfo = null;
  79579. // Create a new mesh to contain the glTF hierarchy
  79580. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  79581. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  79582. var childMesh = null;
  79583. for (var i = 0; i < meshes.length; i++) {
  79584. var mesh = meshes[i];
  79585. if (!mesh.parent) {
  79586. // Exclude controller meshes from picking results
  79587. mesh.isPickable = false;
  79588. // Handle root node, attach to the new parentMesh
  79589. childMesh = mesh;
  79590. break;
  79591. }
  79592. }
  79593. if (childMesh) {
  79594. childMesh.setParent(parentMesh);
  79595. // Create our mesh info. Note that this method will always return non-null.
  79596. loadedMeshInfo = this.createMeshInfo(parentMesh);
  79597. }
  79598. else {
  79599. BABYLON.Tools.Warn('Could not find root node in model file.');
  79600. }
  79601. return loadedMeshInfo;
  79602. };
  79603. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  79604. var loadedMeshInfo = new LoadedMeshInfo();
  79605. var i;
  79606. loadedMeshInfo.rootNode = rootNode;
  79607. // Reset the caches
  79608. loadedMeshInfo.buttonMeshes = {};
  79609. loadedMeshInfo.axisMeshes = {};
  79610. // Button Meshes
  79611. for (i = 0; i < this._mapping.buttons.length; i++) {
  79612. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  79613. if (!buttonMeshName) {
  79614. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  79615. continue;
  79616. }
  79617. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  79618. if (!buttonMesh) {
  79619. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  79620. continue;
  79621. }
  79622. var buttonMeshInfo = {
  79623. index: i,
  79624. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  79625. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  79626. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  79627. };
  79628. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  79629. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  79630. }
  79631. else {
  79632. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  79633. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  79634. '(VALUE: ' + !!buttonMeshInfo.value +
  79635. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  79636. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  79637. ')');
  79638. }
  79639. }
  79640. // Axis Meshes
  79641. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  79642. var axisMeshName = this._mapping.axisMeshNames[i];
  79643. if (!axisMeshName) {
  79644. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  79645. continue;
  79646. }
  79647. var axisMesh = getChildByName(rootNode, axisMeshName);
  79648. if (!axisMesh) {
  79649. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  79650. continue;
  79651. }
  79652. var axisMeshInfo = {
  79653. index: i,
  79654. value: getImmediateChildByName(axisMesh, 'VALUE'),
  79655. min: getImmediateChildByName(axisMesh, 'MIN'),
  79656. max: getImmediateChildByName(axisMesh, 'MAX')
  79657. };
  79658. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  79659. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  79660. }
  79661. else {
  79662. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  79663. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  79664. '(VALUE: ' + !!axisMeshInfo.value +
  79665. ', MIN: ' + !!axisMeshInfo.min +
  79666. ', MAX:' + !!axisMeshInfo.max +
  79667. ')');
  79668. }
  79669. }
  79670. // Pointing Ray
  79671. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  79672. if (!loadedMeshInfo.pointingPoseNode) {
  79673. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  79674. }
  79675. else {
  79676. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  79677. }
  79678. return loadedMeshInfo;
  79679. // Look through all children recursively. This will return null if no mesh exists with the given name.
  79680. function getChildByName(node, name) {
  79681. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  79682. }
  79683. // Look through only immediate children. This will return null if no mesh exists with the given name.
  79684. function getImmediateChildByName(node, name) {
  79685. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  79686. }
  79687. };
  79688. /**
  79689. * Gets the ray of the controller in the direction the controller is pointing
  79690. * @param length the length the resulting ray should be
  79691. * @returns a ray in the direction the controller is pointing
  79692. */
  79693. WindowsMotionController.prototype.getForwardRay = function (length) {
  79694. if (length === void 0) { length = 100; }
  79695. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  79696. return _super.prototype.getForwardRay.call(this, length);
  79697. }
  79698. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  79699. var origin = m.getTranslation();
  79700. var forward = new BABYLON.Vector3(0, 0, -1);
  79701. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  79702. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  79703. return new BABYLON.Ray(origin, direction, length);
  79704. };
  79705. /**
  79706. * Disposes of the controller
  79707. */
  79708. WindowsMotionController.prototype.dispose = function () {
  79709. _super.prototype.dispose.call(this);
  79710. this.onTrackpadChangedObservable.clear();
  79711. };
  79712. /**
  79713. * The base url used to load the left and right controller models
  79714. */
  79715. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  79716. /**
  79717. * The name of the left controller model file
  79718. */
  79719. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  79720. /**
  79721. * The name of the right controller model file
  79722. */
  79723. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  79724. /**
  79725. * The controller name prefix for this controller type
  79726. */
  79727. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  79728. /**
  79729. * The controller id pattern for this controller type
  79730. */
  79731. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  79732. return WindowsMotionController;
  79733. }(BABYLON.WebVRController));
  79734. BABYLON.WindowsMotionController = WindowsMotionController;
  79735. })(BABYLON || (BABYLON = {}));
  79736. //# sourceMappingURL=babylon.windowsMotionController.js.map
  79737. var BABYLON;
  79738. (function (BABYLON) {
  79739. /**
  79740. * Gear VR Controller
  79741. */
  79742. var GearVRController = /** @class */ (function (_super) {
  79743. __extends(GearVRController, _super);
  79744. /**
  79745. * Creates a new GearVRController from a gamepad
  79746. * @param vrGamepad the gamepad that the controller should be created from
  79747. */
  79748. function GearVRController(vrGamepad) {
  79749. var _this = _super.call(this, vrGamepad) || this;
  79750. _this._buttonIndexToObservableNameMap = [
  79751. 'onTrackpadChangedObservable',
  79752. 'onTriggerStateChangedObservable' // Trigger
  79753. ];
  79754. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  79755. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  79756. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  79757. _this._disableTrackPosition(_this._calculatedPosition);
  79758. return _this;
  79759. }
  79760. /**
  79761. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79762. * @param scene scene in which to add meshes
  79763. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79764. */
  79765. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  79766. var _this = this;
  79767. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  79768. // Offset the controller so it will rotate around the users wrist
  79769. var mesh = new BABYLON.Mesh("", scene);
  79770. newMeshes[1].parent = mesh;
  79771. newMeshes[1].position.z = -0.15;
  79772. _this._defaultModel = mesh;
  79773. _this.attachToMesh(_this._defaultModel);
  79774. if (meshLoaded) {
  79775. meshLoaded(_this._defaultModel);
  79776. }
  79777. });
  79778. };
  79779. /**
  79780. * Called once for each button that changed state since the last frame
  79781. * @param buttonIdx Which button index changed
  79782. * @param state New state of the button
  79783. * @param changes Which properties on the state changed since last frame
  79784. */
  79785. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79786. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  79787. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  79788. // Only emit events for buttons that we know how to map from index to observable
  79789. var observable = this[observableName];
  79790. if (observable) {
  79791. observable.notifyObservers(state);
  79792. }
  79793. }
  79794. };
  79795. /**
  79796. * Base Url for the controller model.
  79797. */
  79798. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  79799. /**
  79800. * File name for the controller model.
  79801. */
  79802. GearVRController.MODEL_FILENAME = 'generic.babylon';
  79803. /**
  79804. * Gamepad Id prefix used to identify this controller.
  79805. */
  79806. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  79807. return GearVRController;
  79808. }(BABYLON.WebVRController));
  79809. BABYLON.GearVRController = GearVRController;
  79810. })(BABYLON || (BABYLON = {}));
  79811. //# sourceMappingURL=babylon.gearVRController.js.map
  79812. var BABYLON;
  79813. (function (BABYLON) {
  79814. /**
  79815. * Google Daydream controller
  79816. */
  79817. var DaydreamController = /** @class */ (function (_super) {
  79818. __extends(DaydreamController, _super);
  79819. /**
  79820. * Creates a new DaydreamController from a gamepad
  79821. * @param vrGamepad the gamepad that the controller should be created from
  79822. */
  79823. function DaydreamController(vrGamepad) {
  79824. var _this = _super.call(this, vrGamepad) || this;
  79825. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  79826. return _this;
  79827. }
  79828. /**
  79829. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79830. * @param scene scene in which to add meshes
  79831. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79832. */
  79833. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  79834. var _this = this;
  79835. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  79836. _this._defaultModel = newMeshes[1];
  79837. _this.attachToMesh(_this._defaultModel);
  79838. if (meshLoaded) {
  79839. meshLoaded(_this._defaultModel);
  79840. }
  79841. });
  79842. };
  79843. /**
  79844. * Called once for each button that changed state since the last frame
  79845. * @param buttonIdx Which button index changed
  79846. * @param state New state of the button
  79847. * @param changes Which properties on the state changed since last frame
  79848. */
  79849. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79850. // Daydream controller only has 1 GamepadButton (on the trackpad).
  79851. if (buttonIdx === 0) {
  79852. var observable = this.onTriggerStateChangedObservable;
  79853. if (observable) {
  79854. observable.notifyObservers(state);
  79855. }
  79856. }
  79857. else {
  79858. // If the app or home buttons are ever made available
  79859. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  79860. }
  79861. };
  79862. /**
  79863. * Base Url for the controller model.
  79864. */
  79865. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  79866. /**
  79867. * File name for the controller model.
  79868. */
  79869. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  79870. /**
  79871. * Gamepad Id prefix used to identify Daydream Controller.
  79872. */
  79873. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  79874. return DaydreamController;
  79875. }(BABYLON.WebVRController));
  79876. BABYLON.DaydreamController = DaydreamController;
  79877. })(BABYLON || (BABYLON = {}));
  79878. //# sourceMappingURL=babylon.daydreamController.js.map
  79879. var BABYLON;
  79880. (function (BABYLON) {
  79881. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  79882. get: function () {
  79883. if (!this._gamepadManager) {
  79884. this._gamepadManager = new BABYLON.GamepadManager(this);
  79885. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  79886. if (!component) {
  79887. component = new GamepadSystemSceneComponent(this);
  79888. this._addComponent(component);
  79889. }
  79890. }
  79891. return this._gamepadManager;
  79892. },
  79893. enumerable: true,
  79894. configurable: true
  79895. });
  79896. /**
  79897. * Adds a gamepad to the free camera inputs manager
  79898. */
  79899. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  79900. this.add(new BABYLON.FreeCameraGamepadInput());
  79901. return this;
  79902. };
  79903. /**
  79904. * Adds a gamepad to the arc rotate camera inputs manager
  79905. */
  79906. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  79907. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  79908. return this;
  79909. };
  79910. /**
  79911. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  79912. */
  79913. var GamepadSystemSceneComponent = /** @class */ (function () {
  79914. /**
  79915. * Creates a new instance of the component for the given scene
  79916. * @param scene Defines the scene to register the component in
  79917. */
  79918. function GamepadSystemSceneComponent(scene) {
  79919. /**
  79920. * The component name helpfull to identify the component in the list of scene components.
  79921. */
  79922. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  79923. this.scene = scene;
  79924. }
  79925. /**
  79926. * Registers the component in a given scene
  79927. */
  79928. GamepadSystemSceneComponent.prototype.register = function () {
  79929. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  79930. };
  79931. /**
  79932. * Rebuilds the elements related to this component in case of
  79933. * context lost for instance.
  79934. */
  79935. GamepadSystemSceneComponent.prototype.rebuild = function () {
  79936. // Nothing to do for gamepads
  79937. };
  79938. /**
  79939. * Disposes the component and the associated ressources
  79940. */
  79941. GamepadSystemSceneComponent.prototype.dispose = function () {
  79942. var gamepadManager = this.scene._gamepadManager;
  79943. if (gamepadManager) {
  79944. gamepadManager.dispose();
  79945. this.scene._gamepadManager = null;
  79946. }
  79947. };
  79948. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  79949. var gamepadManager = this.scene._gamepadManager;
  79950. if (gamepadManager && gamepadManager._isMonitoring) {
  79951. gamepadManager._checkGamepadsStatus();
  79952. }
  79953. };
  79954. return GamepadSystemSceneComponent;
  79955. }());
  79956. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  79957. })(BABYLON || (BABYLON = {}));
  79958. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  79959. var BABYLON;
  79960. (function (BABYLON) {
  79961. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  79962. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  79963. });
  79964. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  79965. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  79966. });
  79967. /**
  79968. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  79969. * an arc rotate version arcFollowCamera are available.
  79970. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79971. */
  79972. var FollowCamera = /** @class */ (function (_super) {
  79973. __extends(FollowCamera, _super);
  79974. /**
  79975. * Instantiates the follow camera.
  79976. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79977. * @param name Define the name of the camera in the scene
  79978. * @param position Define the position of the camera
  79979. * @param scene Define the scene the camera belong to
  79980. * @param lockedTarget Define the target of the camera
  79981. */
  79982. function FollowCamera(name, position, scene, lockedTarget) {
  79983. if (lockedTarget === void 0) { lockedTarget = null; }
  79984. var _this = _super.call(this, name, position, scene) || this;
  79985. /**
  79986. * Distance the follow camera should follow an object at
  79987. */
  79988. _this.radius = 12;
  79989. /**
  79990. * Define a rotation offset between the camera and the object it follows
  79991. */
  79992. _this.rotationOffset = 0;
  79993. /**
  79994. * Define a height offset between the camera and the object it follows.
  79995. * It can help following an object from the top (like a car chaing a plane)
  79996. */
  79997. _this.heightOffset = 4;
  79998. /**
  79999. * Define how fast the camera can accelerate to follow it s target.
  80000. */
  80001. _this.cameraAcceleration = 0.05;
  80002. /**
  80003. * Define the speed limit of the camera following an object.
  80004. */
  80005. _this.maxCameraSpeed = 20;
  80006. _this.lockedTarget = lockedTarget;
  80007. return _this;
  80008. }
  80009. FollowCamera.prototype._follow = function (cameraTarget) {
  80010. if (!cameraTarget)
  80011. return;
  80012. var yRotation;
  80013. if (cameraTarget.rotationQuaternion) {
  80014. var rotMatrix = new BABYLON.Matrix();
  80015. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  80016. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  80017. }
  80018. else {
  80019. yRotation = cameraTarget.rotation.y;
  80020. }
  80021. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  80022. var targetPosition = cameraTarget.getAbsolutePosition();
  80023. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  80024. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  80025. var dx = targetX - this.position.x;
  80026. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  80027. var dz = (targetZ) - this.position.z;
  80028. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  80029. var vy = dy * this.cameraAcceleration;
  80030. var vz = dz * this.cameraAcceleration * 2;
  80031. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  80032. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  80033. }
  80034. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  80035. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  80036. }
  80037. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  80038. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  80039. }
  80040. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  80041. this.setTarget(targetPosition);
  80042. };
  80043. /** @hidden */
  80044. FollowCamera.prototype._checkInputs = function () {
  80045. _super.prototype._checkInputs.call(this);
  80046. if (this.lockedTarget) {
  80047. this._follow(this.lockedTarget);
  80048. }
  80049. };
  80050. /**
  80051. * Gets the camera class name.
  80052. * @returns the class name
  80053. */
  80054. FollowCamera.prototype.getClassName = function () {
  80055. return "FollowCamera";
  80056. };
  80057. __decorate([
  80058. BABYLON.serialize()
  80059. ], FollowCamera.prototype, "radius", void 0);
  80060. __decorate([
  80061. BABYLON.serialize()
  80062. ], FollowCamera.prototype, "rotationOffset", void 0);
  80063. __decorate([
  80064. BABYLON.serialize()
  80065. ], FollowCamera.prototype, "heightOffset", void 0);
  80066. __decorate([
  80067. BABYLON.serialize()
  80068. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  80069. __decorate([
  80070. BABYLON.serialize()
  80071. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  80072. __decorate([
  80073. BABYLON.serializeAsMeshReference("lockedTargetId")
  80074. ], FollowCamera.prototype, "lockedTarget", void 0);
  80075. return FollowCamera;
  80076. }(BABYLON.TargetCamera));
  80077. BABYLON.FollowCamera = FollowCamera;
  80078. /**
  80079. * Arc Rotate version of the follow camera.
  80080. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  80081. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  80082. */
  80083. var ArcFollowCamera = /** @class */ (function (_super) {
  80084. __extends(ArcFollowCamera, _super);
  80085. /**
  80086. * Instantiates a new ArcFollowCamera
  80087. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  80088. * @param name Define the name of the camera
  80089. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  80090. * @param beta Define the rotation angle of the camera around the elevation axis
  80091. * @param radius Define the radius of the camera from its target point
  80092. * @param target Define the target of the camera
  80093. * @param scene Define the scene the camera belongs to
  80094. */
  80095. function ArcFollowCamera(name,
  80096. /** The longitudinal angle of the camera */
  80097. alpha,
  80098. /** The latitudinal angle of the camera */
  80099. beta,
  80100. /** The radius of the camera from its target */
  80101. radius,
  80102. /** Define the camera target (the messh it should follow) */
  80103. target, scene) {
  80104. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  80105. _this.alpha = alpha;
  80106. _this.beta = beta;
  80107. _this.radius = radius;
  80108. _this.target = target;
  80109. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  80110. _this._follow();
  80111. return _this;
  80112. }
  80113. ArcFollowCamera.prototype._follow = function () {
  80114. if (!this.target) {
  80115. return;
  80116. }
  80117. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  80118. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  80119. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  80120. var targetPosition = this.target.getAbsolutePosition();
  80121. this.position = targetPosition.add(this._cartesianCoordinates);
  80122. this.setTarget(targetPosition);
  80123. };
  80124. /** @hidden */
  80125. ArcFollowCamera.prototype._checkInputs = function () {
  80126. _super.prototype._checkInputs.call(this);
  80127. this._follow();
  80128. };
  80129. /**
  80130. * Returns the class name of the object.
  80131. * It is mostly used internally for serialization purposes.
  80132. */
  80133. ArcFollowCamera.prototype.getClassName = function () {
  80134. return "ArcFollowCamera";
  80135. };
  80136. return ArcFollowCamera;
  80137. }(BABYLON.TargetCamera));
  80138. BABYLON.ArcFollowCamera = ArcFollowCamera;
  80139. })(BABYLON || (BABYLON = {}));
  80140. //# sourceMappingURL=babylon.followCamera.js.map
  80141. var BABYLON;
  80142. (function (BABYLON) {
  80143. /**
  80144. * 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,
  80145. * which still works and will still be found in many Playgrounds.
  80146. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80147. */
  80148. var UniversalCamera = /** @class */ (function (_super) {
  80149. __extends(UniversalCamera, _super);
  80150. /**
  80151. * 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,
  80152. * which still works and will still be found in many Playgrounds.
  80153. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80154. * @param name Define the name of the camera in the scene
  80155. * @param position Define the start position of the camera in the scene
  80156. * @param scene Define the scene the camera belongs to
  80157. */
  80158. function UniversalCamera(name, position, scene) {
  80159. var _this = _super.call(this, name, position, scene) || this;
  80160. _this.inputs.addGamepad();
  80161. return _this;
  80162. }
  80163. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  80164. /**
  80165. * Defines the gamepad rotation sensiblity.
  80166. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  80167. */
  80168. get: function () {
  80169. var gamepad = this.inputs.attached["gamepad"];
  80170. if (gamepad)
  80171. return gamepad.gamepadAngularSensibility;
  80172. return 0;
  80173. },
  80174. set: function (value) {
  80175. var gamepad = this.inputs.attached["gamepad"];
  80176. if (gamepad)
  80177. gamepad.gamepadAngularSensibility = value;
  80178. },
  80179. enumerable: true,
  80180. configurable: true
  80181. });
  80182. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  80183. /**
  80184. * Defines the gamepad move sensiblity.
  80185. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  80186. */
  80187. get: function () {
  80188. var gamepad = this.inputs.attached["gamepad"];
  80189. if (gamepad)
  80190. return gamepad.gamepadMoveSensibility;
  80191. return 0;
  80192. },
  80193. set: function (value) {
  80194. var gamepad = this.inputs.attached["gamepad"];
  80195. if (gamepad)
  80196. gamepad.gamepadMoveSensibility = value;
  80197. },
  80198. enumerable: true,
  80199. configurable: true
  80200. });
  80201. /**
  80202. * Gets the current object class name.
  80203. * @return the class name
  80204. */
  80205. UniversalCamera.prototype.getClassName = function () {
  80206. return "UniversalCamera";
  80207. };
  80208. return UniversalCamera;
  80209. }(BABYLON.TouchCamera));
  80210. BABYLON.UniversalCamera = UniversalCamera;
  80211. })(BABYLON || (BABYLON = {}));
  80212. //# sourceMappingURL=babylon.universalCamera.js.map
  80213. var BABYLON;
  80214. (function (BABYLON) {
  80215. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  80216. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  80217. });
  80218. /**
  80219. * This represents a FPS type of camera. This is only here for back compat purpose.
  80220. * Please use the UniversalCamera instead as both are identical.
  80221. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80222. */
  80223. var GamepadCamera = /** @class */ (function (_super) {
  80224. __extends(GamepadCamera, _super);
  80225. /**
  80226. * Instantiates a new Gamepad Camera
  80227. * This represents a FPS type of camera. This is only here for back compat purpose.
  80228. * Please use the UniversalCamera instead as both are identical.
  80229. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80230. * @param name Define the name of the camera in the scene
  80231. * @param position Define the start position of the camera in the scene
  80232. * @param scene Define the scene the camera belongs to
  80233. */
  80234. function GamepadCamera(name, position, scene) {
  80235. return _super.call(this, name, position, scene) || this;
  80236. }
  80237. /**
  80238. * Gets the current object class name.
  80239. * @return the class name
  80240. */
  80241. GamepadCamera.prototype.getClassName = function () {
  80242. return "GamepadCamera";
  80243. };
  80244. return GamepadCamera;
  80245. }(BABYLON.UniversalCamera));
  80246. BABYLON.GamepadCamera = GamepadCamera;
  80247. })(BABYLON || (BABYLON = {}));
  80248. //# sourceMappingURL=babylon.gamepadCamera.js.map
  80249. var BABYLON;
  80250. (function (BABYLON) {
  80251. var PostProcessRenderPipelineManager = /** @class */ (function () {
  80252. function PostProcessRenderPipelineManager() {
  80253. this._renderPipelines = {};
  80254. }
  80255. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  80256. this._renderPipelines[renderPipeline._name] = renderPipeline;
  80257. };
  80258. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  80259. if (unique === void 0) { unique = false; }
  80260. var renderPipeline = this._renderPipelines[renderPipelineName];
  80261. if (!renderPipeline) {
  80262. return;
  80263. }
  80264. renderPipeline._attachCameras(cameras, unique);
  80265. };
  80266. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  80267. var renderPipeline = this._renderPipelines[renderPipelineName];
  80268. if (!renderPipeline) {
  80269. return;
  80270. }
  80271. renderPipeline._detachCameras(cameras);
  80272. };
  80273. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  80274. var renderPipeline = this._renderPipelines[renderPipelineName];
  80275. if (!renderPipeline) {
  80276. return;
  80277. }
  80278. renderPipeline._enableEffect(renderEffectName, cameras);
  80279. };
  80280. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  80281. var renderPipeline = this._renderPipelines[renderPipelineName];
  80282. if (!renderPipeline) {
  80283. return;
  80284. }
  80285. renderPipeline._disableEffect(renderEffectName, cameras);
  80286. };
  80287. PostProcessRenderPipelineManager.prototype.update = function () {
  80288. for (var renderPipelineName in this._renderPipelines) {
  80289. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  80290. var pipeline = this._renderPipelines[renderPipelineName];
  80291. if (!pipeline.isSupported) {
  80292. pipeline.dispose();
  80293. delete this._renderPipelines[renderPipelineName];
  80294. }
  80295. else {
  80296. pipeline._update();
  80297. }
  80298. }
  80299. }
  80300. };
  80301. /** @hidden */
  80302. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  80303. for (var renderPipelineName in this._renderPipelines) {
  80304. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  80305. var pipeline = this._renderPipelines[renderPipelineName];
  80306. pipeline._rebuild();
  80307. }
  80308. }
  80309. };
  80310. PostProcessRenderPipelineManager.prototype.dispose = function () {
  80311. for (var renderPipelineName in this._renderPipelines) {
  80312. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  80313. var pipeline = this._renderPipelines[renderPipelineName];
  80314. pipeline.dispose();
  80315. }
  80316. }
  80317. };
  80318. return PostProcessRenderPipelineManager;
  80319. }());
  80320. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  80321. })(BABYLON || (BABYLON = {}));
  80322. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  80323. var BABYLON;
  80324. (function (BABYLON) {
  80325. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  80326. get: function () {
  80327. if (!this._postProcessRenderPipelineManager) {
  80328. // Register the G Buffer component to the scene.
  80329. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  80330. if (!component) {
  80331. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  80332. this._addComponent(component);
  80333. }
  80334. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  80335. }
  80336. return this._postProcessRenderPipelineManager;
  80337. },
  80338. enumerable: true,
  80339. configurable: true
  80340. });
  80341. /**
  80342. * Defines the Render Pipeline scene component responsible to rendering pipelines
  80343. */
  80344. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  80345. /**
  80346. * Creates a new instance of the component for the given scene
  80347. * @param scene Defines the scene to register the component in
  80348. */
  80349. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  80350. /**
  80351. * The component name helpfull to identify the component in the list of scene components.
  80352. */
  80353. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  80354. this.scene = scene;
  80355. }
  80356. /**
  80357. * Registers the component in a given scene
  80358. */
  80359. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  80360. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  80361. };
  80362. /**
  80363. * Rebuilds the elements related to this component in case of
  80364. * context lost for instance.
  80365. */
  80366. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  80367. if (this.scene._postProcessRenderPipelineManager) {
  80368. this.scene._postProcessRenderPipelineManager._rebuild();
  80369. }
  80370. };
  80371. /**
  80372. * Disposes the component and the associated ressources
  80373. */
  80374. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  80375. if (this.scene._postProcessRenderPipelineManager) {
  80376. this.scene._postProcessRenderPipelineManager.dispose();
  80377. }
  80378. };
  80379. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  80380. if (this.scene._postProcessRenderPipelineManager) {
  80381. this.scene._postProcessRenderPipelineManager.update();
  80382. }
  80383. };
  80384. return PostProcessRenderPipelineManagerSceneComponent;
  80385. }());
  80386. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  80387. })(BABYLON || (BABYLON = {}));
  80388. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  80389. var BABYLON;
  80390. (function (BABYLON) {
  80391. /**
  80392. * This represents a set of one or more post processes in Babylon.
  80393. * A post process can be used to apply a shader to a texture after it is rendered.
  80394. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  80395. */
  80396. var PostProcessRenderEffect = /** @class */ (function () {
  80397. /**
  80398. * Instantiates a post process render effect.
  80399. * A post process can be used to apply a shader to a texture after it is rendered.
  80400. * @param engine The engine the effect is tied to
  80401. * @param name The name of the effect
  80402. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  80403. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  80404. */
  80405. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  80406. this._name = name;
  80407. this._singleInstance = singleInstance || true;
  80408. this._getPostProcesses = getPostProcesses;
  80409. this._cameras = {};
  80410. this._indicesForCamera = {};
  80411. this._postProcesses = {};
  80412. }
  80413. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  80414. /**
  80415. * Checks if all the post processes in the effect are supported.
  80416. */
  80417. get: function () {
  80418. for (var index in this._postProcesses) {
  80419. if (this._postProcesses.hasOwnProperty(index)) {
  80420. var pps = this._postProcesses[index];
  80421. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  80422. if (!pps[ppIndex].isSupported) {
  80423. return false;
  80424. }
  80425. }
  80426. }
  80427. }
  80428. return true;
  80429. },
  80430. enumerable: true,
  80431. configurable: true
  80432. });
  80433. /**
  80434. * Updates the current state of the effect
  80435. * @hidden
  80436. */
  80437. PostProcessRenderEffect.prototype._update = function () {
  80438. };
  80439. /**
  80440. * Attaches the effect on cameras
  80441. * @param cameras The camera to attach to.
  80442. * @hidden
  80443. */
  80444. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  80445. var _this = this;
  80446. var cameraKey;
  80447. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80448. if (!cams) {
  80449. return;
  80450. }
  80451. for (var i = 0; i < cams.length; i++) {
  80452. var camera = cams[i];
  80453. var cameraName = camera.name;
  80454. if (this._singleInstance) {
  80455. cameraKey = 0;
  80456. }
  80457. else {
  80458. cameraKey = cameraName;
  80459. }
  80460. if (!this._postProcesses[cameraKey]) {
  80461. var postProcess = this._getPostProcesses();
  80462. if (postProcess) {
  80463. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  80464. }
  80465. }
  80466. if (!this._indicesForCamera[cameraName]) {
  80467. this._indicesForCamera[cameraName] = [];
  80468. }
  80469. this._postProcesses[cameraKey].forEach(function (postProcess) {
  80470. var index = camera.attachPostProcess(postProcess);
  80471. _this._indicesForCamera[cameraName].push(index);
  80472. });
  80473. if (!this._cameras[cameraName]) {
  80474. this._cameras[cameraName] = camera;
  80475. }
  80476. }
  80477. };
  80478. /**
  80479. * Detatches the effect on cameras
  80480. * @param cameras The camera to detatch from.
  80481. * @hidden
  80482. */
  80483. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  80484. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80485. if (!cams) {
  80486. return;
  80487. }
  80488. for (var i = 0; i < cams.length; i++) {
  80489. var camera = cams[i];
  80490. var cameraName = camera.name;
  80491. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  80492. camera.detachPostProcess(postProcess);
  80493. });
  80494. if (this._cameras[cameraName]) {
  80495. //this._indicesForCamera.splice(index, 1);
  80496. this._cameras[cameraName] = null;
  80497. }
  80498. }
  80499. };
  80500. /**
  80501. * Enables the effect on given cameras
  80502. * @param cameras The camera to enable.
  80503. * @hidden
  80504. */
  80505. PostProcessRenderEffect.prototype._enable = function (cameras) {
  80506. var _this = this;
  80507. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80508. if (!cams) {
  80509. return;
  80510. }
  80511. for (var i = 0; i < cams.length; i++) {
  80512. var camera = cams[i];
  80513. var cameraName = camera.name;
  80514. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  80515. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  80516. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  80517. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  80518. });
  80519. }
  80520. }
  80521. }
  80522. };
  80523. /**
  80524. * Disables the effect on the given cameras
  80525. * @param cameras The camera to disable.
  80526. * @hidden
  80527. */
  80528. PostProcessRenderEffect.prototype._disable = function (cameras) {
  80529. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80530. if (!cams) {
  80531. return;
  80532. }
  80533. for (var i = 0; i < cams.length; i++) {
  80534. var camera = cams[i];
  80535. var cameraName = camera.name;
  80536. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  80537. camera.detachPostProcess(postProcess);
  80538. });
  80539. }
  80540. };
  80541. /**
  80542. * Gets a list of the post processes contained in the effect.
  80543. * @param camera The camera to get the post processes on.
  80544. * @returns The list of the post processes in the effect.
  80545. */
  80546. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  80547. if (this._singleInstance) {
  80548. return this._postProcesses[0];
  80549. }
  80550. else {
  80551. if (!camera) {
  80552. return null;
  80553. }
  80554. return this._postProcesses[camera.name];
  80555. }
  80556. };
  80557. return PostProcessRenderEffect;
  80558. }());
  80559. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  80560. })(BABYLON || (BABYLON = {}));
  80561. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  80562. var BABYLON;
  80563. (function (BABYLON) {
  80564. var PostProcessRenderPipeline = /** @class */ (function () {
  80565. function PostProcessRenderPipeline(engine, name) {
  80566. this.engine = engine;
  80567. this._name = name;
  80568. this._renderEffects = {};
  80569. this._renderEffectsForIsolatedPass = new Array();
  80570. this._cameras = [];
  80571. }
  80572. PostProcessRenderPipeline.prototype.getClassName = function () {
  80573. return "PostProcessRenderPipeline";
  80574. };
  80575. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  80576. get: function () {
  80577. for (var renderEffectName in this._renderEffects) {
  80578. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80579. if (!this._renderEffects[renderEffectName].isSupported) {
  80580. return false;
  80581. }
  80582. }
  80583. }
  80584. return true;
  80585. },
  80586. enumerable: true,
  80587. configurable: true
  80588. });
  80589. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  80590. this._renderEffects[renderEffect._name] = renderEffect;
  80591. };
  80592. // private
  80593. /** @hidden */
  80594. PostProcessRenderPipeline.prototype._rebuild = function () {
  80595. };
  80596. /** @hidden */
  80597. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  80598. var renderEffects = this._renderEffects[renderEffectName];
  80599. if (!renderEffects) {
  80600. return;
  80601. }
  80602. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  80603. };
  80604. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  80605. var renderEffects = this._renderEffects[renderEffectName];
  80606. if (!renderEffects) {
  80607. return;
  80608. }
  80609. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  80610. };
  80611. /** @hidden */
  80612. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  80613. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80614. if (!cams) {
  80615. return;
  80616. }
  80617. var indicesToDelete = [];
  80618. var i;
  80619. for (i = 0; i < cams.length; i++) {
  80620. var camera = cams[i];
  80621. var cameraName = camera.name;
  80622. if (this._cameras.indexOf(camera) === -1) {
  80623. this._cameras[cameraName] = camera;
  80624. }
  80625. else if (unique) {
  80626. indicesToDelete.push(i);
  80627. }
  80628. }
  80629. for (i = 0; i < indicesToDelete.length; i++) {
  80630. cameras.splice(indicesToDelete[i], 1);
  80631. }
  80632. for (var renderEffectName in this._renderEffects) {
  80633. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80634. this._renderEffects[renderEffectName]._attachCameras(cams);
  80635. }
  80636. }
  80637. };
  80638. /** @hidden */
  80639. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  80640. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80641. if (!cams) {
  80642. return;
  80643. }
  80644. for (var renderEffectName in this._renderEffects) {
  80645. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80646. this._renderEffects[renderEffectName]._detachCameras(cams);
  80647. }
  80648. }
  80649. for (var i = 0; i < cams.length; i++) {
  80650. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  80651. }
  80652. };
  80653. /** @hidden */
  80654. PostProcessRenderPipeline.prototype._update = function () {
  80655. for (var renderEffectName in this._renderEffects) {
  80656. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80657. this._renderEffects[renderEffectName]._update();
  80658. }
  80659. }
  80660. for (var i = 0; i < this._cameras.length; i++) {
  80661. var cameraName = this._cameras[i].name;
  80662. if (this._renderEffectsForIsolatedPass[cameraName]) {
  80663. this._renderEffectsForIsolatedPass[cameraName]._update();
  80664. }
  80665. }
  80666. };
  80667. /** @hidden */
  80668. PostProcessRenderPipeline.prototype._reset = function () {
  80669. this._renderEffects = {};
  80670. this._renderEffectsForIsolatedPass = new Array();
  80671. };
  80672. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  80673. // 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)
  80674. var effectKeys = Object.keys(this._renderEffects);
  80675. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  80676. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  80677. if (postProcesses) {
  80678. postProcesses[0].samples = sampleCount;
  80679. return true;
  80680. }
  80681. }
  80682. return false;
  80683. };
  80684. PostProcessRenderPipeline.prototype.dispose = function () {
  80685. // Must be implemented by children
  80686. };
  80687. __decorate([
  80688. BABYLON.serialize()
  80689. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  80690. return PostProcessRenderPipeline;
  80691. }());
  80692. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  80693. })(BABYLON || (BABYLON = {}));
  80694. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  80695. var BABYLON;
  80696. (function (BABYLON) {
  80697. /**
  80698. * This represents a depth renderer in Babylon.
  80699. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  80700. */
  80701. var DepthRenderer = /** @class */ (function () {
  80702. /**
  80703. * Instantiates a depth renderer
  80704. * @param scene The scene the renderer belongs to
  80705. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  80706. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  80707. */
  80708. function DepthRenderer(scene, type, camera) {
  80709. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  80710. if (camera === void 0) { camera = null; }
  80711. var _this = this;
  80712. /**
  80713. * Specifiess that the depth renderer will only be used within
  80714. * the camera it is created for.
  80715. * This can help forcing its rendering during the camera processing.
  80716. */
  80717. this.useOnlyInActiveCamera = false;
  80718. this._scene = scene;
  80719. // Register the G Buffer component to the scene.
  80720. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  80721. if (!component) {
  80722. component = new BABYLON.DepthRendererSceneComponent(scene);
  80723. scene._addComponent(component);
  80724. }
  80725. this._camera = camera;
  80726. var engine = scene.getEngine();
  80727. // Render target
  80728. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  80729. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80730. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80731. this._depthMap.refreshRate = 1;
  80732. this._depthMap.renderParticles = false;
  80733. this._depthMap.renderList = null;
  80734. // Camera to get depth map from to support multiple concurrent cameras
  80735. this._depthMap.activeCamera = this._camera;
  80736. this._depthMap.ignoreCameraViewport = true;
  80737. this._depthMap.useCameraPostProcesses = false;
  80738. // set default depth value to 1.0 (far away)
  80739. this._depthMap.onClearObservable.add(function (engine) {
  80740. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  80741. });
  80742. // Custom render function
  80743. var renderSubMesh = function (subMesh) {
  80744. var mesh = subMesh.getRenderingMesh();
  80745. var scene = _this._scene;
  80746. var engine = scene.getEngine();
  80747. var material = subMesh.getMaterial();
  80748. if (!material) {
  80749. return;
  80750. }
  80751. // Culling and reverse (right handed system)
  80752. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  80753. // Managing instances
  80754. var batch = mesh._getInstancesRenderList(subMesh._id);
  80755. if (batch.mustReturn) {
  80756. return;
  80757. }
  80758. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  80759. var camera = _this._camera || scene.activeCamera;
  80760. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  80761. engine.enableEffect(_this._effect);
  80762. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  80763. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  80764. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  80765. // Alpha test
  80766. if (material && material.needAlphaTesting()) {
  80767. var alphaTexture = material.getAlphaTestTexture();
  80768. if (alphaTexture) {
  80769. _this._effect.setTexture("diffuseSampler", alphaTexture);
  80770. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  80771. }
  80772. }
  80773. // Bones
  80774. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80775. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80776. }
  80777. // Draw
  80778. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  80779. }
  80780. };
  80781. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80782. var index;
  80783. if (depthOnlySubMeshes.length) {
  80784. engine.setColorWrite(false);
  80785. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80786. renderSubMesh(depthOnlySubMeshes.data[index]);
  80787. }
  80788. engine.setColorWrite(true);
  80789. }
  80790. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80791. renderSubMesh(opaqueSubMeshes.data[index]);
  80792. }
  80793. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80794. renderSubMesh(alphaTestSubMeshes.data[index]);
  80795. }
  80796. };
  80797. }
  80798. /**
  80799. * Creates the depth rendering effect and checks if the effect is ready.
  80800. * @param subMesh The submesh to be used to render the depth map of
  80801. * @param useInstances If multiple world instances should be used
  80802. * @returns if the depth renderer is ready to render the depth map
  80803. */
  80804. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  80805. var material = subMesh.getMaterial();
  80806. if (material.disableDepthWrite) {
  80807. return false;
  80808. }
  80809. var defines = [];
  80810. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80811. var mesh = subMesh.getMesh();
  80812. // Alpha test
  80813. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  80814. defines.push("#define ALPHATEST");
  80815. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80816. attribs.push(BABYLON.VertexBuffer.UVKind);
  80817. defines.push("#define UV1");
  80818. }
  80819. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  80820. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80821. defines.push("#define UV2");
  80822. }
  80823. }
  80824. // Bones
  80825. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80826. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80827. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80828. if (mesh.numBoneInfluencers > 4) {
  80829. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  80830. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  80831. }
  80832. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80833. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  80834. }
  80835. else {
  80836. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80837. }
  80838. // Instances
  80839. if (useInstances) {
  80840. defines.push("#define INSTANCES");
  80841. attribs.push("world0");
  80842. attribs.push("world1");
  80843. attribs.push("world2");
  80844. attribs.push("world3");
  80845. }
  80846. // Get correct effect
  80847. var join = defines.join("\n");
  80848. if (this._cachedDefines !== join) {
  80849. this._cachedDefines = join;
  80850. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  80851. }
  80852. return this._effect.isReady();
  80853. };
  80854. /**
  80855. * Gets the texture which the depth map will be written to.
  80856. * @returns The depth map texture
  80857. */
  80858. DepthRenderer.prototype.getDepthMap = function () {
  80859. return this._depthMap;
  80860. };
  80861. /**
  80862. * Disposes of the depth renderer.
  80863. */
  80864. DepthRenderer.prototype.dispose = function () {
  80865. this._depthMap.dispose();
  80866. };
  80867. return DepthRenderer;
  80868. }());
  80869. BABYLON.DepthRenderer = DepthRenderer;
  80870. })(BABYLON || (BABYLON = {}));
  80871. //# sourceMappingURL=babylon.depthRenderer.js.map
  80872. var BABYLON;
  80873. (function (BABYLON) {
  80874. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  80875. camera = camera || this.activeCamera;
  80876. if (!camera) {
  80877. throw "No camera available to enable depth renderer";
  80878. }
  80879. if (!this._depthRenderer) {
  80880. this._depthRenderer = {};
  80881. }
  80882. if (!this._depthRenderer[camera.id]) {
  80883. var textureType = 0;
  80884. if (this.getEngine().getCaps().textureHalfFloatRender) {
  80885. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  80886. }
  80887. else if (this.getEngine().getCaps().textureFloatRender) {
  80888. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80889. }
  80890. else {
  80891. throw "Depth renderer does not support int texture type";
  80892. }
  80893. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  80894. }
  80895. return this._depthRenderer[camera.id];
  80896. };
  80897. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  80898. camera = camera || this.activeCamera;
  80899. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  80900. return;
  80901. }
  80902. this._depthRenderer[camera.id].dispose();
  80903. delete this._depthRenderer[camera.id];
  80904. };
  80905. /**
  80906. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  80907. * in several rendering techniques.
  80908. */
  80909. var DepthRendererSceneComponent = /** @class */ (function () {
  80910. /**
  80911. * Creates a new instance of the component for the given scene
  80912. * @param scene Defines the scene to register the component in
  80913. */
  80914. function DepthRendererSceneComponent(scene) {
  80915. /**
  80916. * The component name helpfull to identify the component in the list of scene components.
  80917. */
  80918. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  80919. this.scene = scene;
  80920. }
  80921. /**
  80922. * Registers the component in a given scene
  80923. */
  80924. DepthRendererSceneComponent.prototype.register = function () {
  80925. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  80926. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  80927. };
  80928. /**
  80929. * Rebuilds the elements related to this component in case of
  80930. * context lost for instance.
  80931. */
  80932. DepthRendererSceneComponent.prototype.rebuild = function () {
  80933. // Nothing to do for this component
  80934. };
  80935. /**
  80936. * Disposes the component and the associated ressources
  80937. */
  80938. DepthRendererSceneComponent.prototype.dispose = function () {
  80939. for (var key in this.scene._depthRenderer) {
  80940. this.scene._depthRenderer[key].dispose();
  80941. }
  80942. };
  80943. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  80944. if (this.scene._depthRenderer) {
  80945. for (var key in this.scene._depthRenderer) {
  80946. var depthRenderer = this.scene._depthRenderer[key];
  80947. if (!depthRenderer.useOnlyInActiveCamera) {
  80948. renderTargets.push(depthRenderer.getDepthMap());
  80949. }
  80950. }
  80951. }
  80952. };
  80953. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  80954. if (this.scene._depthRenderer) {
  80955. for (var key in this.scene._depthRenderer) {
  80956. var depthRenderer = this.scene._depthRenderer[key];
  80957. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  80958. renderTargets.push(depthRenderer.getDepthMap());
  80959. }
  80960. }
  80961. }
  80962. };
  80963. return DepthRendererSceneComponent;
  80964. }());
  80965. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  80966. })(BABYLON || (BABYLON = {}));
  80967. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  80968. var BABYLON;
  80969. (function (BABYLON) {
  80970. /**
  80971. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  80972. */
  80973. var GeometryBufferRenderer = /** @class */ (function () {
  80974. /**
  80975. * Creates a new G Buffer for the scene
  80976. * @param scene The scene the buffer belongs to
  80977. * @param ratio How big is the buffer related to the main canvas.
  80978. */
  80979. function GeometryBufferRenderer(scene, ratio) {
  80980. if (ratio === void 0) { ratio = 1; }
  80981. this._enablePosition = false;
  80982. this._scene = scene;
  80983. this._ratio = ratio;
  80984. // Register the G Buffer component to the scene.
  80985. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  80986. if (!component) {
  80987. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  80988. scene._addComponent(component);
  80989. }
  80990. // Render target
  80991. this._createRenderTargets();
  80992. }
  80993. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  80994. /**
  80995. * Set the render list (meshes to be rendered) used in the G buffer.
  80996. */
  80997. set: function (meshes) {
  80998. this._multiRenderTarget.renderList = meshes;
  80999. },
  81000. enumerable: true,
  81001. configurable: true
  81002. });
  81003. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  81004. /**
  81005. * Gets wether or not G buffer are supported by the running hardware.
  81006. * This requires draw buffer supports
  81007. */
  81008. get: function () {
  81009. return this._multiRenderTarget.isSupported;
  81010. },
  81011. enumerable: true,
  81012. configurable: true
  81013. });
  81014. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  81015. /**
  81016. * Gets wether or not position are enabled for the G buffer.
  81017. */
  81018. get: function () {
  81019. return this._enablePosition;
  81020. },
  81021. /**
  81022. * Sets wether or not position are enabled for the G buffer.
  81023. */
  81024. set: function (enable) {
  81025. this._enablePosition = enable;
  81026. this.dispose();
  81027. this._createRenderTargets();
  81028. },
  81029. enumerable: true,
  81030. configurable: true
  81031. });
  81032. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  81033. /**
  81034. * Gets the scene associated with the buffer.
  81035. */
  81036. get: function () {
  81037. return this._scene;
  81038. },
  81039. enumerable: true,
  81040. configurable: true
  81041. });
  81042. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  81043. /**
  81044. * Gets the ratio used by the buffer during its creation.
  81045. * How big is the buffer related to the main canvas.
  81046. */
  81047. get: function () {
  81048. return this._ratio;
  81049. },
  81050. enumerable: true,
  81051. configurable: true
  81052. });
  81053. /**
  81054. * Checks wether everything is ready to render a submesh to the G buffer.
  81055. * @param subMesh the submesh to check readiness for
  81056. * @param useInstances is the mesh drawn using instance or not
  81057. * @returns true if ready otherwise false
  81058. */
  81059. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  81060. var material = subMesh.getMaterial();
  81061. if (material && material.disableDepthWrite) {
  81062. return false;
  81063. }
  81064. var defines = [];
  81065. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  81066. var mesh = subMesh.getMesh();
  81067. // Alpha test
  81068. if (material && material.needAlphaTesting()) {
  81069. defines.push("#define ALPHATEST");
  81070. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81071. attribs.push(BABYLON.VertexBuffer.UVKind);
  81072. defines.push("#define UV1");
  81073. }
  81074. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  81075. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81076. defines.push("#define UV2");
  81077. }
  81078. }
  81079. // Buffers
  81080. if (this._enablePosition) {
  81081. defines.push("#define POSITION");
  81082. }
  81083. // Bones
  81084. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  81085. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  81086. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  81087. if (mesh.numBoneInfluencers > 4) {
  81088. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  81089. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  81090. }
  81091. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  81092. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  81093. }
  81094. else {
  81095. defines.push("#define NUM_BONE_INFLUENCERS 0");
  81096. }
  81097. // Instances
  81098. if (useInstances) {
  81099. defines.push("#define INSTANCES");
  81100. attribs.push("world0");
  81101. attribs.push("world1");
  81102. attribs.push("world2");
  81103. attribs.push("world3");
  81104. }
  81105. // Get correct effect
  81106. var join = defines.join("\n");
  81107. if (this._cachedDefines !== join) {
  81108. this._cachedDefines = join;
  81109. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  81110. }
  81111. return this._effect.isReady();
  81112. };
  81113. /**
  81114. * Gets the current underlying G Buffer.
  81115. * @returns the buffer
  81116. */
  81117. GeometryBufferRenderer.prototype.getGBuffer = function () {
  81118. return this._multiRenderTarget;
  81119. };
  81120. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  81121. /**
  81122. * Gets the number of samples used to render the buffer (anti aliasing).
  81123. */
  81124. get: function () {
  81125. return this._multiRenderTarget.samples;
  81126. },
  81127. /**
  81128. * Sets the number of samples used to render the buffer (anti aliasing).
  81129. */
  81130. set: function (value) {
  81131. this._multiRenderTarget.samples = value;
  81132. },
  81133. enumerable: true,
  81134. configurable: true
  81135. });
  81136. /**
  81137. * Disposes the renderer and frees up associated resources.
  81138. */
  81139. GeometryBufferRenderer.prototype.dispose = function () {
  81140. this.getGBuffer().dispose();
  81141. };
  81142. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  81143. var _this = this;
  81144. var engine = this._scene.getEngine();
  81145. var count = this._enablePosition ? 3 : 2;
  81146. 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 });
  81147. if (!this.isSupported) {
  81148. return;
  81149. }
  81150. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81151. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81152. this._multiRenderTarget.refreshRate = 1;
  81153. this._multiRenderTarget.renderParticles = false;
  81154. this._multiRenderTarget.renderList = null;
  81155. // set default depth value to 1.0 (far away)
  81156. this._multiRenderTarget.onClearObservable.add(function (engine) {
  81157. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  81158. });
  81159. // Custom render function
  81160. var renderSubMesh = function (subMesh) {
  81161. var mesh = subMesh.getRenderingMesh();
  81162. var scene = _this._scene;
  81163. var engine = scene.getEngine();
  81164. var material = subMesh.getMaterial();
  81165. if (!material) {
  81166. return;
  81167. }
  81168. // Culling
  81169. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  81170. // Managing instances
  81171. var batch = mesh._getInstancesRenderList(subMesh._id);
  81172. if (batch.mustReturn) {
  81173. return;
  81174. }
  81175. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  81176. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  81177. engine.enableEffect(_this._effect);
  81178. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  81179. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  81180. _this._effect.setMatrix("view", scene.getViewMatrix());
  81181. // Alpha test
  81182. if (material && material.needAlphaTesting()) {
  81183. var alphaTexture = material.getAlphaTestTexture();
  81184. if (alphaTexture) {
  81185. _this._effect.setTexture("diffuseSampler", alphaTexture);
  81186. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  81187. }
  81188. }
  81189. // Bones
  81190. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  81191. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  81192. }
  81193. // Draw
  81194. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  81195. }
  81196. };
  81197. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  81198. var index;
  81199. if (depthOnlySubMeshes.length) {
  81200. engine.setColorWrite(false);
  81201. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  81202. renderSubMesh(depthOnlySubMeshes.data[index]);
  81203. }
  81204. engine.setColorWrite(true);
  81205. }
  81206. for (index = 0; index < opaqueSubMeshes.length; index++) {
  81207. renderSubMesh(opaqueSubMeshes.data[index]);
  81208. }
  81209. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  81210. renderSubMesh(alphaTestSubMeshes.data[index]);
  81211. }
  81212. };
  81213. };
  81214. return GeometryBufferRenderer;
  81215. }());
  81216. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  81217. })(BABYLON || (BABYLON = {}));
  81218. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  81219. var BABYLON;
  81220. (function (BABYLON) {
  81221. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  81222. get: function () {
  81223. this._geometryBufferRenderer;
  81224. },
  81225. set: function (value) {
  81226. if (value && value.isSupported) {
  81227. this._geometryBufferRenderer = value;
  81228. }
  81229. ;
  81230. },
  81231. enumerable: true,
  81232. configurable: true
  81233. });
  81234. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  81235. if (ratio === void 0) { ratio = 1; }
  81236. if (this._geometryBufferRenderer) {
  81237. return this._geometryBufferRenderer;
  81238. }
  81239. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  81240. if (!this._geometryBufferRenderer.isSupported) {
  81241. this._geometryBufferRenderer = null;
  81242. }
  81243. return this._geometryBufferRenderer;
  81244. };
  81245. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  81246. if (!this._geometryBufferRenderer) {
  81247. return;
  81248. }
  81249. this._geometryBufferRenderer.dispose();
  81250. this._geometryBufferRenderer = null;
  81251. };
  81252. /**
  81253. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  81254. * in several rendering techniques.
  81255. */
  81256. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  81257. /**
  81258. * Creates a new instance of the component for the given scene
  81259. * @param scene Defines the scene to register the component in
  81260. */
  81261. function GeometryBufferRendererSceneComponent(scene) {
  81262. /**
  81263. * The component name helpful to identify the component in the list of scene components.
  81264. */
  81265. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  81266. this.scene = scene;
  81267. }
  81268. /**
  81269. * Registers the component in a given scene
  81270. */
  81271. GeometryBufferRendererSceneComponent.prototype.register = function () {
  81272. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  81273. };
  81274. /**
  81275. * Rebuilds the elements related to this component in case of
  81276. * context lost for instance.
  81277. */
  81278. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  81279. // Nothing to do for this component
  81280. };
  81281. /**
  81282. * Disposes the component and the associated ressources
  81283. */
  81284. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  81285. // Nothing to do for this component
  81286. };
  81287. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  81288. if (this.scene._geometryBufferRenderer) {
  81289. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  81290. }
  81291. };
  81292. return GeometryBufferRendererSceneComponent;
  81293. }());
  81294. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  81295. })(BABYLON || (BABYLON = {}));
  81296. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  81297. var BABYLON;
  81298. (function (BABYLON) {
  81299. var SSAORenderingPipeline = /** @class */ (function (_super) {
  81300. __extends(SSAORenderingPipeline, _super);
  81301. /**
  81302. * @constructor
  81303. * @param {string} name - The rendering pipeline name
  81304. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  81305. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  81306. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  81307. */
  81308. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  81309. var _this = _super.call(this, scene.getEngine(), name) || this;
  81310. // Members
  81311. /**
  81312. * The PassPostProcess id in the pipeline that contains the original scene color
  81313. */
  81314. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  81315. /**
  81316. * The SSAO PostProcess id in the pipeline
  81317. */
  81318. _this.SSAORenderEffect = "SSAORenderEffect";
  81319. /**
  81320. * The horizontal blur PostProcess id in the pipeline
  81321. */
  81322. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  81323. /**
  81324. * The vertical blur PostProcess id in the pipeline
  81325. */
  81326. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  81327. /**
  81328. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  81329. */
  81330. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  81331. /**
  81332. * The output strength of the SSAO post-process. Default value is 1.0.
  81333. */
  81334. _this.totalStrength = 1.0;
  81335. /**
  81336. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  81337. */
  81338. _this.radius = 0.0001;
  81339. /**
  81340. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  81341. * Must not be equal to fallOff and superior to fallOff.
  81342. * Default value is 0.975
  81343. */
  81344. _this.area = 0.0075;
  81345. /**
  81346. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  81347. * Must not be equal to area and inferior to area.
  81348. * Default value is 0.0
  81349. */
  81350. _this.fallOff = 0.000001;
  81351. /**
  81352. * The base color of the SSAO post-process
  81353. * The final result is "base + ssao" between [0, 1]
  81354. */
  81355. _this.base = 0.5;
  81356. _this._firstUpdate = true;
  81357. _this._scene = scene;
  81358. // Set up assets
  81359. _this._createRandomTexture();
  81360. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  81361. var ssaoRatio = ratio.ssaoRatio || ratio;
  81362. var combineRatio = ratio.combineRatio || ratio;
  81363. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  81364. _this._createSSAOPostProcess(ssaoRatio);
  81365. _this._createBlurPostProcess(ssaoRatio);
  81366. _this._createSSAOCombinePostProcess(combineRatio);
  81367. // Set up pipeline
  81368. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  81369. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  81370. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  81371. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  81372. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  81373. // Finish
  81374. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81375. if (cameras)
  81376. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  81377. return _this;
  81378. }
  81379. // Public Methods
  81380. /**
  81381. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  81382. */
  81383. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  81384. if (disableDepthRender === void 0) { disableDepthRender = false; }
  81385. for (var i = 0; i < this._scene.cameras.length; i++) {
  81386. var camera = this._scene.cameras[i];
  81387. this._originalColorPostProcess.dispose(camera);
  81388. this._ssaoPostProcess.dispose(camera);
  81389. this._blurHPostProcess.dispose(camera);
  81390. this._blurVPostProcess.dispose(camera);
  81391. this._ssaoCombinePostProcess.dispose(camera);
  81392. }
  81393. this._randomTexture.dispose();
  81394. if (disableDepthRender)
  81395. this._scene.disableDepthRenderer();
  81396. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  81397. _super.prototype.dispose.call(this);
  81398. };
  81399. // Private Methods
  81400. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  81401. var _this = this;
  81402. var size = 16;
  81403. 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);
  81404. 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);
  81405. this._blurHPostProcess.onActivateObservable.add(function () {
  81406. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  81407. _this._blurHPostProcess.kernel = size * dw;
  81408. });
  81409. this._blurVPostProcess.onActivateObservable.add(function () {
  81410. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  81411. _this._blurVPostProcess.kernel = size * dw;
  81412. });
  81413. };
  81414. /** @hidden */
  81415. SSAORenderingPipeline.prototype._rebuild = function () {
  81416. this._firstUpdate = true;
  81417. _super.prototype._rebuild.call(this);
  81418. };
  81419. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  81420. var _this = this;
  81421. var numSamples = 16;
  81422. var sampleSphere = [
  81423. 0.5381, 0.1856, -0.4319,
  81424. 0.1379, 0.2486, 0.4430,
  81425. 0.3371, 0.5679, -0.0057,
  81426. -0.6999, -0.0451, -0.0019,
  81427. 0.0689, -0.1598, -0.8547,
  81428. 0.0560, 0.0069, -0.1843,
  81429. -0.0146, 0.1402, 0.0762,
  81430. 0.0100, -0.1924, -0.0344,
  81431. -0.3577, -0.5301, -0.4358,
  81432. -0.3169, 0.1063, 0.0158,
  81433. 0.0103, -0.5869, 0.0046,
  81434. -0.0897, -0.4940, 0.3287,
  81435. 0.7119, -0.0154, -0.0918,
  81436. -0.0533, 0.0596, -0.5411,
  81437. 0.0352, -0.0631, 0.5460,
  81438. -0.4776, 0.2847, -0.0271
  81439. ];
  81440. var samplesFactor = 1.0 / numSamples;
  81441. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  81442. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  81443. "area", "fallOff", "base", "range", "viewport"
  81444. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  81445. this._ssaoPostProcess.onApply = function (effect) {
  81446. if (_this._firstUpdate) {
  81447. effect.setArray3("sampleSphere", sampleSphere);
  81448. effect.setFloat("samplesFactor", samplesFactor);
  81449. effect.setFloat("randTextureTiles", 4.0);
  81450. }
  81451. effect.setFloat("totalStrength", _this.totalStrength);
  81452. effect.setFloat("radius", _this.radius);
  81453. effect.setFloat("area", _this.area);
  81454. effect.setFloat("fallOff", _this.fallOff);
  81455. effect.setFloat("base", _this.base);
  81456. effect.setTexture("textureSampler", _this._depthTexture);
  81457. effect.setTexture("randomSampler", _this._randomTexture);
  81458. };
  81459. };
  81460. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  81461. var _this = this;
  81462. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  81463. this._ssaoCombinePostProcess.onApply = function (effect) {
  81464. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  81465. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  81466. };
  81467. };
  81468. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  81469. var size = 512;
  81470. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  81471. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  81472. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  81473. var context = this._randomTexture.getContext();
  81474. var rand = function (min, max) {
  81475. return Math.random() * (max - min) + min;
  81476. };
  81477. var randVector = BABYLON.Vector3.Zero();
  81478. for (var x = 0; x < size; x++) {
  81479. for (var y = 0; y < size; y++) {
  81480. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  81481. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  81482. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  81483. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  81484. context.fillRect(x, y, 1, 1);
  81485. }
  81486. }
  81487. this._randomTexture.update(false);
  81488. };
  81489. __decorate([
  81490. BABYLON.serialize()
  81491. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  81492. __decorate([
  81493. BABYLON.serialize()
  81494. ], SSAORenderingPipeline.prototype, "radius", void 0);
  81495. __decorate([
  81496. BABYLON.serialize()
  81497. ], SSAORenderingPipeline.prototype, "area", void 0);
  81498. __decorate([
  81499. BABYLON.serialize()
  81500. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  81501. __decorate([
  81502. BABYLON.serialize()
  81503. ], SSAORenderingPipeline.prototype, "base", void 0);
  81504. return SSAORenderingPipeline;
  81505. }(BABYLON.PostProcessRenderPipeline));
  81506. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  81507. })(BABYLON || (BABYLON = {}));
  81508. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  81509. var BABYLON;
  81510. (function (BABYLON) {
  81511. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  81512. __extends(SSAO2RenderingPipeline, _super);
  81513. /**
  81514. * @constructor
  81515. * @param {string} name - The rendering pipeline name
  81516. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  81517. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }
  81518. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  81519. */
  81520. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  81521. var _this = _super.call(this, scene.getEngine(), name) || this;
  81522. // Members
  81523. /**
  81524. * The PassPostProcess id in the pipeline that contains the original scene color
  81525. */
  81526. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  81527. /**
  81528. * The SSAO PostProcess id in the pipeline
  81529. */
  81530. _this.SSAORenderEffect = "SSAORenderEffect";
  81531. /**
  81532. * The horizontal blur PostProcess id in the pipeline
  81533. */
  81534. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  81535. /**
  81536. * The vertical blur PostProcess id in the pipeline
  81537. */
  81538. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  81539. /**
  81540. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  81541. */
  81542. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  81543. /**
  81544. * The output strength of the SSAO post-process. Default value is 1.0.
  81545. */
  81546. _this.totalStrength = 1.0;
  81547. /**
  81548. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  81549. */
  81550. _this.maxZ = 100.0;
  81551. /**
  81552. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  81553. */
  81554. _this.minZAspect = 0.2;
  81555. _this._samples = 8;
  81556. _this._textureSamples = 1;
  81557. /**
  81558. * Are we using bilateral blur ?
  81559. */
  81560. _this._expensiveBlur = true;
  81561. /**
  81562. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  81563. */
  81564. _this.radius = 2.0;
  81565. /**
  81566. * The base color of the SSAO post-process
  81567. * The final result is "base + ssao" between [0, 1]
  81568. */
  81569. _this.base = 0;
  81570. _this._firstUpdate = true;
  81571. _this._bits = new Uint32Array(1);
  81572. _this._scene = scene;
  81573. _this._ratio = ratio;
  81574. if (!_this.isSupported) {
  81575. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  81576. return _this;
  81577. }
  81578. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  81579. var blurRatio = _this._ratio.blurRatio || ratio;
  81580. // Set up assets
  81581. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  81582. _this._createRandomTexture();
  81583. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  81584. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  81585. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  81586. _this._originalColorPostProcess.samples = _this.textureSamples;
  81587. _this._createSSAOPostProcess(1.0);
  81588. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  81589. _this._createSSAOCombinePostProcess(blurRatio);
  81590. // Set up pipeline
  81591. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  81592. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  81593. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  81594. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  81595. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  81596. // Finish
  81597. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81598. if (cameras)
  81599. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  81600. return _this;
  81601. }
  81602. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  81603. get: function () {
  81604. return this._samples;
  81605. },
  81606. /**
  81607. * Number of samples used for the SSAO calculations. Default value is 8
  81608. */
  81609. set: function (n) {
  81610. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  81611. this._samples = n;
  81612. this._sampleSphere = this._generateHemisphere();
  81613. this._firstUpdate = true;
  81614. },
  81615. enumerable: true,
  81616. configurable: true
  81617. });
  81618. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  81619. get: function () {
  81620. return this._textureSamples;
  81621. },
  81622. /**
  81623. * Number of samples to use for antialiasing
  81624. */
  81625. set: function (n) {
  81626. this._textureSamples = n;
  81627. this._originalColorPostProcess.samples = n;
  81628. this._blurHPostProcess.samples = n;
  81629. this._blurVPostProcess.samples = n;
  81630. this._ssaoPostProcess.samples = n;
  81631. this._ssaoCombinePostProcess.samples = n;
  81632. },
  81633. enumerable: true,
  81634. configurable: true
  81635. });
  81636. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  81637. get: function () {
  81638. return this._expensiveBlur;
  81639. },
  81640. set: function (b) {
  81641. 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"]);
  81642. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  81643. this._expensiveBlur = b;
  81644. this._firstUpdate = true;
  81645. },
  81646. enumerable: true,
  81647. configurable: true
  81648. });
  81649. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  81650. /**
  81651. * Support test.
  81652. */
  81653. get: function () {
  81654. var engine = BABYLON.Engine.LastCreatedEngine;
  81655. if (!engine) {
  81656. return false;
  81657. }
  81658. return engine.getCaps().drawBuffersExtension;
  81659. },
  81660. enumerable: true,
  81661. configurable: true
  81662. });
  81663. // Public Methods
  81664. /**
  81665. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  81666. */
  81667. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  81668. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  81669. for (var i = 0; i < this._scene.cameras.length; i++) {
  81670. var camera = this._scene.cameras[i];
  81671. this._originalColorPostProcess.dispose(camera);
  81672. this._ssaoPostProcess.dispose(camera);
  81673. this._blurHPostProcess.dispose(camera);
  81674. this._blurVPostProcess.dispose(camera);
  81675. this._ssaoCombinePostProcess.dispose(camera);
  81676. }
  81677. this._randomTexture.dispose();
  81678. if (disableGeometryBufferRenderer)
  81679. this._scene.disableGeometryBufferRenderer();
  81680. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  81681. _super.prototype.dispose.call(this);
  81682. };
  81683. // Private Methods
  81684. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  81685. var _this = this;
  81686. this._samplerOffsets = [];
  81687. var expensive = this.expensiveBlur;
  81688. for (var i = -8; i < 8; i++) {
  81689. this._samplerOffsets.push(i * 2 + 0.5);
  81690. }
  81691. 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");
  81692. this._blurHPostProcess.onApply = function (effect) {
  81693. if (!_this._scene.activeCamera) {
  81694. return;
  81695. }
  81696. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  81697. effect.setFloat("near", _this._scene.activeCamera.minZ);
  81698. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  81699. effect.setFloat("radius", _this.radius);
  81700. effect.setTexture("depthSampler", _this._depthTexture);
  81701. if (_this._firstUpdate) {
  81702. effect.setArray("samplerOffsets", _this._samplerOffsets);
  81703. }
  81704. };
  81705. 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");
  81706. this._blurVPostProcess.onApply = function (effect) {
  81707. if (!_this._scene.activeCamera) {
  81708. return;
  81709. }
  81710. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  81711. effect.setFloat("near", _this._scene.activeCamera.minZ);
  81712. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  81713. effect.setFloat("radius", _this.radius);
  81714. effect.setTexture("depthSampler", _this._depthTexture);
  81715. if (_this._firstUpdate) {
  81716. effect.setArray("samplerOffsets", _this._samplerOffsets);
  81717. _this._firstUpdate = false;
  81718. }
  81719. };
  81720. this._blurHPostProcess.samples = this.textureSamples;
  81721. this._blurVPostProcess.samples = this.textureSamples;
  81722. };
  81723. /** @hidden */
  81724. SSAO2RenderingPipeline.prototype._rebuild = function () {
  81725. this._firstUpdate = true;
  81726. _super.prototype._rebuild.call(this);
  81727. };
  81728. //Van der Corput radical inverse
  81729. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  81730. this._bits[0] = i;
  81731. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  81732. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  81733. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  81734. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  81735. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  81736. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  81737. };
  81738. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  81739. return [i / n, this._radicalInverse_VdC(i)];
  81740. };
  81741. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  81742. var phi = v * 2.0 * Math.PI;
  81743. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  81744. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  81745. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  81746. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  81747. };
  81748. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  81749. var numSamples = this.samples;
  81750. var result = [];
  81751. var vector;
  81752. var i = 0;
  81753. while (i < numSamples) {
  81754. if (numSamples < 16) {
  81755. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  81756. }
  81757. else {
  81758. var rand = this._hammersley(i, numSamples);
  81759. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  81760. }
  81761. result.push(vector.x, vector.y, vector.z);
  81762. i++;
  81763. }
  81764. return result;
  81765. };
  81766. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  81767. var _this = this;
  81768. var numSamples = this.samples;
  81769. this._sampleSphere = this._generateHemisphere();
  81770. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  81771. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  81772. "base", "range", "projection", "near", "far", "texelSize",
  81773. "xViewport", "yViewport", "maxZ", "minZAspect"
  81774. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  81775. this._ssaoPostProcess.onApply = function (effect) {
  81776. if (_this._firstUpdate) {
  81777. effect.setArray3("sampleSphere", _this._sampleSphere);
  81778. effect.setFloat("randTextureTiles", 32.0);
  81779. }
  81780. if (!_this._scene.activeCamera) {
  81781. return;
  81782. }
  81783. effect.setFloat("samplesFactor", 1 / _this.samples);
  81784. effect.setFloat("totalStrength", _this.totalStrength);
  81785. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  81786. effect.setFloat("radius", _this.radius);
  81787. effect.setFloat("maxZ", _this.maxZ);
  81788. effect.setFloat("minZAspect", _this.minZAspect);
  81789. effect.setFloat("base", _this.base);
  81790. effect.setFloat("near", _this._scene.activeCamera.minZ);
  81791. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  81792. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  81793. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  81794. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  81795. effect.setTexture("textureSampler", _this._depthTexture);
  81796. effect.setTexture("normalSampler", _this._normalTexture);
  81797. effect.setTexture("randomSampler", _this._randomTexture);
  81798. };
  81799. this._ssaoPostProcess.samples = this.textureSamples;
  81800. };
  81801. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  81802. var _this = this;
  81803. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  81804. this._ssaoCombinePostProcess.onApply = function (effect) {
  81805. var viewport = _this._scene.activeCamera.viewport;
  81806. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  81807. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  81808. };
  81809. this._ssaoCombinePostProcess.samples = this.textureSamples;
  81810. };
  81811. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  81812. var size = 128;
  81813. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  81814. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  81815. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  81816. var context = this._randomTexture.getContext();
  81817. var rand = function (min, max) {
  81818. return Math.random() * (max - min) + min;
  81819. };
  81820. var randVector = BABYLON.Vector3.Zero();
  81821. for (var x = 0; x < size; x++) {
  81822. for (var y = 0; y < size; y++) {
  81823. randVector.x = rand(0.0, 1.0);
  81824. randVector.y = rand(0.0, 1.0);
  81825. randVector.z = 0.0;
  81826. randVector.normalize();
  81827. randVector.scaleInPlace(255);
  81828. randVector.x = Math.floor(randVector.x);
  81829. randVector.y = Math.floor(randVector.y);
  81830. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  81831. context.fillRect(x, y, 1, 1);
  81832. }
  81833. }
  81834. this._randomTexture.update(false);
  81835. };
  81836. /**
  81837. * Serialize the rendering pipeline (Used when exporting)
  81838. * @returns the serialized object
  81839. */
  81840. SSAO2RenderingPipeline.prototype.serialize = function () {
  81841. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81842. serializationObject.customType = "SSAO2RenderingPipeline";
  81843. return serializationObject;
  81844. };
  81845. /**
  81846. * Parse the serialized pipeline
  81847. * @param source Source pipeline.
  81848. * @param scene The scene to load the pipeline to.
  81849. * @param rootUrl The URL of the serialized pipeline.
  81850. * @returns An instantiated pipeline from the serialized object.
  81851. */
  81852. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  81853. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  81854. };
  81855. __decorate([
  81856. BABYLON.serialize()
  81857. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  81858. __decorate([
  81859. BABYLON.serialize()
  81860. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  81861. __decorate([
  81862. BABYLON.serialize()
  81863. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  81864. __decorate([
  81865. BABYLON.serialize("samples")
  81866. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  81867. __decorate([
  81868. BABYLON.serialize("textureSamples")
  81869. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  81870. __decorate([
  81871. BABYLON.serialize()
  81872. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  81873. __decorate([
  81874. BABYLON.serialize("expensiveBlur")
  81875. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  81876. __decorate([
  81877. BABYLON.serialize()
  81878. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  81879. __decorate([
  81880. BABYLON.serialize()
  81881. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  81882. return SSAO2RenderingPipeline;
  81883. }(BABYLON.PostProcessRenderPipeline));
  81884. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  81885. })(BABYLON || (BABYLON = {}));
  81886. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  81887. // BABYLON.JS Chromatic Aberration GLSL Shader
  81888. // Author: Olivier Guyot
  81889. // Separates very slightly R, G and B colors on the edges of the screen
  81890. // Inspired by Francois Tarlier & Martins Upitis
  81891. var BABYLON;
  81892. (function (BABYLON) {
  81893. var LensRenderingPipeline = /** @class */ (function (_super) {
  81894. __extends(LensRenderingPipeline, _super);
  81895. /**
  81896. * @constructor
  81897. *
  81898. * Effect parameters are as follow:
  81899. * {
  81900. * chromatic_aberration: number; // from 0 to x (1 for realism)
  81901. * edge_blur: number; // from 0 to x (1 for realism)
  81902. * distortion: number; // from 0 to x (1 for realism)
  81903. * grain_amount: number; // from 0 to 1
  81904. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  81905. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  81906. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  81907. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  81908. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  81909. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  81910. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  81911. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  81912. * }
  81913. * Note: if an effect parameter is unset, effect is disabled
  81914. *
  81915. * @param {string} name - The rendering pipeline name
  81916. * @param {object} parameters - An object containing all parameters (see above)
  81917. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  81918. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  81919. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  81920. */
  81921. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  81922. if (ratio === void 0) { ratio = 1.0; }
  81923. var _this = _super.call(this, scene.getEngine(), name) || this;
  81924. // Lens effects can be of the following:
  81925. // - chromatic aberration (slight shift of RGB colors)
  81926. // - blur on the edge of the lens
  81927. // - lens distortion
  81928. // - depth-of-field blur & highlights enhancing
  81929. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  81930. // - grain effect (noise or custom texture)
  81931. // Two additional texture samplers are needed:
  81932. // - depth map (for depth-of-field)
  81933. // - grain texture
  81934. /**
  81935. * The chromatic aberration PostProcess id in the pipeline
  81936. */
  81937. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  81938. /**
  81939. * The highlights enhancing PostProcess id in the pipeline
  81940. */
  81941. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  81942. /**
  81943. * The depth-of-field PostProcess id in the pipeline
  81944. */
  81945. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  81946. _this._scene = scene;
  81947. // Fetch texture samplers
  81948. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  81949. if (parameters.grain_texture) {
  81950. _this._grainTexture = parameters.grain_texture;
  81951. }
  81952. else {
  81953. _this._createGrainTexture();
  81954. }
  81955. // save parameters
  81956. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  81957. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  81958. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  81959. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  81960. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  81961. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  81962. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  81963. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  81964. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  81965. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  81966. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  81967. // Create effects
  81968. _this._createChromaticAberrationPostProcess(ratio);
  81969. _this._createHighlightsPostProcess(ratio);
  81970. _this._createDepthOfFieldPostProcess(ratio / 4);
  81971. // Set up pipeline
  81972. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  81973. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  81974. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  81975. if (_this._highlightsGain === -1) {
  81976. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  81977. }
  81978. // Finish
  81979. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81980. if (cameras) {
  81981. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  81982. }
  81983. return _this;
  81984. }
  81985. // public methods (self explanatory)
  81986. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  81987. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  81988. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  81989. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  81990. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  81991. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  81992. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  81993. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  81994. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  81995. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  81996. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  81997. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  81998. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  81999. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  82000. };
  82001. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  82002. this._highlightsPostProcess.updateEffect();
  82003. };
  82004. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  82005. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  82006. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  82007. this._highlightsGain = amount;
  82008. };
  82009. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  82010. if (this._highlightsGain === -1) {
  82011. this._highlightsGain = 1.0;
  82012. }
  82013. this._highlightsThreshold = amount;
  82014. };
  82015. LensRenderingPipeline.prototype.disableHighlights = function () {
  82016. this._highlightsGain = -1;
  82017. };
  82018. /**
  82019. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  82020. */
  82021. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  82022. if (disableDepthRender === void 0) { disableDepthRender = false; }
  82023. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  82024. this._chromaticAberrationPostProcess = null;
  82025. this._highlightsPostProcess = null;
  82026. this._depthOfFieldPostProcess = null;
  82027. this._grainTexture.dispose();
  82028. if (disableDepthRender)
  82029. this._scene.disableDepthRenderer();
  82030. };
  82031. // colors shifting and distortion
  82032. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  82033. var _this = this;
  82034. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  82035. [], // samplers
  82036. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  82037. this._chromaticAberrationPostProcess.onApply = function (effect) {
  82038. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  82039. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  82040. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  82041. effect.setFloat('radialIntensity', 1);
  82042. effect.setFloat2('direction', 17, 17);
  82043. effect.setFloat2('centerPosition', 0.5, 0.5);
  82044. };
  82045. };
  82046. // highlights enhancing
  82047. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  82048. var _this = this;
  82049. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  82050. [], // samplers
  82051. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  82052. this._highlightsPostProcess.onApply = function (effect) {
  82053. effect.setFloat('gain', _this._highlightsGain);
  82054. effect.setFloat('threshold', _this._highlightsThreshold);
  82055. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  82056. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  82057. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  82058. };
  82059. };
  82060. // colors shifting and distortion
  82061. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  82062. var _this = this;
  82063. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  82064. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  82065. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  82066. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  82067. this._depthOfFieldPostProcess.onApply = function (effect) {
  82068. effect.setTexture("depthSampler", _this._depthTexture);
  82069. effect.setTexture("grainSampler", _this._grainTexture);
  82070. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  82071. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  82072. effect.setFloat('grain_amount', _this._grainAmount);
  82073. effect.setBool('blur_noise', _this._blurNoise);
  82074. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  82075. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  82076. effect.setFloat('distortion', _this._distortion);
  82077. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  82078. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  82079. effect.setFloat('aperture', _this._dofAperture);
  82080. effect.setFloat('darken', _this._dofDarken);
  82081. effect.setFloat('edge_blur', _this._edgeBlur);
  82082. effect.setBool('highlights', (_this._highlightsGain !== -1));
  82083. if (_this._scene.activeCamera) {
  82084. effect.setFloat('near', _this._scene.activeCamera.minZ);
  82085. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  82086. }
  82087. };
  82088. };
  82089. // creates a black and white random noise texture, 512x512
  82090. LensRenderingPipeline.prototype._createGrainTexture = function () {
  82091. var size = 512;
  82092. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82093. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  82094. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  82095. var context = this._grainTexture.getContext();
  82096. var rand = function (min, max) {
  82097. return Math.random() * (max - min) + min;
  82098. };
  82099. var value;
  82100. for (var x = 0; x < size; x++) {
  82101. for (var y = 0; y < size; y++) {
  82102. value = Math.floor(rand(0.42, 0.58) * 255);
  82103. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  82104. context.fillRect(x, y, 1, 1);
  82105. }
  82106. }
  82107. this._grainTexture.update(false);
  82108. };
  82109. return LensRenderingPipeline;
  82110. }(BABYLON.PostProcessRenderPipeline));
  82111. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  82112. })(BABYLON || (BABYLON = {}));
  82113. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  82114. var BABYLON;
  82115. (function (BABYLON) {
  82116. var StandardRenderingPipeline = /** @class */ (function (_super) {
  82117. __extends(StandardRenderingPipeline, _super);
  82118. /**
  82119. * @constructor
  82120. * @param {string} name - The rendering pipeline name
  82121. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  82122. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  82123. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  82124. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  82125. */
  82126. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  82127. if (originalPostProcess === void 0) { originalPostProcess = null; }
  82128. var _this = _super.call(this, scene.getEngine(), name) || this;
  82129. /**
  82130. * Post-process used to down scale an image x4
  82131. */
  82132. _this.downSampleX4PostProcess = null;
  82133. /**
  82134. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  82135. */
  82136. _this.brightPassPostProcess = null;
  82137. /**
  82138. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  82139. */
  82140. _this.blurHPostProcesses = [];
  82141. /**
  82142. * Post-process array storing all the vertical blur post-processes used by the pipeline
  82143. */
  82144. _this.blurVPostProcesses = [];
  82145. /**
  82146. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  82147. */
  82148. _this.textureAdderPostProcess = null;
  82149. /**
  82150. * Post-process used to create volumetric lighting effect
  82151. */
  82152. _this.volumetricLightPostProcess = null;
  82153. /**
  82154. * Post-process used to smooth the previous volumetric light post-process on the X axis
  82155. */
  82156. _this.volumetricLightSmoothXPostProcess = null;
  82157. /**
  82158. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  82159. */
  82160. _this.volumetricLightSmoothYPostProcess = null;
  82161. /**
  82162. * Post-process used to merge the volumetric light effect and the real scene color
  82163. */
  82164. _this.volumetricLightMergePostProces = null;
  82165. /**
  82166. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  82167. */
  82168. _this.volumetricLightFinalPostProcess = null;
  82169. /**
  82170. * Base post-process used to calculate the average luminance of the final image for HDR
  82171. */
  82172. _this.luminancePostProcess = null;
  82173. /**
  82174. * Post-processes used to create down sample post-processes in order to get
  82175. * the average luminance of the final image for HDR
  82176. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  82177. */
  82178. _this.luminanceDownSamplePostProcesses = [];
  82179. /**
  82180. * Post-process used to create a HDR effect (light adaptation)
  82181. */
  82182. _this.hdrPostProcess = null;
  82183. /**
  82184. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  82185. */
  82186. _this.textureAdderFinalPostProcess = null;
  82187. /**
  82188. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  82189. */
  82190. _this.lensFlareFinalPostProcess = null;
  82191. /**
  82192. * Post-process used to merge the final HDR post-process and the real scene color
  82193. */
  82194. _this.hdrFinalPostProcess = null;
  82195. /**
  82196. * Post-process used to create a lens flare effect
  82197. */
  82198. _this.lensFlarePostProcess = null;
  82199. /**
  82200. * Post-process that merges the result of the lens flare post-process and the real scene color
  82201. */
  82202. _this.lensFlareComposePostProcess = null;
  82203. /**
  82204. * Post-process used to create a motion blur effect
  82205. */
  82206. _this.motionBlurPostProcess = null;
  82207. /**
  82208. * Post-process used to create a depth of field effect
  82209. */
  82210. _this.depthOfFieldPostProcess = null;
  82211. /**
  82212. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  82213. */
  82214. _this.fxaaPostProcess = null;
  82215. // Values
  82216. /**
  82217. * Represents the brightness threshold in order to configure the illuminated surfaces
  82218. */
  82219. _this.brightThreshold = 1.0;
  82220. /**
  82221. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  82222. */
  82223. _this.blurWidth = 512.0;
  82224. /**
  82225. * Sets if the blur for highlighted surfaces must be only horizontal
  82226. */
  82227. _this.horizontalBlur = false;
  82228. /**
  82229. * Sets the overall exposure used by the pipeline
  82230. */
  82231. _this.exposure = 1.0;
  82232. /**
  82233. * Texture used typically to simulate "dirty" on camera lens
  82234. */
  82235. _this.lensTexture = null;
  82236. /**
  82237. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  82238. */
  82239. _this.volumetricLightCoefficient = 0.2;
  82240. /**
  82241. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  82242. */
  82243. _this.volumetricLightPower = 4.0;
  82244. /**
  82245. * Used the set the blur intensity to smooth the volumetric lights
  82246. */
  82247. _this.volumetricLightBlurScale = 64.0;
  82248. /**
  82249. * Light (spot or directional) used to generate the volumetric lights rays
  82250. * The source light must have a shadow generate so the pipeline can get its
  82251. * depth map
  82252. */
  82253. _this.sourceLight = null;
  82254. /**
  82255. * For eye adaptation, represents the minimum luminance the eye can see
  82256. */
  82257. _this.hdrMinimumLuminance = 1.0;
  82258. /**
  82259. * For eye adaptation, represents the decrease luminance speed
  82260. */
  82261. _this.hdrDecreaseRate = 0.5;
  82262. /**
  82263. * For eye adaptation, represents the increase luminance speed
  82264. */
  82265. _this.hdrIncreaseRate = 0.5;
  82266. /**
  82267. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  82268. */
  82269. _this.lensColorTexture = null;
  82270. /**
  82271. * The overall strengh for the lens flare effect
  82272. */
  82273. _this.lensFlareStrength = 20.0;
  82274. /**
  82275. * Dispersion coefficient for lens flare ghosts
  82276. */
  82277. _this.lensFlareGhostDispersal = 1.4;
  82278. /**
  82279. * Main lens flare halo width
  82280. */
  82281. _this.lensFlareHaloWidth = 0.7;
  82282. /**
  82283. * Based on the lens distortion effect, defines how much the lens flare result
  82284. * is distorted
  82285. */
  82286. _this.lensFlareDistortionStrength = 16.0;
  82287. /**
  82288. * Lens star texture must be used to simulate rays on the flares and is available
  82289. * in the documentation
  82290. */
  82291. _this.lensStarTexture = null;
  82292. /**
  82293. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  82294. * flare effect by taking account of the dirt texture
  82295. */
  82296. _this.lensFlareDirtTexture = null;
  82297. /**
  82298. * Represents the focal length for the depth of field effect
  82299. */
  82300. _this.depthOfFieldDistance = 10.0;
  82301. /**
  82302. * Represents the blur intensity for the blurred part of the depth of field effect
  82303. */
  82304. _this.depthOfFieldBlurWidth = 64.0;
  82305. /**
  82306. * For motion blur, defines how much the image is blurred by the movement
  82307. */
  82308. _this.motionStrength = 1.0;
  82309. /**
  82310. * List of animations for the pipeline (IAnimatable implementation)
  82311. */
  82312. _this.animations = [];
  82313. _this._currentDepthOfFieldSource = null;
  82314. _this._hdrCurrentLuminance = 1.0;
  82315. // Getters and setters
  82316. _this._bloomEnabled = false;
  82317. _this._depthOfFieldEnabled = false;
  82318. _this._vlsEnabled = false;
  82319. _this._lensFlareEnabled = false;
  82320. _this._hdrEnabled = false;
  82321. _this._motionBlurEnabled = false;
  82322. _this._fxaaEnabled = false;
  82323. _this._motionBlurSamples = 64.0;
  82324. _this._volumetricLightStepsCount = 50.0;
  82325. _this._samples = 1;
  82326. _this._cameras = cameras || [];
  82327. // Initialize
  82328. _this._scene = scene;
  82329. _this._basePostProcess = originalPostProcess;
  82330. _this._ratio = ratio;
  82331. // Misc
  82332. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82333. // Finish
  82334. scene.postProcessRenderPipelineManager.addPipeline(_this);
  82335. _this._buildPipeline();
  82336. return _this;
  82337. }
  82338. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  82339. /**
  82340. * Specifies if the bloom pipeline is enabled
  82341. */
  82342. get: function () {
  82343. return this._bloomEnabled;
  82344. },
  82345. set: function (enabled) {
  82346. if (this._bloomEnabled === enabled) {
  82347. return;
  82348. }
  82349. this._bloomEnabled = enabled;
  82350. this._buildPipeline();
  82351. },
  82352. enumerable: true,
  82353. configurable: true
  82354. });
  82355. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  82356. /**
  82357. * Specifies if the depth of field pipeline is enabed
  82358. */
  82359. get: function () {
  82360. return this._depthOfFieldEnabled;
  82361. },
  82362. set: function (enabled) {
  82363. if (this._depthOfFieldEnabled === enabled) {
  82364. return;
  82365. }
  82366. this._depthOfFieldEnabled = enabled;
  82367. this._buildPipeline();
  82368. },
  82369. enumerable: true,
  82370. configurable: true
  82371. });
  82372. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  82373. /**
  82374. * Specifies if the lens flare pipeline is enabed
  82375. */
  82376. get: function () {
  82377. return this._lensFlareEnabled;
  82378. },
  82379. set: function (enabled) {
  82380. if (this._lensFlareEnabled === enabled) {
  82381. return;
  82382. }
  82383. this._lensFlareEnabled = enabled;
  82384. this._buildPipeline();
  82385. },
  82386. enumerable: true,
  82387. configurable: true
  82388. });
  82389. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  82390. /**
  82391. * Specifies if the HDR pipeline is enabled
  82392. */
  82393. get: function () {
  82394. return this._hdrEnabled;
  82395. },
  82396. set: function (enabled) {
  82397. if (this._hdrEnabled === enabled) {
  82398. return;
  82399. }
  82400. this._hdrEnabled = enabled;
  82401. this._buildPipeline();
  82402. },
  82403. enumerable: true,
  82404. configurable: true
  82405. });
  82406. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  82407. /**
  82408. * Specifies if the volumetric lights scattering effect is enabled
  82409. */
  82410. get: function () {
  82411. return this._vlsEnabled;
  82412. },
  82413. set: function (enabled) {
  82414. if (this._vlsEnabled === enabled) {
  82415. return;
  82416. }
  82417. if (enabled) {
  82418. var geometry = this._scene.enableGeometryBufferRenderer();
  82419. if (!geometry) {
  82420. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  82421. return;
  82422. }
  82423. }
  82424. this._vlsEnabled = enabled;
  82425. this._buildPipeline();
  82426. },
  82427. enumerable: true,
  82428. configurable: true
  82429. });
  82430. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  82431. /**
  82432. * Specifies if the motion blur effect is enabled
  82433. */
  82434. get: function () {
  82435. return this._motionBlurEnabled;
  82436. },
  82437. set: function (enabled) {
  82438. if (this._motionBlurEnabled === enabled) {
  82439. return;
  82440. }
  82441. this._motionBlurEnabled = enabled;
  82442. this._buildPipeline();
  82443. },
  82444. enumerable: true,
  82445. configurable: true
  82446. });
  82447. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  82448. /**
  82449. * Specifies if anti-aliasing is enabled
  82450. */
  82451. get: function () {
  82452. return this._fxaaEnabled;
  82453. },
  82454. set: function (enabled) {
  82455. if (this._fxaaEnabled === enabled) {
  82456. return;
  82457. }
  82458. this._fxaaEnabled = enabled;
  82459. this._buildPipeline();
  82460. },
  82461. enumerable: true,
  82462. configurable: true
  82463. });
  82464. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  82465. /**
  82466. * Specifies the number of steps used to calculate the volumetric lights
  82467. * Typically in interval [50, 200]
  82468. */
  82469. get: function () {
  82470. return this._volumetricLightStepsCount;
  82471. },
  82472. set: function (count) {
  82473. if (this.volumetricLightPostProcess) {
  82474. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  82475. }
  82476. this._volumetricLightStepsCount = count;
  82477. },
  82478. enumerable: true,
  82479. configurable: true
  82480. });
  82481. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  82482. /**
  82483. * Specifies the number of samples used for the motion blur effect
  82484. * Typically in interval [16, 64]
  82485. */
  82486. get: function () {
  82487. return this._motionBlurSamples;
  82488. },
  82489. set: function (samples) {
  82490. if (this.motionBlurPostProcess) {
  82491. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  82492. }
  82493. this._motionBlurSamples = samples;
  82494. },
  82495. enumerable: true,
  82496. configurable: true
  82497. });
  82498. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  82499. /**
  82500. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  82501. */
  82502. get: function () {
  82503. return this._samples;
  82504. },
  82505. set: function (sampleCount) {
  82506. if (this._samples === sampleCount) {
  82507. return;
  82508. }
  82509. this._samples = sampleCount;
  82510. this._buildPipeline();
  82511. },
  82512. enumerable: true,
  82513. configurable: true
  82514. });
  82515. StandardRenderingPipeline.prototype._buildPipeline = function () {
  82516. var _this = this;
  82517. var ratio = this._ratio;
  82518. var scene = this._scene;
  82519. this._disposePostProcesses();
  82520. this._reset();
  82521. // Create pass post-process
  82522. if (!this._basePostProcess) {
  82523. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  82524. this.originalPostProcess.onApply = function (effect) {
  82525. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  82526. };
  82527. }
  82528. else {
  82529. this.originalPostProcess = this._basePostProcess;
  82530. }
  82531. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  82532. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  82533. }
  82534. this._currentDepthOfFieldSource = this.originalPostProcess;
  82535. if (this._bloomEnabled) {
  82536. // Create down sample X4 post-process
  82537. this._createDownSampleX4PostProcess(scene, ratio / 2);
  82538. // Create bright pass post-process
  82539. this._createBrightPassPostProcess(scene, ratio / 2);
  82540. // Create gaussian blur post-processes (down sampling blurs)
  82541. this._createBlurPostProcesses(scene, ratio / 4, 1);
  82542. // Create texture adder post-process
  82543. this._createTextureAdderPostProcess(scene, ratio);
  82544. // Create depth-of-field source post-process
  82545. 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);
  82546. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  82547. }
  82548. if (this._vlsEnabled) {
  82549. // Create volumetric light
  82550. this._createVolumetricLightPostProcess(scene, ratio);
  82551. // Create volumetric light final post-process
  82552. 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);
  82553. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  82554. }
  82555. if (this._lensFlareEnabled) {
  82556. // Create lens flare post-process
  82557. this._createLensFlarePostProcess(scene, ratio);
  82558. // Create depth-of-field source post-process post lens-flare and disable it now
  82559. 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);
  82560. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  82561. }
  82562. if (this._hdrEnabled) {
  82563. // Create luminance
  82564. this._createLuminancePostProcesses(scene, this._floatTextureType);
  82565. // Create HDR
  82566. this._createHdrPostProcess(scene, ratio);
  82567. // Create depth-of-field source post-process post hdr and disable it now
  82568. 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);
  82569. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  82570. }
  82571. if (this._depthOfFieldEnabled) {
  82572. // Create gaussian blur used by depth-of-field
  82573. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  82574. // Create depth-of-field post-process
  82575. this._createDepthOfFieldPostProcess(scene, ratio);
  82576. }
  82577. if (this._motionBlurEnabled) {
  82578. // Create motion blur post-process
  82579. this._createMotionBlurPostProcess(scene, ratio);
  82580. }
  82581. if (this._fxaaEnabled) {
  82582. // Create fxaa post-process
  82583. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82584. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  82585. }
  82586. if (this._cameras !== null) {
  82587. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  82588. }
  82589. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  82590. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  82591. }
  82592. };
  82593. // Down Sample X4 Post-Processs
  82594. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  82595. var _this = this;
  82596. var downSampleX4Offsets = new Array(32);
  82597. 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);
  82598. this.downSampleX4PostProcess.onApply = function (effect) {
  82599. var id = 0;
  82600. var width = _this.downSampleX4PostProcess.width;
  82601. var height = _this.downSampleX4PostProcess.height;
  82602. for (var i = -2; i < 2; i++) {
  82603. for (var j = -2; j < 2; j++) {
  82604. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  82605. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  82606. id += 2;
  82607. }
  82608. }
  82609. effect.setArray2("dsOffsets", downSampleX4Offsets);
  82610. };
  82611. // Add to pipeline
  82612. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  82613. };
  82614. // Brightpass Post-Process
  82615. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  82616. var _this = this;
  82617. var brightOffsets = new Array(8);
  82618. 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);
  82619. this.brightPassPostProcess.onApply = function (effect) {
  82620. var sU = (1.0 / _this.brightPassPostProcess.width);
  82621. var sV = (1.0 / _this.brightPassPostProcess.height);
  82622. brightOffsets[0] = -0.5 * sU;
  82623. brightOffsets[1] = 0.5 * sV;
  82624. brightOffsets[2] = 0.5 * sU;
  82625. brightOffsets[3] = 0.5 * sV;
  82626. brightOffsets[4] = -0.5 * sU;
  82627. brightOffsets[5] = -0.5 * sV;
  82628. brightOffsets[6] = 0.5 * sU;
  82629. brightOffsets[7] = -0.5 * sV;
  82630. effect.setArray2("dsOffsets", brightOffsets);
  82631. effect.setFloat("brightThreshold", _this.brightThreshold);
  82632. };
  82633. // Add to pipeline
  82634. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  82635. };
  82636. // Create blur H&V post-processes
  82637. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  82638. var _this = this;
  82639. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  82640. var engine = scene.getEngine();
  82641. 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);
  82642. 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);
  82643. blurX.onActivateObservable.add(function () {
  82644. var dw = blurX.width / engine.getRenderWidth();
  82645. blurX.kernel = _this[blurWidthKey] * dw;
  82646. });
  82647. blurY.onActivateObservable.add(function () {
  82648. var dw = blurY.height / engine.getRenderHeight();
  82649. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  82650. });
  82651. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  82652. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  82653. this.blurHPostProcesses.push(blurX);
  82654. this.blurVPostProcesses.push(blurY);
  82655. };
  82656. // Create texture adder post-process
  82657. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  82658. var _this = this;
  82659. 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);
  82660. this.textureAdderPostProcess.onApply = function (effect) {
  82661. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  82662. effect.setTexture("lensSampler", _this.lensTexture);
  82663. effect.setFloat("exposure", _this.exposure);
  82664. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  82665. };
  82666. // Add to pipeline
  82667. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  82668. };
  82669. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  82670. var _this = this;
  82671. var geometryRenderer = scene.enableGeometryBufferRenderer();
  82672. geometryRenderer.enablePosition = true;
  82673. var geometry = geometryRenderer.getGBuffer();
  82674. // Base post-process
  82675. 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));
  82676. var depthValues = BABYLON.Vector2.Zero();
  82677. this.volumetricLightPostProcess.onApply = function (effect) {
  82678. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  82679. var generator = _this.sourceLight.getShadowGenerator();
  82680. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  82681. effect.setTexture("positionSampler", geometry.textures[2]);
  82682. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  82683. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  82684. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  82685. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  82686. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  82687. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  82688. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  82689. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  82690. effect.setVector2("depthValues", depthValues);
  82691. }
  82692. };
  82693. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  82694. // Smooth
  82695. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  82696. // Merge
  82697. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  82698. this.volumetricLightMergePostProces.onApply = function (effect) {
  82699. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  82700. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  82701. };
  82702. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  82703. };
  82704. // Create luminance
  82705. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  82706. var _this = this;
  82707. // Create luminance
  82708. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  82709. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  82710. var offsets = [];
  82711. this.luminancePostProcess.onApply = function (effect) {
  82712. var sU = (1.0 / _this.luminancePostProcess.width);
  82713. var sV = (1.0 / _this.luminancePostProcess.height);
  82714. offsets[0] = -0.5 * sU;
  82715. offsets[1] = 0.5 * sV;
  82716. offsets[2] = 0.5 * sU;
  82717. offsets[3] = 0.5 * sV;
  82718. offsets[4] = -0.5 * sU;
  82719. offsets[5] = -0.5 * sV;
  82720. offsets[6] = 0.5 * sU;
  82721. offsets[7] = -0.5 * sV;
  82722. effect.setArray2("lumOffsets", offsets);
  82723. };
  82724. // Add to pipeline
  82725. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  82726. // Create down sample luminance
  82727. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  82728. var size = Math.pow(3, i);
  82729. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  82730. if (i === 0) {
  82731. defines += "#define FINAL_DOWN_SAMPLER";
  82732. }
  82733. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  82734. this.luminanceDownSamplePostProcesses.push(postProcess);
  82735. }
  82736. // Create callbacks and add effects
  82737. var lastLuminance = this.luminancePostProcess;
  82738. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  82739. var downSampleOffsets = new Array(18);
  82740. pp.onApply = function (effect) {
  82741. if (!lastLuminance) {
  82742. return;
  82743. }
  82744. var id = 0;
  82745. for (var x = -1; x < 2; x++) {
  82746. for (var y = -1; y < 2; y++) {
  82747. downSampleOffsets[id] = x / lastLuminance.width;
  82748. downSampleOffsets[id + 1] = y / lastLuminance.height;
  82749. id += 2;
  82750. }
  82751. }
  82752. effect.setArray2("dsOffsets", downSampleOffsets);
  82753. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  82754. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  82755. lastLuminance = _this.luminancePostProcess;
  82756. }
  82757. else {
  82758. lastLuminance = pp;
  82759. }
  82760. };
  82761. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  82762. pp.onAfterRender = function (effect) {
  82763. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  82764. 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);
  82765. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  82766. };
  82767. }
  82768. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  82769. });
  82770. };
  82771. // Create HDR post-process
  82772. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  82773. var _this = this;
  82774. 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);
  82775. var outputLiminance = 1;
  82776. var time = 0;
  82777. var lastTime = 0;
  82778. this.hdrPostProcess.onApply = function (effect) {
  82779. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  82780. time += scene.getEngine().getDeltaTime();
  82781. if (outputLiminance < 0) {
  82782. outputLiminance = _this._hdrCurrentLuminance;
  82783. }
  82784. else {
  82785. var dt = (lastTime - time) / 1000.0;
  82786. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  82787. outputLiminance += _this.hdrDecreaseRate * dt;
  82788. }
  82789. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  82790. outputLiminance -= _this.hdrIncreaseRate * dt;
  82791. }
  82792. else {
  82793. outputLiminance = _this._hdrCurrentLuminance;
  82794. }
  82795. }
  82796. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  82797. effect.setFloat("averageLuminance", outputLiminance);
  82798. lastTime = time;
  82799. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  82800. };
  82801. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  82802. };
  82803. // Create lens flare post-process
  82804. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  82805. var _this = this;
  82806. 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);
  82807. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  82808. this._createBlurPostProcesses(scene, ratio / 4, 2);
  82809. 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);
  82810. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  82811. var resolution = new BABYLON.Vector2(0, 0);
  82812. // Lens flare
  82813. this.lensFlarePostProcess.onApply = function (effect) {
  82814. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  82815. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  82816. effect.setFloat("strength", _this.lensFlareStrength);
  82817. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  82818. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  82819. // Shift
  82820. resolution.x = _this.lensFlarePostProcess.width;
  82821. resolution.y = _this.lensFlarePostProcess.height;
  82822. effect.setVector2("resolution", resolution);
  82823. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  82824. };
  82825. // Compose
  82826. 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);
  82827. 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);
  82828. this.lensFlareComposePostProcess.onApply = function (effect) {
  82829. if (!_this._scene.activeCamera) {
  82830. return;
  82831. }
  82832. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  82833. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  82834. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  82835. // Lens start rotation matrix
  82836. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  82837. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  82838. 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));
  82839. camRot *= 4.0;
  82840. 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);
  82841. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  82842. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  82843. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  82844. };
  82845. };
  82846. // Create depth-of-field post-process
  82847. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  82848. var _this = this;
  82849. 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);
  82850. this.depthOfFieldPostProcess.onApply = function (effect) {
  82851. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  82852. effect.setTexture("depthSampler", _this._getDepthTexture());
  82853. effect.setFloat("distance", _this.depthOfFieldDistance);
  82854. };
  82855. // Add to pipeline
  82856. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  82857. };
  82858. // Create motion blur post-process
  82859. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  82860. var _this = this;
  82861. 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);
  82862. var motionScale = 0;
  82863. var prevViewProjection = BABYLON.Matrix.Identity();
  82864. var invViewProjection = BABYLON.Matrix.Identity();
  82865. var viewProjection = BABYLON.Matrix.Identity();
  82866. var screenSize = BABYLON.Vector2.Zero();
  82867. this.motionBlurPostProcess.onApply = function (effect) {
  82868. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  82869. viewProjection.invertToRef(invViewProjection);
  82870. effect.setMatrix("inverseViewProjection", invViewProjection);
  82871. effect.setMatrix("prevViewProjection", prevViewProjection);
  82872. prevViewProjection = viewProjection;
  82873. screenSize.x = _this.motionBlurPostProcess.width;
  82874. screenSize.y = _this.motionBlurPostProcess.height;
  82875. effect.setVector2("screenSize", screenSize);
  82876. motionScale = scene.getEngine().getFps() / 60.0;
  82877. effect.setFloat("motionScale", motionScale);
  82878. effect.setFloat("motionStrength", _this.motionStrength);
  82879. effect.setTexture("depthSampler", _this._getDepthTexture());
  82880. };
  82881. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  82882. };
  82883. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  82884. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  82885. var renderer = this._scene.enableGeometryBufferRenderer();
  82886. return renderer.getGBuffer().textures[0];
  82887. }
  82888. return this._scene.enableDepthRenderer().getDepthMap();
  82889. };
  82890. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  82891. for (var i = 0; i < this._cameras.length; i++) {
  82892. var camera = this._cameras[i];
  82893. if (this.originalPostProcess) {
  82894. this.originalPostProcess.dispose(camera);
  82895. }
  82896. if (this.downSampleX4PostProcess) {
  82897. this.downSampleX4PostProcess.dispose(camera);
  82898. }
  82899. if (this.brightPassPostProcess) {
  82900. this.brightPassPostProcess.dispose(camera);
  82901. }
  82902. if (this.textureAdderPostProcess) {
  82903. this.textureAdderPostProcess.dispose(camera);
  82904. }
  82905. if (this.textureAdderFinalPostProcess) {
  82906. this.textureAdderFinalPostProcess.dispose(camera);
  82907. }
  82908. if (this.volumetricLightPostProcess) {
  82909. this.volumetricLightPostProcess.dispose(camera);
  82910. }
  82911. if (this.volumetricLightSmoothXPostProcess) {
  82912. this.volumetricLightSmoothXPostProcess.dispose(camera);
  82913. }
  82914. if (this.volumetricLightSmoothYPostProcess) {
  82915. this.volumetricLightSmoothYPostProcess.dispose(camera);
  82916. }
  82917. if (this.volumetricLightMergePostProces) {
  82918. this.volumetricLightMergePostProces.dispose(camera);
  82919. }
  82920. if (this.volumetricLightFinalPostProcess) {
  82921. this.volumetricLightFinalPostProcess.dispose(camera);
  82922. }
  82923. if (this.lensFlarePostProcess) {
  82924. this.lensFlarePostProcess.dispose(camera);
  82925. }
  82926. if (this.lensFlareComposePostProcess) {
  82927. this.lensFlareComposePostProcess.dispose(camera);
  82928. }
  82929. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  82930. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  82931. }
  82932. if (this.luminancePostProcess) {
  82933. this.luminancePostProcess.dispose(camera);
  82934. }
  82935. if (this.hdrPostProcess) {
  82936. this.hdrPostProcess.dispose(camera);
  82937. }
  82938. if (this.hdrFinalPostProcess) {
  82939. this.hdrFinalPostProcess.dispose(camera);
  82940. }
  82941. if (this.depthOfFieldPostProcess) {
  82942. this.depthOfFieldPostProcess.dispose(camera);
  82943. }
  82944. if (this.motionBlurPostProcess) {
  82945. this.motionBlurPostProcess.dispose(camera);
  82946. }
  82947. if (this.fxaaPostProcess) {
  82948. this.fxaaPostProcess.dispose(camera);
  82949. }
  82950. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  82951. this.blurHPostProcesses[j].dispose(camera);
  82952. }
  82953. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  82954. this.blurVPostProcesses[j].dispose(camera);
  82955. }
  82956. }
  82957. this.originalPostProcess = null;
  82958. this.downSampleX4PostProcess = null;
  82959. this.brightPassPostProcess = null;
  82960. this.textureAdderPostProcess = null;
  82961. this.textureAdderFinalPostProcess = null;
  82962. this.volumetricLightPostProcess = null;
  82963. this.volumetricLightSmoothXPostProcess = null;
  82964. this.volumetricLightSmoothYPostProcess = null;
  82965. this.volumetricLightMergePostProces = null;
  82966. this.volumetricLightFinalPostProcess = null;
  82967. this.lensFlarePostProcess = null;
  82968. this.lensFlareComposePostProcess = null;
  82969. this.luminancePostProcess = null;
  82970. this.hdrPostProcess = null;
  82971. this.hdrFinalPostProcess = null;
  82972. this.depthOfFieldPostProcess = null;
  82973. this.motionBlurPostProcess = null;
  82974. this.fxaaPostProcess = null;
  82975. this.luminanceDownSamplePostProcesses = [];
  82976. this.blurHPostProcesses = [];
  82977. this.blurVPostProcesses = [];
  82978. };
  82979. /**
  82980. * Dispose of the pipeline and stop all post processes
  82981. */
  82982. StandardRenderingPipeline.prototype.dispose = function () {
  82983. this._disposePostProcesses();
  82984. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  82985. _super.prototype.dispose.call(this);
  82986. };
  82987. /**
  82988. * Serialize the rendering pipeline (Used when exporting)
  82989. * @returns the serialized object
  82990. */
  82991. StandardRenderingPipeline.prototype.serialize = function () {
  82992. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  82993. if (this.sourceLight) {
  82994. serializationObject.sourceLightId = this.sourceLight.id;
  82995. }
  82996. serializationObject.customType = "StandardRenderingPipeline";
  82997. return serializationObject;
  82998. };
  82999. /**
  83000. * Parse the serialized pipeline
  83001. * @param source Source pipeline.
  83002. * @param scene The scene to load the pipeline to.
  83003. * @param rootUrl The URL of the serialized pipeline.
  83004. * @returns An instantiated pipeline from the serialized object.
  83005. */
  83006. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  83007. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  83008. if (source.sourceLightId) {
  83009. p.sourceLight = scene.getLightByID(source.sourceLightId);
  83010. }
  83011. return p;
  83012. };
  83013. // Luminance steps
  83014. StandardRenderingPipeline.LuminanceSteps = 6;
  83015. __decorate([
  83016. BABYLON.serialize()
  83017. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  83018. __decorate([
  83019. BABYLON.serialize()
  83020. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  83021. __decorate([
  83022. BABYLON.serialize()
  83023. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  83024. __decorate([
  83025. BABYLON.serialize()
  83026. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  83027. __decorate([
  83028. BABYLON.serializeAsTexture("lensTexture")
  83029. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  83030. __decorate([
  83031. BABYLON.serialize()
  83032. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  83033. __decorate([
  83034. BABYLON.serialize()
  83035. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  83036. __decorate([
  83037. BABYLON.serialize()
  83038. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  83039. __decorate([
  83040. BABYLON.serialize()
  83041. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  83042. __decorate([
  83043. BABYLON.serialize()
  83044. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  83045. __decorate([
  83046. BABYLON.serialize()
  83047. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  83048. __decorate([
  83049. BABYLON.serializeAsTexture("lensColorTexture")
  83050. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  83051. __decorate([
  83052. BABYLON.serialize()
  83053. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  83054. __decorate([
  83055. BABYLON.serialize()
  83056. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  83057. __decorate([
  83058. BABYLON.serialize()
  83059. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  83060. __decorate([
  83061. BABYLON.serialize()
  83062. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  83063. __decorate([
  83064. BABYLON.serializeAsTexture("lensStarTexture")
  83065. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  83066. __decorate([
  83067. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  83068. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  83069. __decorate([
  83070. BABYLON.serialize()
  83071. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  83072. __decorate([
  83073. BABYLON.serialize()
  83074. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  83075. __decorate([
  83076. BABYLON.serialize()
  83077. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  83078. __decorate([
  83079. BABYLON.serialize()
  83080. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  83081. __decorate([
  83082. BABYLON.serialize()
  83083. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  83084. __decorate([
  83085. BABYLON.serialize()
  83086. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  83087. __decorate([
  83088. BABYLON.serialize()
  83089. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  83090. __decorate([
  83091. BABYLON.serialize()
  83092. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  83093. __decorate([
  83094. BABYLON.serialize()
  83095. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  83096. __decorate([
  83097. BABYLON.serialize()
  83098. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  83099. __decorate([
  83100. BABYLON.serialize()
  83101. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  83102. __decorate([
  83103. BABYLON.serialize()
  83104. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  83105. __decorate([
  83106. BABYLON.serialize()
  83107. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  83108. __decorate([
  83109. BABYLON.serialize()
  83110. ], StandardRenderingPipeline.prototype, "samples", null);
  83111. return StandardRenderingPipeline;
  83112. }(BABYLON.PostProcessRenderPipeline));
  83113. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  83114. })(BABYLON || (BABYLON = {}));
  83115. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  83116. var BABYLON;
  83117. (function (BABYLON) {
  83118. var FxaaPostProcess = /** @class */ (function (_super) {
  83119. __extends(FxaaPostProcess, _super);
  83120. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  83121. if (camera === void 0) { camera = null; }
  83122. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83123. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  83124. var defines = _this._getDefines();
  83125. _this.updateEffect(defines);
  83126. _this.onApplyObservable.add(function (effect) {
  83127. var texelSize = _this.texelSize;
  83128. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  83129. });
  83130. return _this;
  83131. }
  83132. FxaaPostProcess.prototype._getDefines = function () {
  83133. var engine = this.getEngine();
  83134. if (!engine) {
  83135. return null;
  83136. }
  83137. var glInfo = engine.getGlInfo();
  83138. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  83139. return "#define MALI 1\n";
  83140. }
  83141. return null;
  83142. };
  83143. return FxaaPostProcess;
  83144. }(BABYLON.PostProcess));
  83145. BABYLON.FxaaPostProcess = FxaaPostProcess;
  83146. })(BABYLON || (BABYLON = {}));
  83147. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  83148. var BABYLON;
  83149. (function (BABYLON) {
  83150. /**
  83151. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  83152. */
  83153. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  83154. __extends(ChromaticAberrationPostProcess, _super);
  83155. /**
  83156. * Creates a new instance ChromaticAberrationPostProcess
  83157. * @param name The name of the effect.
  83158. * @param screenWidth The width of the screen to apply the effect on.
  83159. * @param screenHeight The height of the screen to apply the effect on.
  83160. * @param options The required width/height ratio to downsize to before computing the render pass.
  83161. * @param camera The camera to apply the render pass to.
  83162. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83163. * @param engine The engine which the post process will be applied. (default: current engine)
  83164. * @param reusable If the post process can be reused on the same frame. (default: false)
  83165. * @param textureType Type of textures used when performing the post process. (default: 0)
  83166. * @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)
  83167. */
  83168. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83169. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83170. if (blockCompilation === void 0) { blockCompilation = false; }
  83171. 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;
  83172. /**
  83173. * The amount of seperation of rgb channels (default: 30)
  83174. */
  83175. _this.aberrationAmount = 30;
  83176. /**
  83177. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  83178. */
  83179. _this.radialIntensity = 0;
  83180. /**
  83181. * 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))
  83182. */
  83183. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  83184. /**
  83185. * 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))
  83186. */
  83187. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  83188. _this.onApplyObservable.add(function (effect) {
  83189. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  83190. effect.setFloat('screen_width', screenWidth);
  83191. effect.setFloat('screen_height', screenHeight);
  83192. effect.setFloat('radialIntensity', _this.radialIntensity);
  83193. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  83194. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  83195. });
  83196. return _this;
  83197. }
  83198. return ChromaticAberrationPostProcess;
  83199. }(BABYLON.PostProcess));
  83200. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  83201. })(BABYLON || (BABYLON = {}));
  83202. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  83203. var BABYLON;
  83204. (function (BABYLON) {
  83205. /**
  83206. * The GrainPostProcess adds noise to the image at mid luminance levels
  83207. */
  83208. var GrainPostProcess = /** @class */ (function (_super) {
  83209. __extends(GrainPostProcess, _super);
  83210. /**
  83211. * Creates a new instance of @see GrainPostProcess
  83212. * @param name The name of the effect.
  83213. * @param options The required width/height ratio to downsize to before computing the render pass.
  83214. * @param camera The camera to apply the render pass to.
  83215. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83216. * @param engine The engine which the post process will be applied. (default: current engine)
  83217. * @param reusable If the post process can be reused on the same frame. (default: false)
  83218. * @param textureType Type of textures used when performing the post process. (default: 0)
  83219. * @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)
  83220. */
  83221. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83222. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83223. if (blockCompilation === void 0) { blockCompilation = false; }
  83224. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  83225. /**
  83226. * The intensity of the grain added (default: 30)
  83227. */
  83228. _this.intensity = 30;
  83229. /**
  83230. * If the grain should be randomized on every frame
  83231. */
  83232. _this.animated = false;
  83233. _this.onApplyObservable.add(function (effect) {
  83234. effect.setFloat('intensity', _this.intensity);
  83235. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  83236. });
  83237. return _this;
  83238. }
  83239. return GrainPostProcess;
  83240. }(BABYLON.PostProcess));
  83241. BABYLON.GrainPostProcess = GrainPostProcess;
  83242. })(BABYLON || (BABYLON = {}));
  83243. //# sourceMappingURL=babylon.grainPostProcess.js.map
  83244. var BABYLON;
  83245. (function (BABYLON) {
  83246. /**
  83247. * The SharpenPostProcess applies a sharpen kernel to every pixel
  83248. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  83249. */
  83250. var SharpenPostProcess = /** @class */ (function (_super) {
  83251. __extends(SharpenPostProcess, _super);
  83252. /**
  83253. * Creates a new instance ConvolutionPostProcess
  83254. * @param name The name of the effect.
  83255. * @param options The required width/height ratio to downsize to before computing the render pass.
  83256. * @param camera The camera to apply the render pass to.
  83257. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83258. * @param engine The engine which the post process will be applied. (default: current engine)
  83259. * @param reusable If the post process can be reused on the same frame. (default: false)
  83260. * @param textureType Type of textures used when performing the post process. (default: 0)
  83261. * @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)
  83262. */
  83263. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83264. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83265. if (blockCompilation === void 0) { blockCompilation = false; }
  83266. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  83267. /**
  83268. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  83269. */
  83270. _this.colorAmount = 1.0;
  83271. /**
  83272. * How much sharpness should be applied (default: 0.3)
  83273. */
  83274. _this.edgeAmount = 0.3;
  83275. _this.onApply = function (effect) {
  83276. effect.setFloat2("screenSize", _this.width, _this.height);
  83277. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  83278. };
  83279. return _this;
  83280. }
  83281. return SharpenPostProcess;
  83282. }(BABYLON.PostProcess));
  83283. BABYLON.SharpenPostProcess = SharpenPostProcess;
  83284. })(BABYLON || (BABYLON = {}));
  83285. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  83286. var BABYLON;
  83287. (function (BABYLON) {
  83288. /**
  83289. * The Blur Post Process which blurs an image based on a kernel and direction.
  83290. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  83291. */
  83292. var BlurPostProcess = /** @class */ (function (_super) {
  83293. __extends(BlurPostProcess, _super);
  83294. /**
  83295. * Creates a new instance BlurPostProcess
  83296. * @param name The name of the effect.
  83297. * @param direction The direction in which to blur the image.
  83298. * @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.
  83299. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  83300. * @param camera The camera to apply the render pass to.
  83301. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83302. * @param engine The engine which the post process will be applied. (default: current engine)
  83303. * @param reusable If the post process can be reused on the same frame. (default: false)
  83304. * @param textureType Type of textures used when performing the post process. (default: 0)
  83305. * @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)
  83306. */
  83307. function BlurPostProcess(name,
  83308. /** The direction in which to blur the image. */
  83309. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  83310. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83311. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83312. if (defines === void 0) { defines = ""; }
  83313. if (blockCompilation === void 0) { blockCompilation = false; }
  83314. 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;
  83315. _this.direction = direction;
  83316. _this.blockCompilation = blockCompilation;
  83317. _this._packedFloat = false;
  83318. _this._staticDefines = "";
  83319. _this._staticDefines = defines;
  83320. _this.onApplyObservable.add(function (effect) {
  83321. if (_this._outputTexture) {
  83322. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  83323. }
  83324. else {
  83325. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  83326. }
  83327. });
  83328. _this.kernel = kernel;
  83329. return _this;
  83330. }
  83331. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  83332. /**
  83333. * Gets the length in pixels of the blur sample region
  83334. */
  83335. get: function () {
  83336. return this._idealKernel;
  83337. },
  83338. /**
  83339. * Sets the length in pixels of the blur sample region
  83340. */
  83341. set: function (v) {
  83342. if (this._idealKernel === v) {
  83343. return;
  83344. }
  83345. v = Math.max(v, 1);
  83346. this._idealKernel = v;
  83347. this._kernel = this._nearestBestKernel(v);
  83348. if (!this.blockCompilation) {
  83349. this._updateParameters();
  83350. }
  83351. },
  83352. enumerable: true,
  83353. configurable: true
  83354. });
  83355. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  83356. /**
  83357. * Gets wether or not the blur is unpacking/repacking floats
  83358. */
  83359. get: function () {
  83360. return this._packedFloat;
  83361. },
  83362. /**
  83363. * Sets wether or not the blur needs to unpack/repack floats
  83364. */
  83365. set: function (v) {
  83366. if (this._packedFloat === v) {
  83367. return;
  83368. }
  83369. this._packedFloat = v;
  83370. if (!this.blockCompilation) {
  83371. this._updateParameters();
  83372. }
  83373. },
  83374. enumerable: true,
  83375. configurable: true
  83376. });
  83377. /**
  83378. * Updates the effect with the current post process compile time values and recompiles the shader.
  83379. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  83380. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  83381. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  83382. * @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
  83383. * @param onCompiled Called when the shader has been compiled.
  83384. * @param onError Called if there is an error when compiling a shader.
  83385. */
  83386. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  83387. if (defines === void 0) { defines = null; }
  83388. if (uniforms === void 0) { uniforms = null; }
  83389. if (samplers === void 0) { samplers = null; }
  83390. this._updateParameters(onCompiled, onError);
  83391. };
  83392. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  83393. // Generate sampling offsets and weights
  83394. var N = this._kernel;
  83395. var centerIndex = (N - 1) / 2;
  83396. // Generate Gaussian sampling weights over kernel
  83397. var offsets = [];
  83398. var weights = [];
  83399. var totalWeight = 0;
  83400. for (var i = 0; i < N; i++) {
  83401. var u = i / (N - 1);
  83402. var w = this._gaussianWeight(u * 2.0 - 1);
  83403. offsets[i] = (i - centerIndex);
  83404. weights[i] = w;
  83405. totalWeight += w;
  83406. }
  83407. // Normalize weights
  83408. for (var i = 0; i < weights.length; i++) {
  83409. weights[i] /= totalWeight;
  83410. }
  83411. // Optimize: combine samples to take advantage of hardware linear sampling
  83412. // Walk from left to center, combining pairs (symmetrically)
  83413. var linearSamplingWeights = [];
  83414. var linearSamplingOffsets = [];
  83415. var linearSamplingMap = [];
  83416. for (var i = 0; i <= centerIndex; i += 2) {
  83417. var j = Math.min(i + 1, Math.floor(centerIndex));
  83418. var singleCenterSample = i === j;
  83419. if (singleCenterSample) {
  83420. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  83421. }
  83422. else {
  83423. var sharedCell = j === centerIndex;
  83424. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  83425. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  83426. if (offsetLinear === 0) {
  83427. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  83428. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  83429. }
  83430. else {
  83431. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  83432. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  83433. }
  83434. }
  83435. }
  83436. for (var i = 0; i < linearSamplingMap.length; i++) {
  83437. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  83438. linearSamplingWeights[i] = linearSamplingMap[i].w;
  83439. }
  83440. // Replace with optimized
  83441. offsets = linearSamplingOffsets;
  83442. weights = linearSamplingWeights;
  83443. // Generate shaders
  83444. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  83445. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  83446. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  83447. var defines = "";
  83448. defines += this._staticDefines;
  83449. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  83450. if (this._staticDefines.indexOf("DOF") != -1) {
  83451. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  83452. varyingCount--;
  83453. }
  83454. for (var i = 0; i < varyingCount; i++) {
  83455. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  83456. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  83457. }
  83458. var depCount = 0;
  83459. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  83460. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  83461. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  83462. depCount++;
  83463. }
  83464. if (this.packedFloat) {
  83465. defines += "#define PACKEDFLOAT 1";
  83466. }
  83467. this.blockCompilation = false;
  83468. _super.prototype.updateEffect.call(this, defines, null, null, {
  83469. varyingCount: varyingCount,
  83470. depCount: depCount
  83471. }, onCompiled, onError);
  83472. };
  83473. /**
  83474. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  83475. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  83476. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  83477. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  83478. * The gaps between physical kernels are compensated for in the weighting of the samples
  83479. * @param idealKernel Ideal blur kernel.
  83480. * @return Nearest best kernel.
  83481. */
  83482. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  83483. var v = Math.round(idealKernel);
  83484. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  83485. var k = _a[_i];
  83486. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  83487. return Math.max(k, 3);
  83488. }
  83489. }
  83490. return Math.max(v, 3);
  83491. };
  83492. /**
  83493. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  83494. * @param x The point on the Gaussian distribution to sample.
  83495. * @return the value of the Gaussian function at x.
  83496. */
  83497. BlurPostProcess.prototype._gaussianWeight = function (x) {
  83498. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  83499. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  83500. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  83501. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  83502. // truncated at around 1.3% of peak strength.
  83503. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  83504. var sigma = (1 / 3);
  83505. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  83506. var exponent = -((x * x) / (2.0 * sigma * sigma));
  83507. var weight = (1.0 / denominator) * Math.exp(exponent);
  83508. return weight;
  83509. };
  83510. /**
  83511. * Generates a string that can be used as a floating point number in GLSL.
  83512. * @param x Value to print.
  83513. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  83514. * @return GLSL float string.
  83515. */
  83516. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  83517. if (decimalFigures === void 0) { decimalFigures = 8; }
  83518. return x.toFixed(decimalFigures).replace(/0+$/, '');
  83519. };
  83520. return BlurPostProcess;
  83521. }(BABYLON.PostProcess));
  83522. BABYLON.BlurPostProcess = BlurPostProcess;
  83523. })(BABYLON || (BABYLON = {}));
  83524. //# sourceMappingURL=babylon.blurPostProcess.js.map
  83525. var BABYLON;
  83526. (function (BABYLON) {
  83527. /**
  83528. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  83529. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  83530. * based on samples that have a large difference in distance than the center pixel.
  83531. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  83532. */
  83533. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  83534. __extends(DepthOfFieldBlurPostProcess, _super);
  83535. /**
  83536. * Creates a new instance CircleOfConfusionPostProcess
  83537. * @param name The name of the effect.
  83538. * @param scene The scene the effect belongs to.
  83539. * @param direction The direction the blur should be applied.
  83540. * @param kernel The size of the kernel used to blur.
  83541. * @param options The required width/height ratio to downsize to before computing the render pass.
  83542. * @param camera The camera to apply the render pass to.
  83543. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  83544. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  83545. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83546. * @param engine The engine which the post process will be applied. (default: current engine)
  83547. * @param reusable If the post process can be reused on the same frame. (default: false)
  83548. * @param textureType Type of textures used when performing the post process. (default: 0)
  83549. * @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)
  83550. */
  83551. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  83552. if (imageToBlur === void 0) { imageToBlur = null; }
  83553. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83554. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83555. if (blockCompilation === void 0) { blockCompilation = false; }
  83556. 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;
  83557. _this.direction = direction;
  83558. _this.onApplyObservable.add(function (effect) {
  83559. if (imageToBlur != null) {
  83560. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  83561. }
  83562. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  83563. if (scene.activeCamera) {
  83564. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  83565. }
  83566. });
  83567. return _this;
  83568. }
  83569. return DepthOfFieldBlurPostProcess;
  83570. }(BABYLON.BlurPostProcess));
  83571. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  83572. })(BABYLON || (BABYLON = {}));
  83573. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  83574. var BABYLON;
  83575. (function (BABYLON) {
  83576. /**
  83577. * Options to be set when merging outputs from the default pipeline.
  83578. */
  83579. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  83580. function DepthOfFieldMergePostProcessOptions() {
  83581. }
  83582. return DepthOfFieldMergePostProcessOptions;
  83583. }());
  83584. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  83585. /**
  83586. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  83587. */
  83588. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  83589. __extends(DepthOfFieldMergePostProcess, _super);
  83590. /**
  83591. * Creates a new instance of DepthOfFieldMergePostProcess
  83592. * @param name The name of the effect.
  83593. * @param originalFromInput Post process which's input will be used for the merge.
  83594. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  83595. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  83596. * @param options The required width/height ratio to downsize to before computing the render pass.
  83597. * @param camera The camera to apply the render pass to.
  83598. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83599. * @param engine The engine which the post process will be applied. (default: current engine)
  83600. * @param reusable If the post process can be reused on the same frame. (default: false)
  83601. * @param textureType Type of textures used when performing the post process. (default: 0)
  83602. * @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)
  83603. */
  83604. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83605. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83606. if (blockCompilation === void 0) { blockCompilation = false; }
  83607. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  83608. _this.blurSteps = blurSteps;
  83609. _this.onApplyObservable.add(function (effect) {
  83610. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  83611. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  83612. blurSteps.forEach(function (step, index) {
  83613. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  83614. });
  83615. });
  83616. if (!blockCompilation) {
  83617. _this.updateEffect();
  83618. }
  83619. return _this;
  83620. }
  83621. /**
  83622. * Updates the effect with the current post process compile time values and recompiles the shader.
  83623. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  83624. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  83625. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  83626. * @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
  83627. * @param onCompiled Called when the shader has been compiled.
  83628. * @param onError Called if there is an error when compiling a shader.
  83629. */
  83630. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  83631. if (defines === void 0) { defines = null; }
  83632. if (uniforms === void 0) { uniforms = null; }
  83633. if (samplers === void 0) { samplers = null; }
  83634. if (!defines) {
  83635. defines = "";
  83636. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  83637. }
  83638. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  83639. };
  83640. return DepthOfFieldMergePostProcess;
  83641. }(BABYLON.PostProcess));
  83642. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  83643. })(BABYLON || (BABYLON = {}));
  83644. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  83645. var BABYLON;
  83646. (function (BABYLON) {
  83647. /**
  83648. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  83649. */
  83650. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  83651. __extends(CircleOfConfusionPostProcess, _super);
  83652. /**
  83653. * Creates a new instance CircleOfConfusionPostProcess
  83654. * @param name The name of the effect.
  83655. * @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.
  83656. * @param options The required width/height ratio to downsize to before computing the render pass.
  83657. * @param camera The camera to apply the render pass to.
  83658. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83659. * @param engine The engine which the post process will be applied. (default: current engine)
  83660. * @param reusable If the post process can be reused on the same frame. (default: false)
  83661. * @param textureType Type of textures used when performing the post process. (default: 0)
  83662. * @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)
  83663. */
  83664. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83665. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83666. if (blockCompilation === void 0) { blockCompilation = false; }
  83667. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  83668. /**
  83669. * 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.
  83670. */
  83671. _this.lensSize = 50;
  83672. /**
  83673. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  83674. */
  83675. _this.fStop = 1.4;
  83676. /**
  83677. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  83678. */
  83679. _this.focusDistance = 2000;
  83680. /**
  83681. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  83682. */
  83683. _this.focalLength = 50;
  83684. _this._depthTexture = null;
  83685. _this._depthTexture = depthTexture;
  83686. _this.onApplyObservable.add(function (effect) {
  83687. if (!_this._depthTexture) {
  83688. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  83689. return;
  83690. }
  83691. effect.setTexture("depthSampler", _this._depthTexture);
  83692. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  83693. var aperture = _this.lensSize / _this.fStop;
  83694. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  83695. effect.setFloat('focusDistance', _this.focusDistance);
  83696. effect.setFloat('cocPrecalculation', cocPrecalculation);
  83697. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  83698. });
  83699. return _this;
  83700. }
  83701. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  83702. /**
  83703. * 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.
  83704. */
  83705. set: function (value) {
  83706. this._depthTexture = value;
  83707. },
  83708. enumerable: true,
  83709. configurable: true
  83710. });
  83711. return CircleOfConfusionPostProcess;
  83712. }(BABYLON.PostProcess));
  83713. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  83714. })(BABYLON || (BABYLON = {}));
  83715. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  83716. var BABYLON;
  83717. (function (BABYLON) {
  83718. /**
  83719. * Specifies the level of max blur that should be applied when using the depth of field effect
  83720. */
  83721. var DepthOfFieldEffectBlurLevel;
  83722. (function (DepthOfFieldEffectBlurLevel) {
  83723. /**
  83724. * Subtle blur
  83725. */
  83726. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  83727. /**
  83728. * Medium blur
  83729. */
  83730. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  83731. /**
  83732. * Large blur
  83733. */
  83734. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  83735. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  83736. ;
  83737. /**
  83738. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  83739. */
  83740. var DepthOfFieldEffect = /** @class */ (function (_super) {
  83741. __extends(DepthOfFieldEffect, _super);
  83742. /**
  83743. * Creates a new instance DepthOfFieldEffect
  83744. * @param scene The scene the effect belongs to.
  83745. * @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.
  83746. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  83747. * @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)
  83748. */
  83749. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  83750. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  83751. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  83752. if (blockCompilation === void 0) { blockCompilation = false; }
  83753. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  83754. return _this._effects;
  83755. }, true) || this;
  83756. /**
  83757. * @hidden Internal post processes in depth of field effect
  83758. */
  83759. _this._effects = [];
  83760. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  83761. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  83762. // 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)
  83763. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  83764. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  83765. _this._depthOfFieldBlurY = [];
  83766. _this._depthOfFieldBlurX = [];
  83767. var blurCount = 1;
  83768. var kernelSize = 15;
  83769. switch (blurLevel) {
  83770. case DepthOfFieldEffectBlurLevel.High: {
  83771. blurCount = 3;
  83772. kernelSize = 51;
  83773. break;
  83774. }
  83775. case DepthOfFieldEffectBlurLevel.Medium: {
  83776. blurCount = 2;
  83777. kernelSize = 31;
  83778. break;
  83779. }
  83780. default: {
  83781. kernelSize = 15;
  83782. blurCount = 1;
  83783. break;
  83784. }
  83785. }
  83786. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  83787. var ratio = 1.0;
  83788. for (var i = 0; i < blurCount; i++) {
  83789. 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);
  83790. blurY.autoClear = false;
  83791. ratio = 0.75 / Math.pow(2, i);
  83792. 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);
  83793. blurX.autoClear = false;
  83794. _this._depthOfFieldBlurY.push(blurY);
  83795. _this._depthOfFieldBlurX.push(blurX);
  83796. }
  83797. // Set all post processes on the effect.
  83798. _this._effects = [_this._circleOfConfusion];
  83799. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  83800. _this._effects.push(_this._depthOfFieldBlurY[i]);
  83801. _this._effects.push(_this._depthOfFieldBlurX[i]);
  83802. }
  83803. // Merge blurred images with original image based on circleOfConfusion
  83804. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  83805. _this._dofMerge.autoClear = false;
  83806. _this._effects.push(_this._dofMerge);
  83807. return _this;
  83808. }
  83809. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  83810. get: function () {
  83811. return this._circleOfConfusion.focalLength;
  83812. },
  83813. /**
  83814. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  83815. */
  83816. set: function (value) {
  83817. this._circleOfConfusion.focalLength = value;
  83818. },
  83819. enumerable: true,
  83820. configurable: true
  83821. });
  83822. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  83823. get: function () {
  83824. return this._circleOfConfusion.fStop;
  83825. },
  83826. /**
  83827. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  83828. */
  83829. set: function (value) {
  83830. this._circleOfConfusion.fStop = value;
  83831. },
  83832. enumerable: true,
  83833. configurable: true
  83834. });
  83835. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  83836. get: function () {
  83837. return this._circleOfConfusion.focusDistance;
  83838. },
  83839. /**
  83840. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  83841. */
  83842. set: function (value) {
  83843. this._circleOfConfusion.focusDistance = value;
  83844. },
  83845. enumerable: true,
  83846. configurable: true
  83847. });
  83848. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  83849. get: function () {
  83850. return this._circleOfConfusion.lensSize;
  83851. },
  83852. /**
  83853. * 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.
  83854. */
  83855. set: function (value) {
  83856. this._circleOfConfusion.lensSize = value;
  83857. },
  83858. enumerable: true,
  83859. configurable: true
  83860. });
  83861. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  83862. /**
  83863. * 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.
  83864. */
  83865. set: function (value) {
  83866. this._circleOfConfusion.depthTexture = value;
  83867. },
  83868. enumerable: true,
  83869. configurable: true
  83870. });
  83871. /**
  83872. * Disposes each of the internal effects for a given camera.
  83873. * @param camera The camera to dispose the effect on.
  83874. */
  83875. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  83876. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83877. this._effects[effectIndex].dispose(camera);
  83878. }
  83879. };
  83880. /**
  83881. * @hidden Internal
  83882. */
  83883. DepthOfFieldEffect.prototype._updateEffects = function () {
  83884. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83885. this._effects[effectIndex].updateEffect();
  83886. }
  83887. };
  83888. /**
  83889. * Internal
  83890. * @returns if all the contained post processes are ready.
  83891. * @hidden
  83892. */
  83893. DepthOfFieldEffect.prototype._isReady = function () {
  83894. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83895. if (!this._effects[effectIndex].isReady()) {
  83896. return false;
  83897. }
  83898. }
  83899. return true;
  83900. };
  83901. return DepthOfFieldEffect;
  83902. }(BABYLON.PostProcessRenderEffect));
  83903. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  83904. })(BABYLON || (BABYLON = {}));
  83905. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  83906. var BABYLON;
  83907. (function (BABYLON) {
  83908. /**
  83909. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  83910. */
  83911. var BloomMergePostProcess = /** @class */ (function (_super) {
  83912. __extends(BloomMergePostProcess, _super);
  83913. /**
  83914. * Creates a new instance of @see BloomMergePostProcess
  83915. * @param name The name of the effect.
  83916. * @param originalFromInput Post process which's input will be used for the merge.
  83917. * @param blurred Blurred highlights post process which's output will be used.
  83918. * @param weight Weight of the bloom to be added to the original input.
  83919. * @param options The required width/height ratio to downsize to before computing the render pass.
  83920. * @param camera The camera to apply the render pass to.
  83921. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83922. * @param engine The engine which the post process will be applied. (default: current engine)
  83923. * @param reusable If the post process can be reused on the same frame. (default: false)
  83924. * @param textureType Type of textures used when performing the post process. (default: 0)
  83925. * @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)
  83926. */
  83927. function BloomMergePostProcess(name, originalFromInput, blurred,
  83928. /** Weight of the bloom to be added to the original input. */
  83929. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83930. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83931. if (blockCompilation === void 0) { blockCompilation = false; }
  83932. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  83933. _this.weight = weight;
  83934. _this.onApplyObservable.add(function (effect) {
  83935. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  83936. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  83937. effect.setFloat("bloomWeight", _this.weight);
  83938. });
  83939. if (!blockCompilation) {
  83940. _this.updateEffect();
  83941. }
  83942. return _this;
  83943. }
  83944. return BloomMergePostProcess;
  83945. }(BABYLON.PostProcess));
  83946. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  83947. })(BABYLON || (BABYLON = {}));
  83948. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  83949. var BABYLON;
  83950. (function (BABYLON) {
  83951. /**
  83952. * 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.
  83953. */
  83954. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  83955. __extends(ExtractHighlightsPostProcess, _super);
  83956. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83957. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83958. if (blockCompilation === void 0) { blockCompilation = false; }
  83959. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  83960. /**
  83961. * The luminance threshold, pixels below this value will be set to black.
  83962. */
  83963. _this.threshold = 0.9;
  83964. /** @hidden */
  83965. _this._exposure = 1;
  83966. /**
  83967. * Post process which has the input texture to be used when performing highlight extraction
  83968. * @hidden
  83969. */
  83970. _this._inputPostProcess = null;
  83971. _this.onApplyObservable.add(function (effect) {
  83972. if (_this._inputPostProcess) {
  83973. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  83974. }
  83975. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  83976. effect.setFloat('exposure', _this._exposure);
  83977. });
  83978. return _this;
  83979. }
  83980. return ExtractHighlightsPostProcess;
  83981. }(BABYLON.PostProcess));
  83982. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  83983. })(BABYLON || (BABYLON = {}));
  83984. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  83985. var BABYLON;
  83986. (function (BABYLON) {
  83987. /**
  83988. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  83989. */
  83990. var BloomEffect = /** @class */ (function (_super) {
  83991. __extends(BloomEffect, _super);
  83992. /**
  83993. * Creates a new instance of @see BloomEffect
  83994. * @param scene The scene the effect belongs to.
  83995. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  83996. * @param bloomKernel The size of the kernel to be used when applying the blur.
  83997. * @param bloomWeight The the strength of bloom.
  83998. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  83999. * @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)
  84000. */
  84001. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  84002. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  84003. if (blockCompilation === void 0) { blockCompilation = false; }
  84004. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  84005. return _this._effects;
  84006. }, true) || this;
  84007. _this.bloomScale = bloomScale;
  84008. /**
  84009. * @hidden Internal
  84010. */
  84011. _this._effects = [];
  84012. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  84013. _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);
  84014. _this._blurX.alwaysForcePOT = true;
  84015. _this._blurX.autoClear = false;
  84016. _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);
  84017. _this._blurY.alwaysForcePOT = true;
  84018. _this._blurY.autoClear = false;
  84019. _this.kernel = bloomKernel;
  84020. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  84021. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  84022. _this._merge.autoClear = false;
  84023. _this._effects.push(_this._merge);
  84024. return _this;
  84025. }
  84026. Object.defineProperty(BloomEffect.prototype, "threshold", {
  84027. /**
  84028. * The luminance threshold to find bright areas of the image to bloom.
  84029. */
  84030. get: function () {
  84031. return this._downscale.threshold;
  84032. },
  84033. set: function (value) {
  84034. this._downscale.threshold = value;
  84035. },
  84036. enumerable: true,
  84037. configurable: true
  84038. });
  84039. Object.defineProperty(BloomEffect.prototype, "weight", {
  84040. /**
  84041. * The strength of the bloom.
  84042. */
  84043. get: function () {
  84044. return this._merge.weight;
  84045. },
  84046. set: function (value) {
  84047. this._merge.weight = value;
  84048. },
  84049. enumerable: true,
  84050. configurable: true
  84051. });
  84052. Object.defineProperty(BloomEffect.prototype, "kernel", {
  84053. /**
  84054. * Specifies the size of the bloom blur kernel, relative to the final output size
  84055. */
  84056. get: function () {
  84057. return this._blurX.kernel / this.bloomScale;
  84058. },
  84059. set: function (value) {
  84060. this._blurX.kernel = value * this.bloomScale;
  84061. this._blurY.kernel = value * this.bloomScale;
  84062. },
  84063. enumerable: true,
  84064. configurable: true
  84065. });
  84066. /**
  84067. * Disposes each of the internal effects for a given camera.
  84068. * @param camera The camera to dispose the effect on.
  84069. */
  84070. BloomEffect.prototype.disposeEffects = function (camera) {
  84071. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  84072. this._effects[effectIndex].dispose(camera);
  84073. }
  84074. };
  84075. /**
  84076. * @hidden Internal
  84077. */
  84078. BloomEffect.prototype._updateEffects = function () {
  84079. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  84080. this._effects[effectIndex].updateEffect();
  84081. }
  84082. };
  84083. /**
  84084. * Internal
  84085. * @returns if all the contained post processes are ready.
  84086. * @hidden
  84087. */
  84088. BloomEffect.prototype._isReady = function () {
  84089. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  84090. if (!this._effects[effectIndex].isReady()) {
  84091. return false;
  84092. }
  84093. }
  84094. return true;
  84095. };
  84096. return BloomEffect;
  84097. }(BABYLON.PostProcessRenderEffect));
  84098. BABYLON.BloomEffect = BloomEffect;
  84099. })(BABYLON || (BABYLON = {}));
  84100. //# sourceMappingURL=babylon.bloomEffect.js.map
  84101. var BABYLON;
  84102. (function (BABYLON) {
  84103. /**
  84104. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  84105. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  84106. */
  84107. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  84108. __extends(DefaultRenderingPipeline, _super);
  84109. /**
  84110. * @constructor
  84111. * @param {string} name - The rendering pipeline name (default: "")
  84112. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  84113. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  84114. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  84115. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  84116. */
  84117. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  84118. if (name === void 0) { name = ""; }
  84119. if (hdr === void 0) { hdr = true; }
  84120. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  84121. if (automaticBuild === void 0) { automaticBuild = true; }
  84122. var _this = _super.call(this, scene.getEngine(), name) || this;
  84123. _this._camerasToBeAttached = [];
  84124. /**
  84125. * ID of the sharpen post process,
  84126. */
  84127. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  84128. /**
  84129. * ID of the image processing post process;
  84130. */
  84131. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  84132. /**
  84133. * ID of the Fast Approximate Anti-Aliasing post process;
  84134. */
  84135. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  84136. /**
  84137. * ID of the chromatic aberration post process,
  84138. */
  84139. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  84140. /**
  84141. * ID of the grain post process
  84142. */
  84143. _this.GrainPostProcessId = "GrainPostProcessEffect";
  84144. /**
  84145. * Glow post process which adds a glow to emmisive areas of the image
  84146. */
  84147. _this._glowLayer = null;
  84148. /**
  84149. * Animations which can be used to tweak settings over a period of time
  84150. */
  84151. _this.animations = [];
  84152. _this._imageProcessingConfigurationObserver = null;
  84153. // Values
  84154. _this._sharpenEnabled = false;
  84155. _this._bloomEnabled = false;
  84156. _this._depthOfFieldEnabled = false;
  84157. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  84158. _this._fxaaEnabled = false;
  84159. _this._imageProcessingEnabled = true;
  84160. _this._bloomScale = 0.5;
  84161. _this._chromaticAberrationEnabled = false;
  84162. _this._grainEnabled = false;
  84163. _this._buildAllowed = true;
  84164. _this._resizeObserver = null;
  84165. _this._hardwareScaleLevel = 1.0;
  84166. _this._bloomKernel = 64;
  84167. /**
  84168. * Specifies the weight of the bloom in the final rendering
  84169. */
  84170. _this._bloomWeight = 0.15;
  84171. /**
  84172. * Specifies the luma threshold for the area that will be blurred by the bloom
  84173. */
  84174. _this._bloomThreshold = 0.9;
  84175. _this._samples = 1;
  84176. _this._hasCleared = false;
  84177. _this._prevPostProcess = null;
  84178. _this._prevPrevPostProcess = null;
  84179. _this._depthOfFieldSceneObserver = null;
  84180. _this._cameras = cameras || scene.cameras;
  84181. _this._cameras = _this._cameras.slice();
  84182. _this._camerasToBeAttached = _this._cameras.slice();
  84183. _this._buildAllowed = automaticBuild;
  84184. // Initialize
  84185. _this._scene = scene;
  84186. var caps = _this._scene.getEngine().getCaps();
  84187. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  84188. // Misc
  84189. if (_this._hdr) {
  84190. if (caps.textureHalfFloatRender) {
  84191. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84192. }
  84193. else if (caps.textureFloatRender) {
  84194. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84195. }
  84196. }
  84197. else {
  84198. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84199. }
  84200. // Attach
  84201. scene.postProcessRenderPipelineManager.addPipeline(_this);
  84202. var engine = _this._scene.getEngine();
  84203. // Create post processes before hand so they can be modified before enabled.
  84204. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  84205. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  84206. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  84207. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  84208. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  84209. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  84210. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  84211. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  84212. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  84213. _this._resizeObserver = engine.onResizeObservable.add(function () {
  84214. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  84215. _this.bloomKernel = _this.bloomKernel;
  84216. });
  84217. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  84218. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  84219. });
  84220. _this._buildPipeline();
  84221. return _this;
  84222. }
  84223. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  84224. get: function () {
  84225. return this._sharpenEnabled;
  84226. },
  84227. /**
  84228. * Enable or disable the sharpen process from the pipeline
  84229. */
  84230. set: function (enabled) {
  84231. if (this._sharpenEnabled === enabled) {
  84232. return;
  84233. }
  84234. this._sharpenEnabled = enabled;
  84235. this._buildPipeline();
  84236. },
  84237. enumerable: true,
  84238. configurable: true
  84239. });
  84240. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  84241. /**
  84242. * Specifies the size of the bloom blur kernel, relative to the final output size
  84243. */
  84244. get: function () {
  84245. return this._bloomKernel;
  84246. },
  84247. set: function (value) {
  84248. this._bloomKernel = value;
  84249. this.bloom.kernel = value / this._hardwareScaleLevel;
  84250. },
  84251. enumerable: true,
  84252. configurable: true
  84253. });
  84254. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  84255. get: function () {
  84256. return this._bloomWeight;
  84257. },
  84258. /**
  84259. * The strength of the bloom.
  84260. */
  84261. set: function (value) {
  84262. if (this._bloomWeight === value) {
  84263. return;
  84264. }
  84265. this.bloom.weight = value;
  84266. this._bloomWeight = value;
  84267. },
  84268. enumerable: true,
  84269. configurable: true
  84270. });
  84271. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  84272. get: function () {
  84273. return this._bloomThreshold;
  84274. },
  84275. /**
  84276. * The strength of the bloom.
  84277. */
  84278. set: function (value) {
  84279. if (this._bloomThreshold === value) {
  84280. return;
  84281. }
  84282. this.bloom.threshold = value;
  84283. this._bloomThreshold = value;
  84284. },
  84285. enumerable: true,
  84286. configurable: true
  84287. });
  84288. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  84289. get: function () {
  84290. return this._bloomScale;
  84291. },
  84292. /**
  84293. * The scale of the bloom, lower value will provide better performance.
  84294. */
  84295. set: function (value) {
  84296. if (this._bloomScale === value) {
  84297. return;
  84298. }
  84299. this._bloomScale = value;
  84300. // recreate bloom and dispose old as this setting is not dynamic
  84301. this._rebuildBloom();
  84302. this._buildPipeline();
  84303. },
  84304. enumerable: true,
  84305. configurable: true
  84306. });
  84307. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  84308. get: function () {
  84309. return this._bloomEnabled;
  84310. },
  84311. /**
  84312. * Enable or disable the bloom from the pipeline
  84313. */
  84314. set: function (enabled) {
  84315. if (this._bloomEnabled === enabled) {
  84316. return;
  84317. }
  84318. this._bloomEnabled = enabled;
  84319. this._buildPipeline();
  84320. },
  84321. enumerable: true,
  84322. configurable: true
  84323. });
  84324. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  84325. // recreate bloom and dispose old as this setting is not dynamic
  84326. var oldBloom = this.bloom;
  84327. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  84328. this.bloom.threshold = oldBloom.threshold;
  84329. for (var i = 0; i < this._cameras.length; i++) {
  84330. oldBloom.disposeEffects(this._cameras[i]);
  84331. }
  84332. };
  84333. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  84334. /**
  84335. * If the depth of field is enabled.
  84336. */
  84337. get: function () {
  84338. return this._depthOfFieldEnabled;
  84339. },
  84340. set: function (enabled) {
  84341. if (this._depthOfFieldEnabled === enabled) {
  84342. return;
  84343. }
  84344. this._depthOfFieldEnabled = enabled;
  84345. this._buildPipeline();
  84346. },
  84347. enumerable: true,
  84348. configurable: true
  84349. });
  84350. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  84351. /**
  84352. * Blur level of the depth of field effect. (Higher blur will effect performance)
  84353. */
  84354. get: function () {
  84355. return this._depthOfFieldBlurLevel;
  84356. },
  84357. set: function (value) {
  84358. if (this._depthOfFieldBlurLevel === value) {
  84359. return;
  84360. }
  84361. this._depthOfFieldBlurLevel = value;
  84362. // recreate dof and dispose old as this setting is not dynamic
  84363. var oldDof = this.depthOfField;
  84364. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  84365. this.depthOfField.focalLength = oldDof.focalLength;
  84366. this.depthOfField.focusDistance = oldDof.focusDistance;
  84367. this.depthOfField.fStop = oldDof.fStop;
  84368. this.depthOfField.lensSize = oldDof.lensSize;
  84369. for (var i = 0; i < this._cameras.length; i++) {
  84370. oldDof.disposeEffects(this._cameras[i]);
  84371. }
  84372. this._buildPipeline();
  84373. },
  84374. enumerable: true,
  84375. configurable: true
  84376. });
  84377. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  84378. get: function () {
  84379. return this._fxaaEnabled;
  84380. },
  84381. /**
  84382. * If the anti aliasing is enabled.
  84383. */
  84384. set: function (enabled) {
  84385. if (this._fxaaEnabled === enabled) {
  84386. return;
  84387. }
  84388. this._fxaaEnabled = enabled;
  84389. this._buildPipeline();
  84390. },
  84391. enumerable: true,
  84392. configurable: true
  84393. });
  84394. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  84395. get: function () {
  84396. return this._samples;
  84397. },
  84398. /**
  84399. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  84400. */
  84401. set: function (sampleCount) {
  84402. if (this._samples === sampleCount) {
  84403. return;
  84404. }
  84405. this._samples = sampleCount;
  84406. this._buildPipeline();
  84407. },
  84408. enumerable: true,
  84409. configurable: true
  84410. });
  84411. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  84412. get: function () {
  84413. return this._imageProcessingEnabled;
  84414. },
  84415. /**
  84416. * If image processing is enabled.
  84417. */
  84418. set: function (enabled) {
  84419. if (this._imageProcessingEnabled === enabled) {
  84420. return;
  84421. }
  84422. this._imageProcessingEnabled = enabled;
  84423. this._buildPipeline();
  84424. },
  84425. enumerable: true,
  84426. configurable: true
  84427. });
  84428. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  84429. get: function () {
  84430. return this._glowLayer == null;
  84431. },
  84432. /**
  84433. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  84434. */
  84435. set: function (enabled) {
  84436. if (enabled && !this._glowLayer) {
  84437. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  84438. }
  84439. else if (!enabled && this._glowLayer) {
  84440. this._glowLayer.dispose();
  84441. this._glowLayer = null;
  84442. }
  84443. },
  84444. enumerable: true,
  84445. configurable: true
  84446. });
  84447. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  84448. get: function () {
  84449. return this._chromaticAberrationEnabled;
  84450. },
  84451. /**
  84452. * Enable or disable the chromaticAberration process from the pipeline
  84453. */
  84454. set: function (enabled) {
  84455. if (this._chromaticAberrationEnabled === enabled) {
  84456. return;
  84457. }
  84458. this._chromaticAberrationEnabled = enabled;
  84459. this._buildPipeline();
  84460. },
  84461. enumerable: true,
  84462. configurable: true
  84463. });
  84464. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  84465. get: function () {
  84466. return this._grainEnabled;
  84467. },
  84468. /**
  84469. * Enable or disable the grain process from the pipeline
  84470. */
  84471. set: function (enabled) {
  84472. if (this._grainEnabled === enabled) {
  84473. return;
  84474. }
  84475. this._grainEnabled = enabled;
  84476. this._buildPipeline();
  84477. },
  84478. enumerable: true,
  84479. configurable: true
  84480. });
  84481. /**
  84482. * Force the compilation of the entire pipeline.
  84483. */
  84484. DefaultRenderingPipeline.prototype.prepare = function () {
  84485. var previousState = this._buildAllowed;
  84486. this._buildAllowed = true;
  84487. this._buildPipeline();
  84488. this._buildAllowed = previousState;
  84489. };
  84490. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  84491. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  84492. if (this._hasCleared) {
  84493. postProcess.autoClear = false;
  84494. }
  84495. else {
  84496. postProcess.autoClear = true;
  84497. this._scene.autoClear = false;
  84498. this._hasCleared = true;
  84499. }
  84500. if (!skipTextureSharing) {
  84501. if (this._prevPrevPostProcess) {
  84502. postProcess.shareOutputWith(this._prevPrevPostProcess);
  84503. }
  84504. else {
  84505. postProcess.useOwnOutput();
  84506. }
  84507. if (this._prevPostProcess) {
  84508. this._prevPrevPostProcess = this._prevPostProcess;
  84509. }
  84510. this._prevPostProcess = postProcess;
  84511. }
  84512. };
  84513. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  84514. var _this = this;
  84515. if (!this._buildAllowed) {
  84516. return;
  84517. }
  84518. this._scene.autoClear = true;
  84519. var engine = this._scene.getEngine();
  84520. this._disposePostProcesses();
  84521. if (this._cameras !== null) {
  84522. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  84523. // get back cameras to be used to reattach pipeline
  84524. this._cameras = this._camerasToBeAttached.slice();
  84525. }
  84526. this._reset();
  84527. this._prevPostProcess = null;
  84528. this._prevPrevPostProcess = null;
  84529. this._hasCleared = false;
  84530. if (this.depthOfFieldEnabled) {
  84531. // Multi camera suport
  84532. if (this._cameras.length > 1) {
  84533. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  84534. var camera = _a[_i];
  84535. var depthRenderer = this._scene.enableDepthRenderer(camera);
  84536. depthRenderer.useOnlyInActiveCamera = true;
  84537. }
  84538. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  84539. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  84540. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  84541. }
  84542. });
  84543. }
  84544. else {
  84545. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  84546. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  84547. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  84548. }
  84549. if (!this.depthOfField._isReady()) {
  84550. this.depthOfField._updateEffects();
  84551. }
  84552. this.addEffect(this.depthOfField);
  84553. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  84554. }
  84555. else {
  84556. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  84557. }
  84558. if (this.bloomEnabled) {
  84559. if (!this.bloom._isReady()) {
  84560. this.bloom._updateEffects();
  84561. }
  84562. this.addEffect(this.bloom);
  84563. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  84564. }
  84565. if (this._imageProcessingEnabled) {
  84566. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  84567. if (this._hdr) {
  84568. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  84569. this._setAutoClearAndTextureSharing(this.imageProcessing);
  84570. }
  84571. else {
  84572. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  84573. }
  84574. }
  84575. if (this.sharpenEnabled) {
  84576. if (!this.sharpen.isReady()) {
  84577. this.sharpen.updateEffect();
  84578. }
  84579. this.addEffect(this._sharpenEffect);
  84580. this._setAutoClearAndTextureSharing(this.sharpen);
  84581. }
  84582. if (this.grainEnabled) {
  84583. if (!this.grain.isReady()) {
  84584. this.grain.updateEffect();
  84585. }
  84586. this.addEffect(this._grainEffect);
  84587. this._setAutoClearAndTextureSharing(this.grain);
  84588. }
  84589. if (this.chromaticAberrationEnabled) {
  84590. if (!this.chromaticAberration.isReady()) {
  84591. this.chromaticAberration.updateEffect();
  84592. }
  84593. this.addEffect(this._chromaticAberrationEffect);
  84594. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  84595. }
  84596. if (this.fxaaEnabled) {
  84597. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  84598. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  84599. this._setAutoClearAndTextureSharing(this.fxaa, true);
  84600. }
  84601. if (this._cameras !== null) {
  84602. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  84603. }
  84604. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  84605. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  84606. }
  84607. };
  84608. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  84609. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  84610. for (var i = 0; i < this._cameras.length; i++) {
  84611. var camera = this._cameras[i];
  84612. if (this.imageProcessing) {
  84613. this.imageProcessing.dispose(camera);
  84614. }
  84615. if (this.fxaa) {
  84616. this.fxaa.dispose(camera);
  84617. }
  84618. // These are created in the constructor and should not be disposed on every pipeline change
  84619. if (disposeNonRecreated) {
  84620. if (this.sharpen) {
  84621. this.sharpen.dispose(camera);
  84622. }
  84623. if (this.depthOfField) {
  84624. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  84625. this.depthOfField.disposeEffects(camera);
  84626. }
  84627. if (this.bloom) {
  84628. this.bloom.disposeEffects(camera);
  84629. }
  84630. if (this.chromaticAberration) {
  84631. this.chromaticAberration.dispose(camera);
  84632. }
  84633. if (this.grain) {
  84634. this.grain.dispose(camera);
  84635. }
  84636. if (this._glowLayer) {
  84637. this._glowLayer.dispose();
  84638. }
  84639. }
  84640. }
  84641. this.imageProcessing = null;
  84642. this.fxaa = null;
  84643. if (disposeNonRecreated) {
  84644. this.sharpen = null;
  84645. this._sharpenEffect = null;
  84646. this.depthOfField = null;
  84647. this.bloom = null;
  84648. this.chromaticAberration = null;
  84649. this._chromaticAberrationEffect = null;
  84650. this.grain = null;
  84651. this._grainEffect = null;
  84652. this._glowLayer = null;
  84653. }
  84654. };
  84655. /**
  84656. * Adds a camera to the pipeline
  84657. * @param camera the camera to be added
  84658. */
  84659. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  84660. this._camerasToBeAttached.push(camera);
  84661. this._buildPipeline();
  84662. };
  84663. /**
  84664. * Removes a camera from the pipeline
  84665. * @param camera the camera to remove
  84666. */
  84667. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  84668. var index = this._camerasToBeAttached.indexOf(camera);
  84669. this._camerasToBeAttached.splice(index, 1);
  84670. this._buildPipeline();
  84671. };
  84672. /**
  84673. * Dispose of the pipeline and stop all post processes
  84674. */
  84675. DefaultRenderingPipeline.prototype.dispose = function () {
  84676. this._disposePostProcesses(true);
  84677. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  84678. this._scene.autoClear = true;
  84679. if (this._resizeObserver) {
  84680. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  84681. this._resizeObserver = null;
  84682. }
  84683. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  84684. _super.prototype.dispose.call(this);
  84685. };
  84686. /**
  84687. * Serialize the rendering pipeline (Used when exporting)
  84688. * @returns the serialized object
  84689. */
  84690. DefaultRenderingPipeline.prototype.serialize = function () {
  84691. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84692. serializationObject.customType = "DefaultRenderingPipeline";
  84693. return serializationObject;
  84694. };
  84695. /**
  84696. * Parse the serialized pipeline
  84697. * @param source Source pipeline.
  84698. * @param scene The scene to load the pipeline to.
  84699. * @param rootUrl The URL of the serialized pipeline.
  84700. * @returns An instantiated pipeline from the serialized object.
  84701. */
  84702. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  84703. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  84704. };
  84705. __decorate([
  84706. BABYLON.serialize()
  84707. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  84708. __decorate([
  84709. BABYLON.serialize()
  84710. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  84711. __decorate([
  84712. BABYLON.serialize()
  84713. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  84714. __decorate([
  84715. BABYLON.serialize()
  84716. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  84717. __decorate([
  84718. BABYLON.serialize()
  84719. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  84720. __decorate([
  84721. BABYLON.serialize()
  84722. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  84723. __decorate([
  84724. BABYLON.serialize()
  84725. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  84726. __decorate([
  84727. BABYLON.serialize()
  84728. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  84729. __decorate([
  84730. BABYLON.serialize()
  84731. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  84732. __decorate([
  84733. BABYLON.serialize()
  84734. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  84735. __decorate([
  84736. BABYLON.serialize()
  84737. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  84738. __decorate([
  84739. BABYLON.serialize()
  84740. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  84741. __decorate([
  84742. BABYLON.serialize()
  84743. ], DefaultRenderingPipeline.prototype, "samples", null);
  84744. __decorate([
  84745. BABYLON.serialize()
  84746. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  84747. __decorate([
  84748. BABYLON.serialize()
  84749. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  84750. __decorate([
  84751. BABYLON.serialize()
  84752. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  84753. __decorate([
  84754. BABYLON.serialize()
  84755. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  84756. return DefaultRenderingPipeline;
  84757. }(BABYLON.PostProcessRenderPipeline));
  84758. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  84759. })(BABYLON || (BABYLON = {}));
  84760. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  84761. var BABYLON;
  84762. (function (BABYLON) {
  84763. /**
  84764. * @hidden
  84765. */
  84766. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  84767. __extends(ImageProcessingConfigurationDefines, _super);
  84768. function ImageProcessingConfigurationDefines() {
  84769. var _this = _super.call(this) || this;
  84770. _this.IMAGEPROCESSING = false;
  84771. _this.VIGNETTE = false;
  84772. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  84773. _this.VIGNETTEBLENDMODEOPAQUE = false;
  84774. _this.TONEMAPPING = false;
  84775. _this.TONEMAPPING_ACES = false;
  84776. _this.CONTRAST = false;
  84777. _this.COLORCURVES = false;
  84778. _this.COLORGRADING = false;
  84779. _this.COLORGRADING3D = false;
  84780. _this.SAMPLER3DGREENDEPTH = false;
  84781. _this.SAMPLER3DBGRMAP = false;
  84782. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  84783. _this.EXPOSURE = false;
  84784. _this.rebuild();
  84785. return _this;
  84786. }
  84787. return ImageProcessingConfigurationDefines;
  84788. }(BABYLON.MaterialDefines));
  84789. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  84790. /**
  84791. * This groups together the common properties used for image processing either in direct forward pass
  84792. * or through post processing effect depending on the use of the image processing pipeline in your scene
  84793. * or not.
  84794. */
  84795. var ImageProcessingConfiguration = /** @class */ (function () {
  84796. function ImageProcessingConfiguration() {
  84797. /**
  84798. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  84799. */
  84800. this.colorCurves = new BABYLON.ColorCurves();
  84801. this._colorCurvesEnabled = false;
  84802. this._colorGradingEnabled = false;
  84803. this._colorGradingWithGreenDepth = true;
  84804. this._colorGradingBGR = true;
  84805. /** @hidden */
  84806. this._exposure = 1.0;
  84807. this._toneMappingEnabled = false;
  84808. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  84809. this._contrast = 1.0;
  84810. /**
  84811. * Vignette stretch size.
  84812. */
  84813. this.vignetteStretch = 0;
  84814. /**
  84815. * Vignette centre X Offset.
  84816. */
  84817. this.vignetteCentreX = 0;
  84818. /**
  84819. * Vignette centre Y Offset.
  84820. */
  84821. this.vignetteCentreY = 0;
  84822. /**
  84823. * Vignette weight or intensity of the vignette effect.
  84824. */
  84825. this.vignetteWeight = 1.5;
  84826. /**
  84827. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  84828. * if vignetteEnabled is set to true.
  84829. */
  84830. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  84831. /**
  84832. * Camera field of view used by the Vignette effect.
  84833. */
  84834. this.vignetteCameraFov = 0.5;
  84835. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  84836. this._vignetteEnabled = false;
  84837. this._applyByPostProcess = false;
  84838. this._isEnabled = true;
  84839. /**
  84840. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  84841. */
  84842. this.onUpdateParameters = new BABYLON.Observable();
  84843. }
  84844. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  84845. /**
  84846. * Gets wether the color curves effect is enabled.
  84847. */
  84848. get: function () {
  84849. return this._colorCurvesEnabled;
  84850. },
  84851. /**
  84852. * Sets wether the color curves effect is enabled.
  84853. */
  84854. set: function (value) {
  84855. if (this._colorCurvesEnabled === value) {
  84856. return;
  84857. }
  84858. this._colorCurvesEnabled = value;
  84859. this._updateParameters();
  84860. },
  84861. enumerable: true,
  84862. configurable: true
  84863. });
  84864. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  84865. /**
  84866. * Gets wether the color grading effect is enabled.
  84867. */
  84868. get: function () {
  84869. return this._colorGradingEnabled;
  84870. },
  84871. /**
  84872. * Sets wether the color grading effect is enabled.
  84873. */
  84874. set: function (value) {
  84875. if (this._colorGradingEnabled === value) {
  84876. return;
  84877. }
  84878. this._colorGradingEnabled = value;
  84879. this._updateParameters();
  84880. },
  84881. enumerable: true,
  84882. configurable: true
  84883. });
  84884. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  84885. /**
  84886. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  84887. */
  84888. get: function () {
  84889. return this._colorGradingWithGreenDepth;
  84890. },
  84891. /**
  84892. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  84893. */
  84894. set: function (value) {
  84895. if (this._colorGradingWithGreenDepth === value) {
  84896. return;
  84897. }
  84898. this._colorGradingWithGreenDepth = value;
  84899. this._updateParameters();
  84900. },
  84901. enumerable: true,
  84902. configurable: true
  84903. });
  84904. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  84905. /**
  84906. * Gets wether the color grading texture contains BGR values.
  84907. */
  84908. get: function () {
  84909. return this._colorGradingBGR;
  84910. },
  84911. /**
  84912. * Sets wether the color grading texture contains BGR values.
  84913. */
  84914. set: function (value) {
  84915. if (this._colorGradingBGR === value) {
  84916. return;
  84917. }
  84918. this._colorGradingBGR = value;
  84919. this._updateParameters();
  84920. },
  84921. enumerable: true,
  84922. configurable: true
  84923. });
  84924. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  84925. /**
  84926. * Gets the Exposure used in the effect.
  84927. */
  84928. get: function () {
  84929. return this._exposure;
  84930. },
  84931. /**
  84932. * Sets the Exposure used in the effect.
  84933. */
  84934. set: function (value) {
  84935. if (this._exposure === value) {
  84936. return;
  84937. }
  84938. this._exposure = value;
  84939. this._updateParameters();
  84940. },
  84941. enumerable: true,
  84942. configurable: true
  84943. });
  84944. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  84945. /**
  84946. * Gets wether the tone mapping effect is enabled.
  84947. */
  84948. get: function () {
  84949. return this._toneMappingEnabled;
  84950. },
  84951. /**
  84952. * Sets wether the tone mapping effect is enabled.
  84953. */
  84954. set: function (value) {
  84955. if (this._toneMappingEnabled === value) {
  84956. return;
  84957. }
  84958. this._toneMappingEnabled = value;
  84959. this._updateParameters();
  84960. },
  84961. enumerable: true,
  84962. configurable: true
  84963. });
  84964. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  84965. /**
  84966. * Gets the type of tone mapping effect.
  84967. */
  84968. get: function () {
  84969. return this._toneMappingType;
  84970. },
  84971. /**
  84972. * Sets the type of tone mapping effect used in BabylonJS.
  84973. */
  84974. set: function (value) {
  84975. if (this._toneMappingType === value) {
  84976. return;
  84977. }
  84978. this._toneMappingType = value;
  84979. this._updateParameters();
  84980. },
  84981. enumerable: true,
  84982. configurable: true
  84983. });
  84984. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  84985. /**
  84986. * Gets the contrast used in the effect.
  84987. */
  84988. get: function () {
  84989. return this._contrast;
  84990. },
  84991. /**
  84992. * Sets the contrast used in the effect.
  84993. */
  84994. set: function (value) {
  84995. if (this._contrast === value) {
  84996. return;
  84997. }
  84998. this._contrast = value;
  84999. this._updateParameters();
  85000. },
  85001. enumerable: true,
  85002. configurable: true
  85003. });
  85004. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  85005. /**
  85006. * Gets the vignette blend mode allowing different kind of effect.
  85007. */
  85008. get: function () {
  85009. return this._vignetteBlendMode;
  85010. },
  85011. /**
  85012. * Sets the vignette blend mode allowing different kind of effect.
  85013. */
  85014. set: function (value) {
  85015. if (this._vignetteBlendMode === value) {
  85016. return;
  85017. }
  85018. this._vignetteBlendMode = value;
  85019. this._updateParameters();
  85020. },
  85021. enumerable: true,
  85022. configurable: true
  85023. });
  85024. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  85025. /**
  85026. * Gets wether the vignette effect is enabled.
  85027. */
  85028. get: function () {
  85029. return this._vignetteEnabled;
  85030. },
  85031. /**
  85032. * Sets wether the vignette effect is enabled.
  85033. */
  85034. set: function (value) {
  85035. if (this._vignetteEnabled === value) {
  85036. return;
  85037. }
  85038. this._vignetteEnabled = value;
  85039. this._updateParameters();
  85040. },
  85041. enumerable: true,
  85042. configurable: true
  85043. });
  85044. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  85045. /**
  85046. * Gets wether the image processing is applied through a post process or not.
  85047. */
  85048. get: function () {
  85049. return this._applyByPostProcess;
  85050. },
  85051. /**
  85052. * Sets wether the image processing is applied through a post process or not.
  85053. */
  85054. set: function (value) {
  85055. if (this._applyByPostProcess === value) {
  85056. return;
  85057. }
  85058. this._applyByPostProcess = value;
  85059. this._updateParameters();
  85060. },
  85061. enumerable: true,
  85062. configurable: true
  85063. });
  85064. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  85065. /**
  85066. * Gets wether the image processing is enabled or not.
  85067. */
  85068. get: function () {
  85069. return this._isEnabled;
  85070. },
  85071. /**
  85072. * Sets wether the image processing is enabled or not.
  85073. */
  85074. set: function (value) {
  85075. if (this._isEnabled === value) {
  85076. return;
  85077. }
  85078. this._isEnabled = value;
  85079. this._updateParameters();
  85080. },
  85081. enumerable: true,
  85082. configurable: true
  85083. });
  85084. /**
  85085. * Method called each time the image processing information changes requires to recompile the effect.
  85086. */
  85087. ImageProcessingConfiguration.prototype._updateParameters = function () {
  85088. this.onUpdateParameters.notifyObservers(this);
  85089. };
  85090. ImageProcessingConfiguration.prototype.getClassName = function () {
  85091. return "ImageProcessingConfiguration";
  85092. };
  85093. /**
  85094. * Prepare the list of uniforms associated with the Image Processing effects.
  85095. * @param uniformsList The list of uniforms used in the effect
  85096. * @param defines the list of defines currently in use
  85097. */
  85098. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  85099. if (defines.EXPOSURE) {
  85100. uniforms.push("exposureLinear");
  85101. }
  85102. if (defines.CONTRAST) {
  85103. uniforms.push("contrast");
  85104. }
  85105. if (defines.COLORGRADING) {
  85106. uniforms.push("colorTransformSettings");
  85107. }
  85108. if (defines.VIGNETTE) {
  85109. uniforms.push("vInverseScreenSize");
  85110. uniforms.push("vignetteSettings1");
  85111. uniforms.push("vignetteSettings2");
  85112. }
  85113. if (defines.COLORCURVES) {
  85114. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  85115. }
  85116. };
  85117. /**
  85118. * Prepare the list of samplers associated with the Image Processing effects.
  85119. * @param uniformsList The list of uniforms used in the effect
  85120. * @param defines the list of defines currently in use
  85121. */
  85122. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  85123. if (defines.COLORGRADING) {
  85124. samplersList.push("txColorTransform");
  85125. }
  85126. };
  85127. /**
  85128. * Prepare the list of defines associated to the shader.
  85129. * @param defines the list of defines to complete
  85130. */
  85131. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  85132. if (forPostProcess === void 0) { forPostProcess = false; }
  85133. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  85134. defines.VIGNETTE = false;
  85135. defines.TONEMAPPING = false;
  85136. defines.TONEMAPPING_ACES = false;
  85137. defines.CONTRAST = false;
  85138. defines.EXPOSURE = false;
  85139. defines.COLORCURVES = false;
  85140. defines.COLORGRADING = false;
  85141. defines.COLORGRADING3D = false;
  85142. defines.IMAGEPROCESSING = false;
  85143. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  85144. return;
  85145. }
  85146. defines.VIGNETTE = this.vignetteEnabled;
  85147. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  85148. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  85149. defines.TONEMAPPING = this.toneMappingEnabled;
  85150. switch (this._toneMappingType) {
  85151. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  85152. defines.TONEMAPPING_ACES = true;
  85153. break;
  85154. }
  85155. defines.CONTRAST = (this.contrast !== 1.0);
  85156. defines.EXPOSURE = (this.exposure !== 1.0);
  85157. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  85158. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  85159. if (defines.COLORGRADING) {
  85160. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  85161. }
  85162. else {
  85163. defines.COLORGRADING3D = false;
  85164. }
  85165. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  85166. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  85167. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  85168. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  85169. };
  85170. /**
  85171. * Returns true if all the image processing information are ready.
  85172. */
  85173. ImageProcessingConfiguration.prototype.isReady = function () {
  85174. // Color Grading texure can not be none blocking.
  85175. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  85176. };
  85177. /**
  85178. * Binds the image processing to the shader.
  85179. * @param effect The effect to bind to
  85180. */
  85181. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  85182. if (aspectRatio === void 0) { aspectRatio = 1; }
  85183. // Color Curves
  85184. if (this._colorCurvesEnabled && this.colorCurves) {
  85185. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  85186. }
  85187. // Vignette
  85188. if (this._vignetteEnabled) {
  85189. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  85190. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  85191. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  85192. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  85193. var vignetteScaleX = vignetteScaleY * aspectRatio;
  85194. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  85195. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  85196. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  85197. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  85198. var vignettePower = -2.0 * this.vignetteWeight;
  85199. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  85200. }
  85201. // Exposure
  85202. effect.setFloat("exposureLinear", this.exposure);
  85203. // Contrast
  85204. effect.setFloat("contrast", this.contrast);
  85205. // Color transform settings
  85206. if (this.colorGradingTexture) {
  85207. effect.setTexture("txColorTransform", this.colorGradingTexture);
  85208. var textureSize = this.colorGradingTexture.getSize().height;
  85209. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  85210. 0.5 / textureSize, // textureOffset
  85211. textureSize, // textureSize
  85212. this.colorGradingTexture.level // weight
  85213. );
  85214. }
  85215. };
  85216. /**
  85217. * Clones the current image processing instance.
  85218. * @return The cloned image processing
  85219. */
  85220. ImageProcessingConfiguration.prototype.clone = function () {
  85221. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  85222. };
  85223. /**
  85224. * Serializes the current image processing instance to a json representation.
  85225. * @return a JSON representation
  85226. */
  85227. ImageProcessingConfiguration.prototype.serialize = function () {
  85228. return BABYLON.SerializationHelper.Serialize(this);
  85229. };
  85230. /**
  85231. * Parses the image processing from a json representation.
  85232. * @param source the JSON source to parse
  85233. * @return The parsed image processing
  85234. */
  85235. ImageProcessingConfiguration.Parse = function (source) {
  85236. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  85237. };
  85238. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  85239. /**
  85240. * Used to apply the vignette as a mix with the pixel color.
  85241. */
  85242. get: function () {
  85243. return this._VIGNETTEMODE_MULTIPLY;
  85244. },
  85245. enumerable: true,
  85246. configurable: true
  85247. });
  85248. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  85249. /**
  85250. * Used to apply the vignette as a replacement of the pixel color.
  85251. */
  85252. get: function () {
  85253. return this._VIGNETTEMODE_OPAQUE;
  85254. },
  85255. enumerable: true,
  85256. configurable: true
  85257. });
  85258. /**
  85259. * Default tone mapping applied in BabylonJS.
  85260. */
  85261. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  85262. /**
  85263. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  85264. * to other engines rendering to increase portability.
  85265. */
  85266. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  85267. // Static constants associated to the image processing.
  85268. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  85269. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  85270. __decorate([
  85271. BABYLON.serializeAsColorCurves()
  85272. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  85273. __decorate([
  85274. BABYLON.serialize()
  85275. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  85276. __decorate([
  85277. BABYLON.serializeAsTexture()
  85278. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  85279. __decorate([
  85280. BABYLON.serialize()
  85281. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  85282. __decorate([
  85283. BABYLON.serialize()
  85284. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  85285. __decorate([
  85286. BABYLON.serialize()
  85287. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  85288. __decorate([
  85289. BABYLON.serialize()
  85290. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  85291. __decorate([
  85292. BABYLON.serialize()
  85293. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  85294. __decorate([
  85295. BABYLON.serialize()
  85296. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  85297. __decorate([
  85298. BABYLON.serialize()
  85299. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  85300. __decorate([
  85301. BABYLON.serialize()
  85302. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  85303. __decorate([
  85304. BABYLON.serialize()
  85305. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  85306. __decorate([
  85307. BABYLON.serialize()
  85308. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  85309. __decorate([
  85310. BABYLON.serialize()
  85311. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  85312. __decorate([
  85313. BABYLON.serializeAsColor4()
  85314. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  85315. __decorate([
  85316. BABYLON.serialize()
  85317. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  85318. __decorate([
  85319. BABYLON.serialize()
  85320. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  85321. __decorate([
  85322. BABYLON.serialize()
  85323. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  85324. __decorate([
  85325. BABYLON.serialize()
  85326. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  85327. __decorate([
  85328. BABYLON.serialize()
  85329. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  85330. return ImageProcessingConfiguration;
  85331. }());
  85332. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  85333. })(BABYLON || (BABYLON = {}));
  85334. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  85335. var BABYLON;
  85336. (function (BABYLON) {
  85337. /**
  85338. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  85339. * It can help converting any input color in a desired output one. This can then be used to create effects
  85340. * from sepia, black and white to sixties or futuristic rendering...
  85341. *
  85342. * The only supported format is currently 3dl.
  85343. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  85344. */
  85345. var ColorGradingTexture = /** @class */ (function (_super) {
  85346. __extends(ColorGradingTexture, _super);
  85347. /**
  85348. * Instantiates a ColorGradingTexture from the following parameters.
  85349. *
  85350. * @param url The location of the color gradind data (currently only supporting 3dl)
  85351. * @param scene The scene the texture will be used in
  85352. */
  85353. function ColorGradingTexture(url, scene) {
  85354. var _this = _super.call(this, scene) || this;
  85355. if (!url) {
  85356. return _this;
  85357. }
  85358. _this._engine = scene.getEngine();
  85359. _this._textureMatrix = BABYLON.Matrix.Identity();
  85360. _this.name = url;
  85361. _this.url = url;
  85362. _this.hasAlpha = false;
  85363. _this.isCube = false;
  85364. _this.is3D = _this._engine.webGLVersion > 1;
  85365. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85366. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85367. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85368. _this.anisotropicFilteringLevel = 1;
  85369. _this._texture = _this._getFromCache(url, true);
  85370. if (!_this._texture) {
  85371. if (!scene.useDelayedTextureLoading) {
  85372. _this.loadTexture();
  85373. }
  85374. else {
  85375. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  85376. }
  85377. }
  85378. return _this;
  85379. }
  85380. /**
  85381. * Returns the texture matrix used in most of the material.
  85382. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  85383. */
  85384. ColorGradingTexture.prototype.getTextureMatrix = function () {
  85385. return this._textureMatrix;
  85386. };
  85387. /**
  85388. * Occurs when the file being loaded is a .3dl LUT file.
  85389. */
  85390. ColorGradingTexture.prototype.load3dlTexture = function () {
  85391. var engine = this._engine;
  85392. var texture;
  85393. if (engine.webGLVersion === 1) {
  85394. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85395. }
  85396. else {
  85397. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85398. }
  85399. this._texture = texture;
  85400. var callback = function (text) {
  85401. if (typeof text !== "string") {
  85402. return;
  85403. }
  85404. var data = null;
  85405. var tempData = null;
  85406. var line;
  85407. var lines = text.split('\n');
  85408. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  85409. var maxColor = 0;
  85410. for (var i = 0; i < lines.length; i++) {
  85411. line = lines[i];
  85412. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  85413. continue;
  85414. if (line.indexOf('#') === 0)
  85415. continue;
  85416. var words = line.split(" ");
  85417. if (size === 0) {
  85418. // Number of space + one
  85419. size = words.length;
  85420. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  85421. tempData = new Float32Array(size * size * size * 4);
  85422. continue;
  85423. }
  85424. if (size != 0) {
  85425. var r = Math.max(parseInt(words[0]), 0);
  85426. var g = Math.max(parseInt(words[1]), 0);
  85427. var b = Math.max(parseInt(words[2]), 0);
  85428. maxColor = Math.max(r, maxColor);
  85429. maxColor = Math.max(g, maxColor);
  85430. maxColor = Math.max(b, maxColor);
  85431. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  85432. if (tempData) {
  85433. tempData[pixelStorageIndex + 0] = r;
  85434. tempData[pixelStorageIndex + 1] = g;
  85435. tempData[pixelStorageIndex + 2] = b;
  85436. }
  85437. pixelIndexSlice++;
  85438. if (pixelIndexSlice % size == 0) {
  85439. pixelIndexH++;
  85440. pixelIndexSlice = 0;
  85441. if (pixelIndexH % size == 0) {
  85442. pixelIndexW++;
  85443. pixelIndexH = 0;
  85444. }
  85445. }
  85446. }
  85447. }
  85448. if (tempData && data) {
  85449. for (var i = 0; i < tempData.length; i++) {
  85450. if (i > 0 && (i + 1) % 4 === 0) {
  85451. data[i] = 255;
  85452. }
  85453. else {
  85454. var value = tempData[i];
  85455. data[i] = (value / maxColor * 255);
  85456. }
  85457. }
  85458. }
  85459. if (texture.is3D) {
  85460. texture.updateSize(size, size, size);
  85461. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  85462. }
  85463. else {
  85464. texture.updateSize(size * size, size);
  85465. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  85466. }
  85467. };
  85468. var scene = this.getScene();
  85469. if (scene) {
  85470. scene._loadFile(this.url, callback);
  85471. }
  85472. else {
  85473. this._engine._loadFile(this.url, callback);
  85474. }
  85475. return this._texture;
  85476. };
  85477. /**
  85478. * Starts the loading process of the texture.
  85479. */
  85480. ColorGradingTexture.prototype.loadTexture = function () {
  85481. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  85482. this.load3dlTexture();
  85483. }
  85484. };
  85485. /**
  85486. * Clones the color gradind texture.
  85487. */
  85488. ColorGradingTexture.prototype.clone = function () {
  85489. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  85490. // Base texture
  85491. newTexture.level = this.level;
  85492. return newTexture;
  85493. };
  85494. /**
  85495. * Called during delayed load for textures.
  85496. */
  85497. ColorGradingTexture.prototype.delayLoad = function () {
  85498. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  85499. return;
  85500. }
  85501. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  85502. this._texture = this._getFromCache(this.url, true);
  85503. if (!this._texture) {
  85504. this.loadTexture();
  85505. }
  85506. };
  85507. /**
  85508. * Parses a color grading texture serialized by Babylon.
  85509. * @param parsedTexture The texture information being parsedTexture
  85510. * @param scene The scene to load the texture in
  85511. * @param rootUrl The root url of the data assets to load
  85512. * @return A color gradind texture
  85513. */
  85514. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  85515. var texture = null;
  85516. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  85517. texture = new ColorGradingTexture(parsedTexture.name, scene);
  85518. texture.name = parsedTexture.name;
  85519. texture.level = parsedTexture.level;
  85520. }
  85521. return texture;
  85522. };
  85523. /**
  85524. * Serializes the LUT texture to json format.
  85525. */
  85526. ColorGradingTexture.prototype.serialize = function () {
  85527. if (!this.name) {
  85528. return null;
  85529. }
  85530. var serializationObject = {};
  85531. serializationObject.name = this.name;
  85532. serializationObject.level = this.level;
  85533. serializationObject.customType = "BABYLON.ColorGradingTexture";
  85534. return serializationObject;
  85535. };
  85536. /**
  85537. * Empty line regex stored for GC.
  85538. */
  85539. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  85540. return ColorGradingTexture;
  85541. }(BABYLON.BaseTexture));
  85542. BABYLON.ColorGradingTexture = ColorGradingTexture;
  85543. })(BABYLON || (BABYLON = {}));
  85544. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  85545. var BABYLON;
  85546. (function (BABYLON) {
  85547. /**
  85548. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  85549. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  85550. * 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;
  85551. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  85552. */
  85553. var ColorCurves = /** @class */ (function () {
  85554. function ColorCurves() {
  85555. this._dirty = true;
  85556. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  85557. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  85558. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  85559. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  85560. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  85561. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  85562. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  85563. this._globalHue = 30;
  85564. this._globalDensity = 0;
  85565. this._globalSaturation = 0;
  85566. this._globalExposure = 0;
  85567. this._highlightsHue = 30;
  85568. this._highlightsDensity = 0;
  85569. this._highlightsSaturation = 0;
  85570. this._highlightsExposure = 0;
  85571. this._midtonesHue = 30;
  85572. this._midtonesDensity = 0;
  85573. this._midtonesSaturation = 0;
  85574. this._midtonesExposure = 0;
  85575. this._shadowsHue = 30;
  85576. this._shadowsDensity = 0;
  85577. this._shadowsSaturation = 0;
  85578. this._shadowsExposure = 0;
  85579. }
  85580. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  85581. /**
  85582. * Gets the global Hue value.
  85583. * 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).
  85584. */
  85585. get: function () {
  85586. return this._globalHue;
  85587. },
  85588. /**
  85589. * Sets the global Hue value.
  85590. * 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).
  85591. */
  85592. set: function (value) {
  85593. this._globalHue = value;
  85594. this._dirty = true;
  85595. },
  85596. enumerable: true,
  85597. configurable: true
  85598. });
  85599. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  85600. /**
  85601. * Gets the global Density value.
  85602. * 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.
  85603. * Values less than zero provide a filter of opposite hue.
  85604. */
  85605. get: function () {
  85606. return this._globalDensity;
  85607. },
  85608. /**
  85609. * Sets the global Density value.
  85610. * 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.
  85611. * Values less than zero provide a filter of opposite hue.
  85612. */
  85613. set: function (value) {
  85614. this._globalDensity = value;
  85615. this._dirty = true;
  85616. },
  85617. enumerable: true,
  85618. configurable: true
  85619. });
  85620. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  85621. /**
  85622. * Gets the global Saturation value.
  85623. * 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.
  85624. */
  85625. get: function () {
  85626. return this._globalSaturation;
  85627. },
  85628. /**
  85629. * Sets the global Saturation value.
  85630. * 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.
  85631. */
  85632. set: function (value) {
  85633. this._globalSaturation = value;
  85634. this._dirty = true;
  85635. },
  85636. enumerable: true,
  85637. configurable: true
  85638. });
  85639. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  85640. /**
  85641. * Gets the global Exposure value.
  85642. * 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.
  85643. */
  85644. get: function () {
  85645. return this._globalExposure;
  85646. },
  85647. /**
  85648. * Sets the global Exposure value.
  85649. * 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.
  85650. */
  85651. set: function (value) {
  85652. this._globalExposure = value;
  85653. this._dirty = true;
  85654. },
  85655. enumerable: true,
  85656. configurable: true
  85657. });
  85658. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  85659. /**
  85660. * Gets the highlights Hue value.
  85661. * 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).
  85662. */
  85663. get: function () {
  85664. return this._highlightsHue;
  85665. },
  85666. /**
  85667. * Sets the highlights Hue value.
  85668. * 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).
  85669. */
  85670. set: function (value) {
  85671. this._highlightsHue = value;
  85672. this._dirty = true;
  85673. },
  85674. enumerable: true,
  85675. configurable: true
  85676. });
  85677. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  85678. /**
  85679. * Gets the highlights Density value.
  85680. * 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.
  85681. * Values less than zero provide a filter of opposite hue.
  85682. */
  85683. get: function () {
  85684. return this._highlightsDensity;
  85685. },
  85686. /**
  85687. * Sets the highlights Density value.
  85688. * 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.
  85689. * Values less than zero provide a filter of opposite hue.
  85690. */
  85691. set: function (value) {
  85692. this._highlightsDensity = value;
  85693. this._dirty = true;
  85694. },
  85695. enumerable: true,
  85696. configurable: true
  85697. });
  85698. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  85699. /**
  85700. * Gets the highlights Saturation value.
  85701. * 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.
  85702. */
  85703. get: function () {
  85704. return this._highlightsSaturation;
  85705. },
  85706. /**
  85707. * Sets the highlights Saturation value.
  85708. * 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.
  85709. */
  85710. set: function (value) {
  85711. this._highlightsSaturation = value;
  85712. this._dirty = true;
  85713. },
  85714. enumerable: true,
  85715. configurable: true
  85716. });
  85717. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  85718. /**
  85719. * Gets the highlights Exposure value.
  85720. * 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.
  85721. */
  85722. get: function () {
  85723. return this._highlightsExposure;
  85724. },
  85725. /**
  85726. * Sets the highlights Exposure value.
  85727. * 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.
  85728. */
  85729. set: function (value) {
  85730. this._highlightsExposure = value;
  85731. this._dirty = true;
  85732. },
  85733. enumerable: true,
  85734. configurable: true
  85735. });
  85736. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  85737. /**
  85738. * Gets the midtones Hue value.
  85739. * 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).
  85740. */
  85741. get: function () {
  85742. return this._midtonesHue;
  85743. },
  85744. /**
  85745. * Sets the midtones Hue value.
  85746. * 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).
  85747. */
  85748. set: function (value) {
  85749. this._midtonesHue = value;
  85750. this._dirty = true;
  85751. },
  85752. enumerable: true,
  85753. configurable: true
  85754. });
  85755. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  85756. /**
  85757. * Gets the midtones Density value.
  85758. * 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.
  85759. * Values less than zero provide a filter of opposite hue.
  85760. */
  85761. get: function () {
  85762. return this._midtonesDensity;
  85763. },
  85764. /**
  85765. * Sets the midtones Density value.
  85766. * 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.
  85767. * Values less than zero provide a filter of opposite hue.
  85768. */
  85769. set: function (value) {
  85770. this._midtonesDensity = value;
  85771. this._dirty = true;
  85772. },
  85773. enumerable: true,
  85774. configurable: true
  85775. });
  85776. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  85777. /**
  85778. * Gets the midtones Saturation value.
  85779. * 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.
  85780. */
  85781. get: function () {
  85782. return this._midtonesSaturation;
  85783. },
  85784. /**
  85785. * Sets the midtones Saturation value.
  85786. * 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.
  85787. */
  85788. set: function (value) {
  85789. this._midtonesSaturation = value;
  85790. this._dirty = true;
  85791. },
  85792. enumerable: true,
  85793. configurable: true
  85794. });
  85795. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  85796. /**
  85797. * Gets the midtones Exposure value.
  85798. * 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.
  85799. */
  85800. get: function () {
  85801. return this._midtonesExposure;
  85802. },
  85803. /**
  85804. * Sets the midtones Exposure value.
  85805. * 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.
  85806. */
  85807. set: function (value) {
  85808. this._midtonesExposure = value;
  85809. this._dirty = true;
  85810. },
  85811. enumerable: true,
  85812. configurable: true
  85813. });
  85814. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  85815. /**
  85816. * Gets the shadows Hue value.
  85817. * 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).
  85818. */
  85819. get: function () {
  85820. return this._shadowsHue;
  85821. },
  85822. /**
  85823. * Sets the shadows Hue value.
  85824. * 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).
  85825. */
  85826. set: function (value) {
  85827. this._shadowsHue = value;
  85828. this._dirty = true;
  85829. },
  85830. enumerable: true,
  85831. configurable: true
  85832. });
  85833. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  85834. /**
  85835. * Gets the shadows Density value.
  85836. * 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.
  85837. * Values less than zero provide a filter of opposite hue.
  85838. */
  85839. get: function () {
  85840. return this._shadowsDensity;
  85841. },
  85842. /**
  85843. * Sets the shadows Density value.
  85844. * 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.
  85845. * Values less than zero provide a filter of opposite hue.
  85846. */
  85847. set: function (value) {
  85848. this._shadowsDensity = value;
  85849. this._dirty = true;
  85850. },
  85851. enumerable: true,
  85852. configurable: true
  85853. });
  85854. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  85855. /**
  85856. * Gets the shadows Saturation value.
  85857. * 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.
  85858. */
  85859. get: function () {
  85860. return this._shadowsSaturation;
  85861. },
  85862. /**
  85863. * Sets the shadows Saturation value.
  85864. * 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.
  85865. */
  85866. set: function (value) {
  85867. this._shadowsSaturation = value;
  85868. this._dirty = true;
  85869. },
  85870. enumerable: true,
  85871. configurable: true
  85872. });
  85873. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  85874. /**
  85875. * Gets the shadows Exposure value.
  85876. * 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.
  85877. */
  85878. get: function () {
  85879. return this._shadowsExposure;
  85880. },
  85881. /**
  85882. * Sets the shadows Exposure value.
  85883. * 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.
  85884. */
  85885. set: function (value) {
  85886. this._shadowsExposure = value;
  85887. this._dirty = true;
  85888. },
  85889. enumerable: true,
  85890. configurable: true
  85891. });
  85892. /**
  85893. * Returns the class name
  85894. * @returns The class name
  85895. */
  85896. ColorCurves.prototype.getClassName = function () {
  85897. return "ColorCurves";
  85898. };
  85899. /**
  85900. * Binds the color curves to the shader.
  85901. * @param colorCurves The color curve to bind
  85902. * @param effect The effect to bind to
  85903. * @param positiveUniform The positive uniform shader parameter
  85904. * @param neutralUniform The neutral uniform shader parameter
  85905. * @param negativeUniform The negative uniform shader parameter
  85906. */
  85907. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  85908. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  85909. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  85910. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  85911. if (colorCurves._dirty) {
  85912. colorCurves._dirty = false;
  85913. // Fill in global info.
  85914. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  85915. // Compute highlights info.
  85916. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  85917. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  85918. // Compute midtones info.
  85919. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  85920. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  85921. // Compute shadows info.
  85922. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  85923. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  85924. // Compute deltas (neutral is midtones).
  85925. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  85926. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  85927. }
  85928. if (effect) {
  85929. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  85930. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  85931. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  85932. }
  85933. };
  85934. /**
  85935. * Prepare the list of uniforms associated with the ColorCurves effects.
  85936. * @param uniformsList The list of uniforms used in the effect
  85937. */
  85938. ColorCurves.PrepareUniforms = function (uniformsList) {
  85939. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  85940. };
  85941. /**
  85942. * Returns color grading data based on a hue, density, saturation and exposure value.
  85943. * @param filterHue The hue of the color filter.
  85944. * @param filterDensity The density of the color filter.
  85945. * @param saturation The saturation.
  85946. * @param exposure The exposure.
  85947. * @param result The result data container.
  85948. */
  85949. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  85950. if (hue == null) {
  85951. return;
  85952. }
  85953. hue = ColorCurves.clamp(hue, 0, 360);
  85954. density = ColorCurves.clamp(density, -100, 100);
  85955. saturation = ColorCurves.clamp(saturation, -100, 100);
  85956. exposure = ColorCurves.clamp(exposure, -100, 100);
  85957. // Remap the slider/config filter density with non-linear mapping and also scale by half
  85958. // so that the maximum filter density is only 50% control. This provides fine control
  85959. // for small values and reasonable range.
  85960. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  85961. density *= 0.5;
  85962. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  85963. if (density < 0) {
  85964. density *= -1;
  85965. hue = (hue + 180) % 360;
  85966. }
  85967. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  85968. result.scaleToRef(2, result);
  85969. result.a = 1 + 0.01 * saturation;
  85970. };
  85971. /**
  85972. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  85973. * @param value The input slider value in range [-100,100].
  85974. * @returns Adjusted value.
  85975. */
  85976. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  85977. value /= 100;
  85978. var x = Math.abs(value);
  85979. x = Math.pow(x, 2);
  85980. if (value < 0) {
  85981. x *= -1;
  85982. }
  85983. x *= 100;
  85984. return x;
  85985. };
  85986. /**
  85987. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  85988. * @param hue The hue (H) input.
  85989. * @param saturation The saturation (S) input.
  85990. * @param brightness The brightness (B) input.
  85991. * @result An RGBA color represented as Vector4.
  85992. */
  85993. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  85994. var h = ColorCurves.clamp(hue, 0, 360);
  85995. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  85996. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  85997. if (s === 0) {
  85998. result.r = v;
  85999. result.g = v;
  86000. result.b = v;
  86001. }
  86002. else {
  86003. // sector 0 to 5
  86004. h /= 60;
  86005. var i = Math.floor(h);
  86006. // fractional part of h
  86007. var f = h - i;
  86008. var p = v * (1 - s);
  86009. var q = v * (1 - s * f);
  86010. var t = v * (1 - s * (1 - f));
  86011. switch (i) {
  86012. case 0:
  86013. result.r = v;
  86014. result.g = t;
  86015. result.b = p;
  86016. break;
  86017. case 1:
  86018. result.r = q;
  86019. result.g = v;
  86020. result.b = p;
  86021. break;
  86022. case 2:
  86023. result.r = p;
  86024. result.g = v;
  86025. result.b = t;
  86026. break;
  86027. case 3:
  86028. result.r = p;
  86029. result.g = q;
  86030. result.b = v;
  86031. break;
  86032. case 4:
  86033. result.r = t;
  86034. result.g = p;
  86035. result.b = v;
  86036. break;
  86037. default: // case 5:
  86038. result.r = v;
  86039. result.g = p;
  86040. result.b = q;
  86041. break;
  86042. }
  86043. }
  86044. result.a = 1;
  86045. };
  86046. /**
  86047. * Returns a value clamped between min and max
  86048. * @param value The value to clamp
  86049. * @param min The minimum of value
  86050. * @param max The maximum of value
  86051. * @returns The clamped value.
  86052. */
  86053. ColorCurves.clamp = function (value, min, max) {
  86054. return Math.min(Math.max(value, min), max);
  86055. };
  86056. /**
  86057. * Clones the current color curve instance.
  86058. * @return The cloned curves
  86059. */
  86060. ColorCurves.prototype.clone = function () {
  86061. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  86062. };
  86063. /**
  86064. * Serializes the current color curve instance to a json representation.
  86065. * @return a JSON representation
  86066. */
  86067. ColorCurves.prototype.serialize = function () {
  86068. return BABYLON.SerializationHelper.Serialize(this);
  86069. };
  86070. /**
  86071. * Parses the color curve from a json representation.
  86072. * @param source the JSON source to parse
  86073. * @return The parsed curves
  86074. */
  86075. ColorCurves.Parse = function (source) {
  86076. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  86077. };
  86078. __decorate([
  86079. BABYLON.serialize()
  86080. ], ColorCurves.prototype, "_globalHue", void 0);
  86081. __decorate([
  86082. BABYLON.serialize()
  86083. ], ColorCurves.prototype, "_globalDensity", void 0);
  86084. __decorate([
  86085. BABYLON.serialize()
  86086. ], ColorCurves.prototype, "_globalSaturation", void 0);
  86087. __decorate([
  86088. BABYLON.serialize()
  86089. ], ColorCurves.prototype, "_globalExposure", void 0);
  86090. __decorate([
  86091. BABYLON.serialize()
  86092. ], ColorCurves.prototype, "_highlightsHue", void 0);
  86093. __decorate([
  86094. BABYLON.serialize()
  86095. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  86096. __decorate([
  86097. BABYLON.serialize()
  86098. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  86099. __decorate([
  86100. BABYLON.serialize()
  86101. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  86102. __decorate([
  86103. BABYLON.serialize()
  86104. ], ColorCurves.prototype, "_midtonesHue", void 0);
  86105. __decorate([
  86106. BABYLON.serialize()
  86107. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  86108. __decorate([
  86109. BABYLON.serialize()
  86110. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  86111. __decorate([
  86112. BABYLON.serialize()
  86113. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  86114. return ColorCurves;
  86115. }());
  86116. BABYLON.ColorCurves = ColorCurves;
  86117. })(BABYLON || (BABYLON = {}));
  86118. //# sourceMappingURL=babylon.colorCurves.js.map
  86119. var BABYLON;
  86120. (function (BABYLON) {
  86121. var RefractionPostProcess = /** @class */ (function (_super) {
  86122. __extends(RefractionPostProcess, _super);
  86123. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  86124. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  86125. _this.color = color;
  86126. _this.depth = depth;
  86127. _this.colorLevel = colorLevel;
  86128. _this._ownRefractionTexture = true;
  86129. _this.onActivateObservable.add(function (cam) {
  86130. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  86131. });
  86132. _this.onApplyObservable.add(function (effect) {
  86133. effect.setColor3("baseColor", _this.color);
  86134. effect.setFloat("depth", _this.depth);
  86135. effect.setFloat("colorLevel", _this.colorLevel);
  86136. effect.setTexture("refractionSampler", _this._refTexture);
  86137. });
  86138. return _this;
  86139. }
  86140. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  86141. /**
  86142. * Gets or sets the refraction texture
  86143. * Please note that you are responsible for disposing the texture if you set it manually
  86144. */
  86145. get: function () {
  86146. return this._refTexture;
  86147. },
  86148. set: function (value) {
  86149. if (this._refTexture && this._ownRefractionTexture) {
  86150. this._refTexture.dispose();
  86151. }
  86152. this._refTexture = value;
  86153. this._ownRefractionTexture = false;
  86154. },
  86155. enumerable: true,
  86156. configurable: true
  86157. });
  86158. // Methods
  86159. RefractionPostProcess.prototype.dispose = function (camera) {
  86160. if (this._refTexture && this._ownRefractionTexture) {
  86161. this._refTexture.dispose();
  86162. this._refTexture = null;
  86163. }
  86164. _super.prototype.dispose.call(this, camera);
  86165. };
  86166. return RefractionPostProcess;
  86167. }(BABYLON.PostProcess));
  86168. BABYLON.RefractionPostProcess = RefractionPostProcess;
  86169. })(BABYLON || (BABYLON = {}));
  86170. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  86171. var BABYLON;
  86172. (function (BABYLON) {
  86173. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  86174. __extends(BlackAndWhitePostProcess, _super);
  86175. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  86176. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  86177. _this.degree = 1;
  86178. _this.onApplyObservable.add(function (effect) {
  86179. effect.setFloat("degree", _this.degree);
  86180. });
  86181. return _this;
  86182. }
  86183. return BlackAndWhitePostProcess;
  86184. }(BABYLON.PostProcess));
  86185. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  86186. })(BABYLON || (BABYLON = {}));
  86187. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  86188. var BABYLON;
  86189. (function (BABYLON) {
  86190. /**
  86191. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  86192. * input texture to perform effects such as edge detection or sharpening
  86193. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  86194. */
  86195. var ConvolutionPostProcess = /** @class */ (function (_super) {
  86196. __extends(ConvolutionPostProcess, _super);
  86197. /**
  86198. * Creates a new instance ConvolutionPostProcess
  86199. * @param name The name of the effect.
  86200. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  86201. * @param options The required width/height ratio to downsize to before computing the render pass.
  86202. * @param camera The camera to apply the render pass to.
  86203. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86204. * @param engine The engine which the post process will be applied. (default: current engine)
  86205. * @param reusable If the post process can be reused on the same frame. (default: false)
  86206. * @param textureType Type of textures used when performing the post process. (default: 0)
  86207. */
  86208. function ConvolutionPostProcess(name,
  86209. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  86210. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  86211. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86212. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  86213. _this.kernel = kernel;
  86214. _this.onApply = function (effect) {
  86215. effect.setFloat2("screenSize", _this.width, _this.height);
  86216. effect.setArray("kernel", _this.kernel);
  86217. };
  86218. return _this;
  86219. }
  86220. // Statics
  86221. /**
  86222. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  86223. */
  86224. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  86225. /**
  86226. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  86227. */
  86228. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  86229. /**
  86230. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  86231. */
  86232. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  86233. /**
  86234. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  86235. */
  86236. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  86237. /**
  86238. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  86239. */
  86240. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  86241. /**
  86242. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  86243. */
  86244. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  86245. return ConvolutionPostProcess;
  86246. }(BABYLON.PostProcess));
  86247. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  86248. })(BABYLON || (BABYLON = {}));
  86249. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  86250. var BABYLON;
  86251. (function (BABYLON) {
  86252. var FilterPostProcess = /** @class */ (function (_super) {
  86253. __extends(FilterPostProcess, _super);
  86254. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  86255. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  86256. _this.kernelMatrix = kernelMatrix;
  86257. _this.onApply = function (effect) {
  86258. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  86259. };
  86260. return _this;
  86261. }
  86262. return FilterPostProcess;
  86263. }(BABYLON.PostProcess));
  86264. BABYLON.FilterPostProcess = FilterPostProcess;
  86265. })(BABYLON || (BABYLON = {}));
  86266. //# sourceMappingURL=babylon.filterPostProcess.js.map
  86267. var BABYLON;
  86268. (function (BABYLON) {
  86269. /**
  86270. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  86271. */
  86272. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  86273. __extends(VolumetricLightScatteringPostProcess, _super);
  86274. /**
  86275. * @constructor
  86276. * @param {string} name - The post-process name
  86277. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  86278. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  86279. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  86280. * @param {number} samples - The post-process quality, default 100
  86281. * @param {number} samplingMode - The post-process filtering mode
  86282. * @param {BABYLON.Engine} engine - The babylon engine
  86283. * @param {boolean} reusable - If the post-process is reusable
  86284. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  86285. */
  86286. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  86287. if (samples === void 0) { samples = 100; }
  86288. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86289. 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;
  86290. _this._screenCoordinates = BABYLON.Vector2.Zero();
  86291. /**
  86292. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  86293. */
  86294. _this.customMeshPosition = BABYLON.Vector3.Zero();
  86295. /**
  86296. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  86297. */
  86298. _this.useCustomMeshPosition = false;
  86299. /**
  86300. * If the post-process should inverse the light scattering direction
  86301. */
  86302. _this.invert = true;
  86303. /**
  86304. * Array containing the excluded meshes not rendered in the internal pass
  86305. */
  86306. _this.excludedMeshes = new Array();
  86307. /**
  86308. * Controls the overall intensity of the post-process
  86309. */
  86310. _this.exposure = 0.3;
  86311. /**
  86312. * Dissipates each sample's contribution in range [0, 1]
  86313. */
  86314. _this.decay = 0.96815;
  86315. /**
  86316. * Controls the overall intensity of each sample
  86317. */
  86318. _this.weight = 0.58767;
  86319. /**
  86320. * Controls the density of each sample
  86321. */
  86322. _this.density = 0.926;
  86323. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  86324. engine = scene.getEngine();
  86325. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  86326. // Configure mesh
  86327. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  86328. // Configure
  86329. _this._createPass(scene, ratio.passRatio || ratio);
  86330. _this.onActivate = function (camera) {
  86331. if (!_this.isSupported) {
  86332. _this.dispose(camera);
  86333. }
  86334. _this.onActivate = null;
  86335. };
  86336. _this.onApplyObservable.add(function (effect) {
  86337. _this._updateMeshScreenCoordinates(scene);
  86338. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  86339. effect.setFloat("exposure", _this.exposure);
  86340. effect.setFloat("decay", _this.decay);
  86341. effect.setFloat("weight", _this.weight);
  86342. effect.setFloat("density", _this.density);
  86343. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  86344. });
  86345. return _this;
  86346. }
  86347. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  86348. /**
  86349. * @hidden
  86350. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  86351. */
  86352. get: function () {
  86353. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  86354. return false;
  86355. },
  86356. set: function (useDiffuseColor) {
  86357. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  86358. },
  86359. enumerable: true,
  86360. configurable: true
  86361. });
  86362. /**
  86363. * Returns the string "VolumetricLightScatteringPostProcess"
  86364. * @returns "VolumetricLightScatteringPostProcess"
  86365. */
  86366. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  86367. return "VolumetricLightScatteringPostProcess";
  86368. };
  86369. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  86370. var mesh = subMesh.getMesh();
  86371. // Render this.mesh as default
  86372. if (mesh === this.mesh && mesh.material) {
  86373. return mesh.material.isReady(mesh);
  86374. }
  86375. var defines = [];
  86376. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86377. var material = subMesh.getMaterial();
  86378. // Alpha test
  86379. if (material) {
  86380. if (material.needAlphaTesting()) {
  86381. defines.push("#define ALPHATEST");
  86382. }
  86383. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86384. attribs.push(BABYLON.VertexBuffer.UVKind);
  86385. defines.push("#define UV1");
  86386. }
  86387. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  86388. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86389. defines.push("#define UV2");
  86390. }
  86391. }
  86392. // Bones
  86393. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86394. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86395. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86396. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86397. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  86398. }
  86399. else {
  86400. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86401. }
  86402. // Instances
  86403. if (useInstances) {
  86404. defines.push("#define INSTANCES");
  86405. attribs.push("world0");
  86406. attribs.push("world1");
  86407. attribs.push("world2");
  86408. attribs.push("world3");
  86409. }
  86410. // Get correct effect
  86411. var join = defines.join("\n");
  86412. if (this._cachedDefines !== join) {
  86413. this._cachedDefines = join;
  86414. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  86415. }
  86416. return this._volumetricLightScatteringPass.isReady();
  86417. };
  86418. /**
  86419. * Sets the new light position for light scattering effect
  86420. * @param position The new custom light position
  86421. */
  86422. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  86423. this.customMeshPosition = position;
  86424. };
  86425. /**
  86426. * Returns the light position for light scattering effect
  86427. * @return {BABYLON.Vector3} The custom light position
  86428. */
  86429. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  86430. return this.customMeshPosition;
  86431. };
  86432. /**
  86433. * Disposes the internal assets and detaches the post-process from the camera
  86434. */
  86435. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  86436. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  86437. if (rttIndex !== -1) {
  86438. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  86439. }
  86440. this._volumetricLightScatteringRTT.dispose();
  86441. _super.prototype.dispose.call(this, camera);
  86442. };
  86443. /**
  86444. * Returns the render target texture used by the post-process
  86445. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  86446. */
  86447. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  86448. return this._volumetricLightScatteringRTT;
  86449. };
  86450. // Private methods
  86451. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  86452. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  86453. return true;
  86454. }
  86455. return false;
  86456. };
  86457. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  86458. var _this = this;
  86459. var engine = scene.getEngine();
  86460. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86461. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86462. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86463. this._volumetricLightScatteringRTT.renderList = null;
  86464. this._volumetricLightScatteringRTT.renderParticles = false;
  86465. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  86466. var camera = this.getCamera();
  86467. if (camera) {
  86468. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  86469. }
  86470. else {
  86471. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  86472. }
  86473. // Custom render function for submeshes
  86474. var renderSubMesh = function (subMesh) {
  86475. var mesh = subMesh.getRenderingMesh();
  86476. if (_this._meshExcluded(mesh)) {
  86477. return;
  86478. }
  86479. var material = subMesh.getMaterial();
  86480. if (!material) {
  86481. return;
  86482. }
  86483. var scene = mesh.getScene();
  86484. var engine = scene.getEngine();
  86485. // Culling
  86486. engine.setState(material.backFaceCulling);
  86487. // Managing instances
  86488. var batch = mesh._getInstancesRenderList(subMesh._id);
  86489. if (batch.mustReturn) {
  86490. return;
  86491. }
  86492. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  86493. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  86494. var effect = _this._volumetricLightScatteringPass;
  86495. if (mesh === _this.mesh) {
  86496. if (subMesh.effect) {
  86497. effect = subMesh.effect;
  86498. }
  86499. else {
  86500. effect = material.getEffect();
  86501. }
  86502. }
  86503. engine.enableEffect(effect);
  86504. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  86505. if (mesh === _this.mesh) {
  86506. material.bind(mesh.getWorldMatrix(), mesh);
  86507. }
  86508. else {
  86509. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  86510. // Alpha test
  86511. if (material && material.needAlphaTesting()) {
  86512. var alphaTexture = material.getAlphaTestTexture();
  86513. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  86514. if (alphaTexture) {
  86515. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  86516. }
  86517. }
  86518. // Bones
  86519. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86520. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86521. }
  86522. }
  86523. // Draw
  86524. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  86525. }
  86526. };
  86527. // Render target texture callbacks
  86528. var savedSceneClearColor;
  86529. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  86530. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  86531. savedSceneClearColor = scene.clearColor;
  86532. scene.clearColor = sceneClearColor;
  86533. });
  86534. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  86535. scene.clearColor = savedSceneClearColor;
  86536. });
  86537. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  86538. var engine = scene.getEngine();
  86539. var index;
  86540. if (depthOnlySubMeshes.length) {
  86541. engine.setColorWrite(false);
  86542. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  86543. renderSubMesh(depthOnlySubMeshes.data[index]);
  86544. }
  86545. engine.setColorWrite(true);
  86546. }
  86547. for (index = 0; index < opaqueSubMeshes.length; index++) {
  86548. renderSubMesh(opaqueSubMeshes.data[index]);
  86549. }
  86550. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  86551. renderSubMesh(alphaTestSubMeshes.data[index]);
  86552. }
  86553. if (transparentSubMeshes.length) {
  86554. // Sort sub meshes
  86555. for (index = 0; index < transparentSubMeshes.length; index++) {
  86556. var submesh = transparentSubMeshes.data[index];
  86557. var boundingInfo = submesh.getBoundingInfo();
  86558. if (boundingInfo && scene.activeCamera) {
  86559. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  86560. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  86561. }
  86562. }
  86563. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  86564. sortedArray.sort(function (a, b) {
  86565. // Alpha index first
  86566. if (a._alphaIndex > b._alphaIndex) {
  86567. return 1;
  86568. }
  86569. if (a._alphaIndex < b._alphaIndex) {
  86570. return -1;
  86571. }
  86572. // Then distance to camera
  86573. if (a._distanceToCamera < b._distanceToCamera) {
  86574. return 1;
  86575. }
  86576. if (a._distanceToCamera > b._distanceToCamera) {
  86577. return -1;
  86578. }
  86579. return 0;
  86580. });
  86581. // Render sub meshes
  86582. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  86583. for (index = 0; index < sortedArray.length; index++) {
  86584. renderSubMesh(sortedArray[index]);
  86585. }
  86586. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86587. }
  86588. };
  86589. };
  86590. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  86591. var transform = scene.getTransformMatrix();
  86592. var meshPosition;
  86593. if (this.useCustomMeshPosition) {
  86594. meshPosition = this.customMeshPosition;
  86595. }
  86596. else if (this.attachedNode) {
  86597. meshPosition = this.attachedNode.position;
  86598. }
  86599. else {
  86600. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  86601. }
  86602. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  86603. this._screenCoordinates.x = pos.x / this._viewPort.width;
  86604. this._screenCoordinates.y = pos.y / this._viewPort.height;
  86605. if (this.invert)
  86606. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  86607. };
  86608. // Static methods
  86609. /**
  86610. * Creates a default mesh for the Volumeric Light Scattering post-process
  86611. * @param name The mesh name
  86612. * @param scene The scene where to create the mesh
  86613. * @return {BABYLON.Mesh} the default mesh
  86614. */
  86615. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  86616. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  86617. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  86618. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  86619. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  86620. mesh.material = material;
  86621. return mesh;
  86622. };
  86623. __decorate([
  86624. BABYLON.serializeAsVector3()
  86625. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  86626. __decorate([
  86627. BABYLON.serialize()
  86628. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  86629. __decorate([
  86630. BABYLON.serialize()
  86631. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  86632. __decorate([
  86633. BABYLON.serializeAsMeshReference()
  86634. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  86635. __decorate([
  86636. BABYLON.serialize()
  86637. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  86638. __decorate([
  86639. BABYLON.serialize()
  86640. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  86641. __decorate([
  86642. BABYLON.serialize()
  86643. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  86644. __decorate([
  86645. BABYLON.serialize()
  86646. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  86647. __decorate([
  86648. BABYLON.serialize()
  86649. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  86650. return VolumetricLightScatteringPostProcess;
  86651. }(BABYLON.PostProcess));
  86652. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  86653. })(BABYLON || (BABYLON = {}));
  86654. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  86655. var BABYLON;
  86656. (function (BABYLON) {
  86657. /**
  86658. *
  86659. * This post-process allows the modification of rendered colors by using
  86660. * a 'look-up table' (LUT). This effect is also called Color Grading.
  86661. *
  86662. * The object needs to be provided an url to a texture containing the color
  86663. * look-up table: the texture must be 256 pixels wide and 16 pixels high.
  86664. * Use an image editing software to tweak the LUT to match your needs.
  86665. *
  86666. * For an example of a color LUT, see here:
  86667. * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  86668. * For explanations on color grading, see here:
  86669. * @see http://udn.epicgames.com/Three/ColorGrading.html
  86670. *
  86671. */
  86672. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  86673. __extends(ColorCorrectionPostProcess, _super);
  86674. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  86675. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  86676. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  86677. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  86678. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86679. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86680. _this.onApply = function (effect) {
  86681. effect.setTexture("colorTable", _this._colorTableTexture);
  86682. };
  86683. return _this;
  86684. }
  86685. return ColorCorrectionPostProcess;
  86686. }(BABYLON.PostProcess));
  86687. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  86688. })(BABYLON || (BABYLON = {}));
  86689. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  86690. var BABYLON;
  86691. (function (BABYLON) {
  86692. /** Defines operator used for tonemapping */
  86693. var TonemappingOperator;
  86694. (function (TonemappingOperator) {
  86695. /** Hable */
  86696. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  86697. /** Reinhard */
  86698. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  86699. /** HejiDawson */
  86700. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  86701. /** Photographic */
  86702. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  86703. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  86704. ;
  86705. /**
  86706. * Defines a post process to apply tone mapping
  86707. */
  86708. var TonemapPostProcess = /** @class */ (function (_super) {
  86709. __extends(TonemapPostProcess, _super);
  86710. /**
  86711. * Creates a new TonemapPostProcess
  86712. * @param name defines the name of the postprocess
  86713. * @param _operator defines the operator to use
  86714. * @param exposureAdjustment defines the required exposure adjustement
  86715. * @param camera defines the camera to use (can be null)
  86716. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  86717. * @param engine defines the hosting engine (can be ignore if camera is set)
  86718. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  86719. */
  86720. function TonemapPostProcess(name, _operator,
  86721. /** Defines the required exposure adjustement */
  86722. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  86723. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86724. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86725. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  86726. _this._operator = _operator;
  86727. _this.exposureAdjustment = exposureAdjustment;
  86728. var defines = "#define ";
  86729. if (_this._operator === TonemappingOperator.Hable)
  86730. defines += "HABLE_TONEMAPPING";
  86731. else if (_this._operator === TonemappingOperator.Reinhard)
  86732. defines += "REINHARD_TONEMAPPING";
  86733. else if (_this._operator === TonemappingOperator.HejiDawson)
  86734. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  86735. else if (_this._operator === TonemappingOperator.Photographic)
  86736. defines += "PHOTOGRAPHIC_TONEMAPPING";
  86737. //sadly a second call to create the effect.
  86738. _this.updateEffect(defines);
  86739. _this.onApply = function (effect) {
  86740. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  86741. };
  86742. return _this;
  86743. }
  86744. return TonemapPostProcess;
  86745. }(BABYLON.PostProcess));
  86746. BABYLON.TonemapPostProcess = TonemapPostProcess;
  86747. })(BABYLON || (BABYLON = {}));
  86748. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  86749. var BABYLON;
  86750. (function (BABYLON) {
  86751. var DisplayPassPostProcess = /** @class */ (function (_super) {
  86752. __extends(DisplayPassPostProcess, _super);
  86753. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  86754. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  86755. }
  86756. return DisplayPassPostProcess;
  86757. }(BABYLON.PostProcess));
  86758. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  86759. })(BABYLON || (BABYLON = {}));
  86760. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  86761. var BABYLON;
  86762. (function (BABYLON) {
  86763. var HighlightsPostProcess = /** @class */ (function (_super) {
  86764. __extends(HighlightsPostProcess, _super);
  86765. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  86766. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86767. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  86768. }
  86769. return HighlightsPostProcess;
  86770. }(BABYLON.PostProcess));
  86771. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  86772. })(BABYLON || (BABYLON = {}));
  86773. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  86774. var BABYLON;
  86775. (function (BABYLON) {
  86776. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  86777. __extends(ImageProcessingPostProcess, _super);
  86778. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  86779. if (camera === void 0) { camera = null; }
  86780. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86781. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  86782. _this._fromLinearSpace = true;
  86783. /**
  86784. * Defines cache preventing GC.
  86785. */
  86786. _this._defines = {
  86787. IMAGEPROCESSING: false,
  86788. VIGNETTE: false,
  86789. VIGNETTEBLENDMODEMULTIPLY: false,
  86790. VIGNETTEBLENDMODEOPAQUE: false,
  86791. TONEMAPPING: false,
  86792. TONEMAPPING_ACES: false,
  86793. CONTRAST: false,
  86794. COLORCURVES: false,
  86795. COLORGRADING: false,
  86796. COLORGRADING3D: false,
  86797. FROMLINEARSPACE: false,
  86798. SAMPLER3DGREENDEPTH: false,
  86799. SAMPLER3DBGRMAP: false,
  86800. IMAGEPROCESSINGPOSTPROCESS: false,
  86801. EXPOSURE: false,
  86802. };
  86803. // Setup the configuration as forced by the constructor. This would then not force the
  86804. // scene materials output in linear space and let untouched the default forward pass.
  86805. if (imageProcessingConfiguration) {
  86806. imageProcessingConfiguration.applyByPostProcess = true;
  86807. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  86808. // This will cause the shader to be compiled
  86809. _this.fromLinearSpace = false;
  86810. }
  86811. // Setup the default processing configuration to the scene.
  86812. else {
  86813. _this._attachImageProcessingConfiguration(null, true);
  86814. _this.imageProcessingConfiguration.applyByPostProcess = true;
  86815. }
  86816. _this.onApply = function (effect) {
  86817. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  86818. };
  86819. return _this;
  86820. }
  86821. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  86822. /**
  86823. * Gets the image processing configuration used either in this material.
  86824. */
  86825. get: function () {
  86826. return this._imageProcessingConfiguration;
  86827. },
  86828. /**
  86829. * Sets the Default image processing configuration used either in the this material.
  86830. *
  86831. * If sets to null, the scene one is in use.
  86832. */
  86833. set: function (value) {
  86834. this._attachImageProcessingConfiguration(value);
  86835. },
  86836. enumerable: true,
  86837. configurable: true
  86838. });
  86839. /**
  86840. * Attaches a new image processing configuration to the PBR Material.
  86841. * @param configuration
  86842. */
  86843. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  86844. var _this = this;
  86845. if (doNotBuild === void 0) { doNotBuild = false; }
  86846. if (configuration === this._imageProcessingConfiguration) {
  86847. return;
  86848. }
  86849. // Detaches observer.
  86850. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  86851. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  86852. }
  86853. // Pick the scene configuration if needed.
  86854. if (!configuration) {
  86855. var scene = null;
  86856. var engine = this.getEngine();
  86857. var camera = this.getCamera();
  86858. if (camera) {
  86859. scene = camera.getScene();
  86860. }
  86861. else if (engine && engine.scenes) {
  86862. var scenes = engine.scenes;
  86863. scene = scenes[scenes.length - 1];
  86864. }
  86865. else {
  86866. scene = BABYLON.Engine.LastCreatedScene;
  86867. }
  86868. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  86869. }
  86870. else {
  86871. this._imageProcessingConfiguration = configuration;
  86872. }
  86873. // Attaches observer.
  86874. if (this._imageProcessingConfiguration) {
  86875. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  86876. _this._updateParameters();
  86877. });
  86878. }
  86879. // Ensure the effect will be rebuilt.
  86880. if (!doNotBuild) {
  86881. this._updateParameters();
  86882. }
  86883. };
  86884. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  86885. /**
  86886. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  86887. */
  86888. get: function () {
  86889. return this.imageProcessingConfiguration.colorCurves;
  86890. },
  86891. /**
  86892. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  86893. */
  86894. set: function (value) {
  86895. this.imageProcessingConfiguration.colorCurves = value;
  86896. },
  86897. enumerable: true,
  86898. configurable: true
  86899. });
  86900. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  86901. /**
  86902. * Gets wether the color curves effect is enabled.
  86903. */
  86904. get: function () {
  86905. return this.imageProcessingConfiguration.colorCurvesEnabled;
  86906. },
  86907. /**
  86908. * Sets wether the color curves effect is enabled.
  86909. */
  86910. set: function (value) {
  86911. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  86912. },
  86913. enumerable: true,
  86914. configurable: true
  86915. });
  86916. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  86917. /**
  86918. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  86919. */
  86920. get: function () {
  86921. return this.imageProcessingConfiguration.colorGradingTexture;
  86922. },
  86923. /**
  86924. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  86925. */
  86926. set: function (value) {
  86927. this.imageProcessingConfiguration.colorGradingTexture = value;
  86928. },
  86929. enumerable: true,
  86930. configurable: true
  86931. });
  86932. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  86933. /**
  86934. * Gets wether the color grading effect is enabled.
  86935. */
  86936. get: function () {
  86937. return this.imageProcessingConfiguration.colorGradingEnabled;
  86938. },
  86939. /**
  86940. * Gets wether the color grading effect is enabled.
  86941. */
  86942. set: function (value) {
  86943. this.imageProcessingConfiguration.colorGradingEnabled = value;
  86944. },
  86945. enumerable: true,
  86946. configurable: true
  86947. });
  86948. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  86949. /**
  86950. * Gets exposure used in the effect.
  86951. */
  86952. get: function () {
  86953. return this.imageProcessingConfiguration.exposure;
  86954. },
  86955. /**
  86956. * Sets exposure used in the effect.
  86957. */
  86958. set: function (value) {
  86959. this.imageProcessingConfiguration.exposure = value;
  86960. },
  86961. enumerable: true,
  86962. configurable: true
  86963. });
  86964. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  86965. /**
  86966. * Gets wether tonemapping is enabled or not.
  86967. */
  86968. get: function () {
  86969. return this._imageProcessingConfiguration.toneMappingEnabled;
  86970. },
  86971. /**
  86972. * Sets wether tonemapping is enabled or not
  86973. */
  86974. set: function (value) {
  86975. this._imageProcessingConfiguration.toneMappingEnabled = value;
  86976. },
  86977. enumerable: true,
  86978. configurable: true
  86979. });
  86980. ;
  86981. ;
  86982. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  86983. /**
  86984. * Gets contrast used in the effect.
  86985. */
  86986. get: function () {
  86987. return this.imageProcessingConfiguration.contrast;
  86988. },
  86989. /**
  86990. * Sets contrast used in the effect.
  86991. */
  86992. set: function (value) {
  86993. this.imageProcessingConfiguration.contrast = value;
  86994. },
  86995. enumerable: true,
  86996. configurable: true
  86997. });
  86998. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  86999. /**
  87000. * Gets Vignette stretch size.
  87001. */
  87002. get: function () {
  87003. return this.imageProcessingConfiguration.vignetteStretch;
  87004. },
  87005. /**
  87006. * Sets Vignette stretch size.
  87007. */
  87008. set: function (value) {
  87009. this.imageProcessingConfiguration.vignetteStretch = value;
  87010. },
  87011. enumerable: true,
  87012. configurable: true
  87013. });
  87014. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  87015. /**
  87016. * Gets Vignette centre X Offset.
  87017. */
  87018. get: function () {
  87019. return this.imageProcessingConfiguration.vignetteCentreX;
  87020. },
  87021. /**
  87022. * Sets Vignette centre X Offset.
  87023. */
  87024. set: function (value) {
  87025. this.imageProcessingConfiguration.vignetteCentreX = value;
  87026. },
  87027. enumerable: true,
  87028. configurable: true
  87029. });
  87030. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  87031. /**
  87032. * Gets Vignette centre Y Offset.
  87033. */
  87034. get: function () {
  87035. return this.imageProcessingConfiguration.vignetteCentreY;
  87036. },
  87037. /**
  87038. * Sets Vignette centre Y Offset.
  87039. */
  87040. set: function (value) {
  87041. this.imageProcessingConfiguration.vignetteCentreY = value;
  87042. },
  87043. enumerable: true,
  87044. configurable: true
  87045. });
  87046. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  87047. /**
  87048. * Gets Vignette weight or intensity of the vignette effect.
  87049. */
  87050. get: function () {
  87051. return this.imageProcessingConfiguration.vignetteWeight;
  87052. },
  87053. /**
  87054. * Sets Vignette weight or intensity of the vignette effect.
  87055. */
  87056. set: function (value) {
  87057. this.imageProcessingConfiguration.vignetteWeight = value;
  87058. },
  87059. enumerable: true,
  87060. configurable: true
  87061. });
  87062. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  87063. /**
  87064. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  87065. * if vignetteEnabled is set to true.
  87066. */
  87067. get: function () {
  87068. return this.imageProcessingConfiguration.vignetteColor;
  87069. },
  87070. /**
  87071. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  87072. * if vignetteEnabled is set to true.
  87073. */
  87074. set: function (value) {
  87075. this.imageProcessingConfiguration.vignetteColor = value;
  87076. },
  87077. enumerable: true,
  87078. configurable: true
  87079. });
  87080. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  87081. /**
  87082. * Gets Camera field of view used by the Vignette effect.
  87083. */
  87084. get: function () {
  87085. return this.imageProcessingConfiguration.vignetteCameraFov;
  87086. },
  87087. /**
  87088. * Sets Camera field of view used by the Vignette effect.
  87089. */
  87090. set: function (value) {
  87091. this.imageProcessingConfiguration.vignetteCameraFov = value;
  87092. },
  87093. enumerable: true,
  87094. configurable: true
  87095. });
  87096. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  87097. /**
  87098. * Gets the vignette blend mode allowing different kind of effect.
  87099. */
  87100. get: function () {
  87101. return this.imageProcessingConfiguration.vignetteBlendMode;
  87102. },
  87103. /**
  87104. * Sets the vignette blend mode allowing different kind of effect.
  87105. */
  87106. set: function (value) {
  87107. this.imageProcessingConfiguration.vignetteBlendMode = value;
  87108. },
  87109. enumerable: true,
  87110. configurable: true
  87111. });
  87112. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  87113. /**
  87114. * Gets wether the vignette effect is enabled.
  87115. */
  87116. get: function () {
  87117. return this.imageProcessingConfiguration.vignetteEnabled;
  87118. },
  87119. /**
  87120. * Sets wether the vignette effect is enabled.
  87121. */
  87122. set: function (value) {
  87123. this.imageProcessingConfiguration.vignetteEnabled = value;
  87124. },
  87125. enumerable: true,
  87126. configurable: true
  87127. });
  87128. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  87129. /**
  87130. * Gets wether the input of the processing is in Gamma or Linear Space.
  87131. */
  87132. get: function () {
  87133. return this._fromLinearSpace;
  87134. },
  87135. /**
  87136. * Sets wether the input of the processing is in Gamma or Linear Space.
  87137. */
  87138. set: function (value) {
  87139. if (this._fromLinearSpace === value) {
  87140. return;
  87141. }
  87142. this._fromLinearSpace = value;
  87143. this._updateParameters();
  87144. },
  87145. enumerable: true,
  87146. configurable: true
  87147. });
  87148. ImageProcessingPostProcess.prototype.getClassName = function () {
  87149. return "ImageProcessingPostProcess";
  87150. };
  87151. ImageProcessingPostProcess.prototype._updateParameters = function () {
  87152. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  87153. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  87154. var defines = "";
  87155. for (var define in this._defines) {
  87156. if (this._defines[define]) {
  87157. defines += "#define " + define + ";\r\n";
  87158. }
  87159. }
  87160. var samplers = ["textureSampler"];
  87161. var uniforms = ["scale"];
  87162. if (BABYLON.ImageProcessingConfiguration) {
  87163. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  87164. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  87165. }
  87166. this.updateEffect(defines, uniforms, samplers);
  87167. };
  87168. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  87169. _super.prototype.dispose.call(this, camera);
  87170. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  87171. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  87172. }
  87173. if (this._imageProcessingConfiguration) {
  87174. this.imageProcessingConfiguration.applyByPostProcess = false;
  87175. }
  87176. };
  87177. __decorate([
  87178. BABYLON.serialize()
  87179. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  87180. return ImageProcessingPostProcess;
  87181. }(BABYLON.PostProcess));
  87182. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  87183. })(BABYLON || (BABYLON = {}));
  87184. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  87185. var BABYLON;
  87186. (function (BABYLON) {
  87187. /**
  87188. * Class used to store bone information
  87189. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  87190. */
  87191. var Bone = /** @class */ (function (_super) {
  87192. __extends(Bone, _super);
  87193. /**
  87194. * Create a new bone
  87195. * @param name defines the bone name
  87196. * @param skeleton defines the parent skeleton
  87197. * @param parentBone defines the parent (can be null if the bone is the root)
  87198. * @param localMatrix defines the local matrix
  87199. * @param restPose defines the rest pose matrix
  87200. * @param baseMatrix defines the base matrix
  87201. * @param index defines index of the bone in the hiearchy
  87202. */
  87203. function Bone(
  87204. /**
  87205. * defines the bone name
  87206. */
  87207. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  87208. if (parentBone === void 0) { parentBone = null; }
  87209. if (localMatrix === void 0) { localMatrix = null; }
  87210. if (restPose === void 0) { restPose = null; }
  87211. if (baseMatrix === void 0) { baseMatrix = null; }
  87212. if (index === void 0) { index = null; }
  87213. var _this = _super.call(this, name, skeleton.getScene()) || this;
  87214. _this.name = name;
  87215. /**
  87216. * Gets the list of child bones
  87217. */
  87218. _this.children = new Array();
  87219. /** Gets the animations associated with this bone */
  87220. _this.animations = new Array();
  87221. /**
  87222. * @hidden Internal only
  87223. * Set this value to map this bone to a different index in the transform matrices
  87224. * Set this value to -1 to exclude the bone from the transform matrices
  87225. */
  87226. _this._index = null;
  87227. _this._absoluteTransform = new BABYLON.Matrix();
  87228. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  87229. _this._scalingDeterminant = 1;
  87230. _this._worldTransform = new BABYLON.Matrix();
  87231. _this._needToDecompose = true;
  87232. _this._needToCompose = false;
  87233. _this._skeleton = skeleton;
  87234. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  87235. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  87236. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  87237. _this._index = index;
  87238. skeleton.bones.push(_this);
  87239. _this.setParent(parentBone, false);
  87240. if (baseMatrix || localMatrix) {
  87241. _this._updateDifferenceMatrix();
  87242. }
  87243. return _this;
  87244. }
  87245. Object.defineProperty(Bone.prototype, "_matrix", {
  87246. /** @hidden */
  87247. get: function () {
  87248. this._compose();
  87249. return this._localMatrix;
  87250. },
  87251. /** @hidden */
  87252. set: function (value) {
  87253. this._localMatrix.copyFrom(value);
  87254. this._needToDecompose = true;
  87255. },
  87256. enumerable: true,
  87257. configurable: true
  87258. });
  87259. // Members
  87260. /**
  87261. * Gets the parent skeleton
  87262. * @returns a skeleton
  87263. */
  87264. Bone.prototype.getSkeleton = function () {
  87265. return this._skeleton;
  87266. };
  87267. /**
  87268. * Gets parent bone
  87269. * @returns a bone or null if the bone is the root of the bone hierarchy
  87270. */
  87271. Bone.prototype.getParent = function () {
  87272. return this._parent;
  87273. };
  87274. /**
  87275. * Sets the parent bone
  87276. * @param parent defines the parent (can be null if the bone is the root)
  87277. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  87278. */
  87279. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  87280. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  87281. if (this._parent === parent) {
  87282. return;
  87283. }
  87284. if (this._parent) {
  87285. var index = this._parent.children.indexOf(this);
  87286. if (index !== -1) {
  87287. this._parent.children.splice(index, 1);
  87288. }
  87289. }
  87290. this._parent = parent;
  87291. if (this._parent) {
  87292. this._parent.children.push(this);
  87293. }
  87294. if (updateDifferenceMatrix) {
  87295. this._updateDifferenceMatrix();
  87296. }
  87297. this.markAsDirty();
  87298. };
  87299. /**
  87300. * Gets the local matrix
  87301. * @returns a matrix
  87302. */
  87303. Bone.prototype.getLocalMatrix = function () {
  87304. this._compose();
  87305. return this._localMatrix;
  87306. };
  87307. /**
  87308. * Gets the base matrix (initial matrix which remains unchanged)
  87309. * @returns a matrix
  87310. */
  87311. Bone.prototype.getBaseMatrix = function () {
  87312. return this._baseMatrix;
  87313. };
  87314. /**
  87315. * Gets the rest pose matrix
  87316. * @returns a matrix
  87317. */
  87318. Bone.prototype.getRestPose = function () {
  87319. return this._restPose;
  87320. };
  87321. /**
  87322. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  87323. */
  87324. Bone.prototype.getWorldMatrix = function () {
  87325. return this._worldTransform;
  87326. };
  87327. /**
  87328. * Sets the local matrix to rest pose matrix
  87329. */
  87330. Bone.prototype.returnToRest = function () {
  87331. this.updateMatrix(this._restPose.clone());
  87332. };
  87333. /**
  87334. * Gets the inverse of the absolute transform matrix.
  87335. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  87336. * @returns a matrix
  87337. */
  87338. Bone.prototype.getInvertedAbsoluteTransform = function () {
  87339. return this._invertedAbsoluteTransform;
  87340. };
  87341. /**
  87342. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  87343. * @returns a matrix
  87344. */
  87345. Bone.prototype.getAbsoluteTransform = function () {
  87346. return this._absoluteTransform;
  87347. };
  87348. Object.defineProperty(Bone.prototype, "position", {
  87349. // Properties (matches AbstractMesh properties)
  87350. /** Gets or sets current position (in local space) */
  87351. get: function () {
  87352. this._decompose();
  87353. return this._localPosition;
  87354. },
  87355. set: function (newPosition) {
  87356. this._decompose();
  87357. this._localPosition.copyFrom(newPosition);
  87358. this._markAsDirtyAndCompose();
  87359. },
  87360. enumerable: true,
  87361. configurable: true
  87362. });
  87363. Object.defineProperty(Bone.prototype, "rotation", {
  87364. /** Gets or sets current rotation (in local space) */
  87365. get: function () {
  87366. return this.getRotation();
  87367. },
  87368. set: function (newRotation) {
  87369. this.setRotation(newRotation);
  87370. },
  87371. enumerable: true,
  87372. configurable: true
  87373. });
  87374. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  87375. /** Gets or sets current rotation quaternion (in local space) */
  87376. get: function () {
  87377. this._decompose();
  87378. return this._localRotation;
  87379. },
  87380. set: function (newRotation) {
  87381. this.setRotationQuaternion(newRotation);
  87382. },
  87383. enumerable: true,
  87384. configurable: true
  87385. });
  87386. Object.defineProperty(Bone.prototype, "scaling", {
  87387. /** Gets or sets current scaling (in local space) */
  87388. get: function () {
  87389. return this.getScale();
  87390. },
  87391. set: function (newScaling) {
  87392. this.setScale(newScaling);
  87393. },
  87394. enumerable: true,
  87395. configurable: true
  87396. });
  87397. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  87398. /**
  87399. * Gets the animation properties override
  87400. */
  87401. get: function () {
  87402. return this._skeleton.animationPropertiesOverride;
  87403. },
  87404. enumerable: true,
  87405. configurable: true
  87406. });
  87407. // Methods
  87408. Bone.prototype._decompose = function () {
  87409. if (!this._needToDecompose) {
  87410. return;
  87411. }
  87412. this._needToDecompose = false;
  87413. if (!this._localScaling) {
  87414. this._localScaling = BABYLON.Vector3.Zero();
  87415. this._localRotation = BABYLON.Quaternion.Zero();
  87416. this._localPosition = BABYLON.Vector3.Zero();
  87417. }
  87418. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  87419. };
  87420. Bone.prototype._compose = function () {
  87421. if (!this._needToCompose) {
  87422. return;
  87423. }
  87424. this._needToCompose = false;
  87425. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  87426. };
  87427. /**
  87428. * Update the base and local matrices
  87429. * @param matrix defines the new base or local matrix
  87430. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  87431. * @param updateLocalMatrix defines if the local matrix should be updated
  87432. */
  87433. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  87434. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  87435. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  87436. this._baseMatrix.copyFrom(matrix);
  87437. if (updateDifferenceMatrix) {
  87438. this._updateDifferenceMatrix();
  87439. }
  87440. if (updateLocalMatrix) {
  87441. this._localMatrix.copyFrom(matrix);
  87442. this._markAsDirtyAndDecompose();
  87443. }
  87444. else {
  87445. this.markAsDirty();
  87446. }
  87447. };
  87448. /** @hidden */
  87449. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  87450. if (updateChildren === void 0) { updateChildren = true; }
  87451. if (!rootMatrix) {
  87452. rootMatrix = this._baseMatrix;
  87453. }
  87454. if (this._parent) {
  87455. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  87456. }
  87457. else {
  87458. this._absoluteTransform.copyFrom(rootMatrix);
  87459. }
  87460. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  87461. if (updateChildren) {
  87462. for (var index = 0; index < this.children.length; index++) {
  87463. this.children[index]._updateDifferenceMatrix();
  87464. }
  87465. }
  87466. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  87467. };
  87468. /**
  87469. * Flag the bone as dirty (Forcing it to update everything)
  87470. */
  87471. Bone.prototype.markAsDirty = function () {
  87472. this._currentRenderId++;
  87473. this._childRenderId++;
  87474. this._skeleton._markAsDirty();
  87475. };
  87476. Bone.prototype._markAsDirtyAndCompose = function () {
  87477. this.markAsDirty();
  87478. this._needToCompose = true;
  87479. };
  87480. Bone.prototype._markAsDirtyAndDecompose = function () {
  87481. this.markAsDirty();
  87482. this._needToDecompose = true;
  87483. };
  87484. /**
  87485. * Copy an animation range from another bone
  87486. * @param source defines the source bone
  87487. * @param rangeName defines the range name to copy
  87488. * @param frameOffset defines the frame offset
  87489. * @param rescaleAsRequired defines if rescaling must be applied if required
  87490. * @param skelDimensionsRatio defines the scaling ratio
  87491. * @returns true if operation was successful
  87492. */
  87493. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  87494. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  87495. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  87496. // all animation may be coming from a library skeleton, so may need to create animation
  87497. if (this.animations.length === 0) {
  87498. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  87499. this.animations[0].setKeys([]);
  87500. }
  87501. // get animation info / verify there is such a range from the source bone
  87502. var sourceRange = source.animations[0].getRange(rangeName);
  87503. if (!sourceRange) {
  87504. return false;
  87505. }
  87506. var from = sourceRange.from;
  87507. var to = sourceRange.to;
  87508. var sourceKeys = source.animations[0].getKeys();
  87509. // rescaling prep
  87510. var sourceBoneLength = source.length;
  87511. var sourceParent = source.getParent();
  87512. var parent = this.getParent();
  87513. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  87514. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  87515. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  87516. var destKeys = this.animations[0].getKeys();
  87517. // loop vars declaration
  87518. var orig;
  87519. var origTranslation;
  87520. var mat;
  87521. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  87522. orig = sourceKeys[key];
  87523. if (orig.frame >= from && orig.frame <= to) {
  87524. if (rescaleAsRequired) {
  87525. mat = orig.value.clone();
  87526. // scale based on parent ratio, when bone has parent
  87527. if (parentScalingReqd) {
  87528. origTranslation = mat.getTranslation();
  87529. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  87530. // scale based on skeleton dimension ratio when root bone, and value is passed
  87531. }
  87532. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  87533. origTranslation = mat.getTranslation();
  87534. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  87535. // use original when root bone, and no data for skelDimensionsRatio
  87536. }
  87537. else {
  87538. mat = orig.value;
  87539. }
  87540. }
  87541. else {
  87542. mat = orig.value;
  87543. }
  87544. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  87545. }
  87546. }
  87547. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  87548. return true;
  87549. };
  87550. /**
  87551. * Translate the bone in local or world space
  87552. * @param vec The amount to translate the bone
  87553. * @param space The space that the translation is in
  87554. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87555. */
  87556. Bone.prototype.translate = function (vec, space, mesh) {
  87557. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87558. var lm = this.getLocalMatrix();
  87559. if (space == BABYLON.Space.LOCAL) {
  87560. lm.m[12] += vec.x;
  87561. lm.m[13] += vec.y;
  87562. lm.m[14] += vec.z;
  87563. }
  87564. else {
  87565. var wm = null;
  87566. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87567. if (mesh) {
  87568. wm = mesh.getWorldMatrix();
  87569. }
  87570. this._skeleton.computeAbsoluteTransforms();
  87571. var tmat = Bone._tmpMats[0];
  87572. var tvec = Bone._tmpVecs[0];
  87573. if (this._parent) {
  87574. if (mesh && wm) {
  87575. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87576. tmat.multiplyToRef(wm, tmat);
  87577. }
  87578. else {
  87579. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87580. }
  87581. }
  87582. tmat.m[12] = 0;
  87583. tmat.m[13] = 0;
  87584. tmat.m[14] = 0;
  87585. tmat.invert();
  87586. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  87587. lm.m[12] += tvec.x;
  87588. lm.m[13] += tvec.y;
  87589. lm.m[14] += tvec.z;
  87590. }
  87591. this._markAsDirtyAndDecompose();
  87592. };
  87593. /**
  87594. * Set the postion of the bone in local or world space
  87595. * @param position The position to set the bone
  87596. * @param space The space that the position is in
  87597. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87598. */
  87599. Bone.prototype.setPosition = function (position, space, mesh) {
  87600. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87601. var lm = this.getLocalMatrix();
  87602. if (space == BABYLON.Space.LOCAL) {
  87603. lm.m[12] = position.x;
  87604. lm.m[13] = position.y;
  87605. lm.m[14] = position.z;
  87606. }
  87607. else {
  87608. var wm = null;
  87609. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87610. if (mesh) {
  87611. wm = mesh.getWorldMatrix();
  87612. }
  87613. this._skeleton.computeAbsoluteTransforms();
  87614. var tmat = Bone._tmpMats[0];
  87615. var vec = Bone._tmpVecs[0];
  87616. if (this._parent) {
  87617. if (mesh && wm) {
  87618. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87619. tmat.multiplyToRef(wm, tmat);
  87620. }
  87621. else {
  87622. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87623. }
  87624. }
  87625. tmat.invert();
  87626. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  87627. lm.m[12] = vec.x;
  87628. lm.m[13] = vec.y;
  87629. lm.m[14] = vec.z;
  87630. }
  87631. this._markAsDirtyAndDecompose();
  87632. };
  87633. /**
  87634. * Set the absolute position of the bone (world space)
  87635. * @param position The position to set the bone
  87636. * @param mesh The mesh that this bone is attached to
  87637. */
  87638. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  87639. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  87640. };
  87641. /**
  87642. * Scale the bone on the x, y and z axes (in local space)
  87643. * @param x The amount to scale the bone on the x axis
  87644. * @param y The amount to scale the bone on the y axis
  87645. * @param z The amount to scale the bone on the z axis
  87646. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  87647. */
  87648. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  87649. if (scaleChildren === void 0) { scaleChildren = false; }
  87650. var locMat = this.getLocalMatrix();
  87651. // Apply new scaling on top of current local matrix
  87652. var scaleMat = Bone._tmpMats[0];
  87653. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  87654. scaleMat.multiplyToRef(locMat, locMat);
  87655. // Invert scaling matrix and apply the inverse to all children
  87656. scaleMat.invert();
  87657. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  87658. var child = _a[_i];
  87659. var cm = child.getLocalMatrix();
  87660. cm.multiplyToRef(scaleMat, cm);
  87661. cm.m[12] *= x;
  87662. cm.m[13] *= y;
  87663. cm.m[14] *= z;
  87664. child._markAsDirtyAndDecompose();
  87665. }
  87666. this._markAsDirtyAndDecompose();
  87667. if (scaleChildren) {
  87668. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  87669. var child = _c[_b];
  87670. child.scale(x, y, z, scaleChildren);
  87671. }
  87672. }
  87673. };
  87674. /**
  87675. * Set the bone scaling in local space
  87676. * @param scale defines the scaling vector
  87677. */
  87678. Bone.prototype.setScale = function (scale) {
  87679. this._decompose();
  87680. this._localScaling.copyFrom(scale);
  87681. this._markAsDirtyAndCompose();
  87682. };
  87683. /**
  87684. * Gets the current scaling in local space
  87685. * @returns the current scaling vector
  87686. */
  87687. Bone.prototype.getScale = function () {
  87688. this._decompose();
  87689. return this._localScaling;
  87690. };
  87691. /**
  87692. * Gets the current scaling in local space and stores it in a target vector
  87693. * @param result defines the target vector
  87694. */
  87695. Bone.prototype.getScaleToRef = function (result) {
  87696. this._decompose();
  87697. result.copyFrom(this._localScaling);
  87698. };
  87699. /**
  87700. * Set the yaw, pitch, and roll of the bone in local or world space
  87701. * @param yaw The rotation of the bone on the y axis
  87702. * @param pitch The rotation of the bone on the x axis
  87703. * @param roll The rotation of the bone on the z axis
  87704. * @param space The space that the axes of rotation are in
  87705. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87706. */
  87707. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  87708. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87709. if (space === BABYLON.Space.LOCAL) {
  87710. var quat = Bone._tmpQuat;
  87711. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  87712. this.setRotationQuaternion(quat, space, mesh);
  87713. return;
  87714. }
  87715. var rotMatInv = Bone._tmpMats[0];
  87716. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87717. return;
  87718. }
  87719. var rotMat = Bone._tmpMats[1];
  87720. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  87721. rotMatInv.multiplyToRef(rotMat, rotMat);
  87722. this._rotateWithMatrix(rotMat, space, mesh);
  87723. };
  87724. /**
  87725. * Add a rotation to the bone on an axis in local or world space
  87726. * @param axis The axis to rotate the bone on
  87727. * @param amount The amount to rotate the bone
  87728. * @param space The space that the axis is in
  87729. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87730. */
  87731. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  87732. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87733. var rmat = Bone._tmpMats[0];
  87734. rmat.m[12] = 0;
  87735. rmat.m[13] = 0;
  87736. rmat.m[14] = 0;
  87737. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  87738. this._rotateWithMatrix(rmat, space, mesh);
  87739. };
  87740. /**
  87741. * Set the rotation of the bone to a particular axis angle in local or world space
  87742. * @param axis The axis to rotate the bone on
  87743. * @param angle The angle that the bone should be rotated to
  87744. * @param space The space that the axis is in
  87745. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87746. */
  87747. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  87748. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87749. if (space === BABYLON.Space.LOCAL) {
  87750. var quat = Bone._tmpQuat;
  87751. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  87752. this.setRotationQuaternion(quat, space, mesh);
  87753. return;
  87754. }
  87755. var rotMatInv = Bone._tmpMats[0];
  87756. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87757. return;
  87758. }
  87759. var rotMat = Bone._tmpMats[1];
  87760. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  87761. rotMatInv.multiplyToRef(rotMat, rotMat);
  87762. this._rotateWithMatrix(rotMat, space, mesh);
  87763. };
  87764. /**
  87765. * Set the euler rotation of the bone in local of world space
  87766. * @param rotation The euler rotation that the bone should be set to
  87767. * @param space The space that the rotation is in
  87768. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87769. */
  87770. Bone.prototype.setRotation = function (rotation, space, mesh) {
  87771. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87772. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  87773. };
  87774. /**
  87775. * Set the quaternion rotation of the bone in local of world space
  87776. * @param quat The quaternion rotation that the bone should be set to
  87777. * @param space The space that the rotation is in
  87778. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87779. */
  87780. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  87781. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87782. if (space === BABYLON.Space.LOCAL) {
  87783. this._decompose();
  87784. this._localRotation.copyFrom(quat);
  87785. this._markAsDirtyAndCompose();
  87786. return;
  87787. }
  87788. var rotMatInv = Bone._tmpMats[0];
  87789. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87790. return;
  87791. }
  87792. var rotMat = Bone._tmpMats[1];
  87793. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  87794. rotMatInv.multiplyToRef(rotMat, rotMat);
  87795. this._rotateWithMatrix(rotMat, space, mesh);
  87796. };
  87797. /**
  87798. * Set the rotation matrix of the bone in local of world space
  87799. * @param rotMat The rotation matrix that the bone should be set to
  87800. * @param space The space that the rotation is in
  87801. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87802. */
  87803. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  87804. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87805. if (space === BABYLON.Space.LOCAL) {
  87806. var quat = Bone._tmpQuat;
  87807. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  87808. this.setRotationQuaternion(quat, space, mesh);
  87809. return;
  87810. }
  87811. var rotMatInv = Bone._tmpMats[0];
  87812. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87813. return;
  87814. }
  87815. var rotMat2 = Bone._tmpMats[1];
  87816. rotMat2.copyFrom(rotMat);
  87817. rotMatInv.multiplyToRef(rotMat, rotMat2);
  87818. this._rotateWithMatrix(rotMat2, space, mesh);
  87819. };
  87820. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  87821. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87822. var lmat = this.getLocalMatrix();
  87823. var lx = lmat.m[12];
  87824. var ly = lmat.m[13];
  87825. var lz = lmat.m[14];
  87826. var parent = this.getParent();
  87827. var parentScale = Bone._tmpMats[3];
  87828. var parentScaleInv = Bone._tmpMats[4];
  87829. if (parent && space == BABYLON.Space.WORLD) {
  87830. if (mesh) {
  87831. parentScale.copyFrom(mesh.getWorldMatrix());
  87832. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  87833. }
  87834. else {
  87835. parentScale.copyFrom(parent.getAbsoluteTransform());
  87836. }
  87837. parentScaleInv.copyFrom(parentScale);
  87838. parentScaleInv.invert();
  87839. lmat.multiplyToRef(parentScale, lmat);
  87840. lmat.multiplyToRef(rmat, lmat);
  87841. lmat.multiplyToRef(parentScaleInv, lmat);
  87842. }
  87843. else {
  87844. if (space == BABYLON.Space.WORLD && mesh) {
  87845. parentScale.copyFrom(mesh.getWorldMatrix());
  87846. parentScaleInv.copyFrom(parentScale);
  87847. parentScaleInv.invert();
  87848. lmat.multiplyToRef(parentScale, lmat);
  87849. lmat.multiplyToRef(rmat, lmat);
  87850. lmat.multiplyToRef(parentScaleInv, lmat);
  87851. }
  87852. else {
  87853. lmat.multiplyToRef(rmat, lmat);
  87854. }
  87855. }
  87856. lmat.m[12] = lx;
  87857. lmat.m[13] = ly;
  87858. lmat.m[14] = lz;
  87859. this.computeAbsoluteTransforms();
  87860. this._markAsDirtyAndDecompose();
  87861. };
  87862. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  87863. var scaleMatrix = Bone._tmpMats[2];
  87864. rotMatInv.copyFrom(this.getAbsoluteTransform());
  87865. if (mesh) {
  87866. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  87867. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  87868. }
  87869. rotMatInv.invert();
  87870. if (isNaN(rotMatInv.m[0])) {
  87871. // Matrix failed to invert.
  87872. // This can happen if scale is zero for example.
  87873. return false;
  87874. }
  87875. scaleMatrix.m[0] *= this._scalingDeterminant;
  87876. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  87877. return true;
  87878. };
  87879. /**
  87880. * Get the position of the bone in local or world space
  87881. * @param space The space that the returned position is in
  87882. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87883. * @returns The position of the bone
  87884. */
  87885. Bone.prototype.getPosition = function (space, mesh) {
  87886. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87887. if (mesh === void 0) { mesh = null; }
  87888. var pos = BABYLON.Vector3.Zero();
  87889. this.getPositionToRef(space, mesh, pos);
  87890. return pos;
  87891. };
  87892. /**
  87893. * Copy the position of the bone to a vector3 in local or world space
  87894. * @param space The space that the returned position is in
  87895. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87896. * @param result The vector3 to copy the position to
  87897. */
  87898. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  87899. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87900. if (space == BABYLON.Space.LOCAL) {
  87901. var lm = this.getLocalMatrix();
  87902. result.x = lm.m[12];
  87903. result.y = lm.m[13];
  87904. result.z = lm.m[14];
  87905. }
  87906. else {
  87907. var wm = null;
  87908. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87909. if (mesh) {
  87910. wm = mesh.getWorldMatrix();
  87911. }
  87912. this._skeleton.computeAbsoluteTransforms();
  87913. var tmat = Bone._tmpMats[0];
  87914. if (mesh && wm) {
  87915. tmat.copyFrom(this.getAbsoluteTransform());
  87916. tmat.multiplyToRef(wm, tmat);
  87917. }
  87918. else {
  87919. tmat = this.getAbsoluteTransform();
  87920. }
  87921. result.x = tmat.m[12];
  87922. result.y = tmat.m[13];
  87923. result.z = tmat.m[14];
  87924. }
  87925. };
  87926. /**
  87927. * Get the absolute position of the bone (world space)
  87928. * @param mesh The mesh that this bone is attached to
  87929. * @returns The absolute position of the bone
  87930. */
  87931. Bone.prototype.getAbsolutePosition = function (mesh) {
  87932. if (mesh === void 0) { mesh = null; }
  87933. var pos = BABYLON.Vector3.Zero();
  87934. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  87935. return pos;
  87936. };
  87937. /**
  87938. * Copy the absolute position of the bone (world space) to the result param
  87939. * @param mesh The mesh that this bone is attached to
  87940. * @param result The vector3 to copy the absolute position to
  87941. */
  87942. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  87943. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  87944. };
  87945. /**
  87946. * Compute the absolute transforms of this bone and its children
  87947. */
  87948. Bone.prototype.computeAbsoluteTransforms = function () {
  87949. this._compose();
  87950. if (this._parent) {
  87951. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  87952. }
  87953. else {
  87954. this._absoluteTransform.copyFrom(this._localMatrix);
  87955. var poseMatrix = this._skeleton.getPoseMatrix();
  87956. if (poseMatrix) {
  87957. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  87958. }
  87959. }
  87960. var children = this.children;
  87961. var len = children.length;
  87962. for (var i = 0; i < len; i++) {
  87963. children[i].computeAbsoluteTransforms();
  87964. }
  87965. };
  87966. /**
  87967. * Get the world direction from an axis that is in the local space of the bone
  87968. * @param localAxis The local direction that is used to compute the world direction
  87969. * @param mesh The mesh that this bone is attached to
  87970. * @returns The world direction
  87971. */
  87972. Bone.prototype.getDirection = function (localAxis, mesh) {
  87973. if (mesh === void 0) { mesh = null; }
  87974. var result = BABYLON.Vector3.Zero();
  87975. this.getDirectionToRef(localAxis, mesh, result);
  87976. return result;
  87977. };
  87978. /**
  87979. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  87980. * @param localAxis The local direction that is used to compute the world direction
  87981. * @param mesh The mesh that this bone is attached to
  87982. * @param result The vector3 that the world direction will be copied to
  87983. */
  87984. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  87985. if (mesh === void 0) { mesh = null; }
  87986. var wm = null;
  87987. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87988. if (mesh) {
  87989. wm = mesh.getWorldMatrix();
  87990. }
  87991. this._skeleton.computeAbsoluteTransforms();
  87992. var mat = Bone._tmpMats[0];
  87993. mat.copyFrom(this.getAbsoluteTransform());
  87994. if (mesh && wm) {
  87995. mat.multiplyToRef(wm, mat);
  87996. }
  87997. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  87998. result.normalize();
  87999. };
  88000. /**
  88001. * Get the euler rotation of the bone in local or world space
  88002. * @param space The space that the rotation should be in
  88003. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88004. * @returns The euler rotation
  88005. */
  88006. Bone.prototype.getRotation = function (space, mesh) {
  88007. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88008. if (mesh === void 0) { mesh = null; }
  88009. var result = BABYLON.Vector3.Zero();
  88010. this.getRotationToRef(space, mesh, result);
  88011. return result;
  88012. };
  88013. /**
  88014. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  88015. * @param space The space that the rotation should be in
  88016. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88017. * @param result The vector3 that the rotation should be copied to
  88018. */
  88019. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  88020. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88021. if (mesh === void 0) { mesh = null; }
  88022. var quat = Bone._tmpQuat;
  88023. this.getRotationQuaternionToRef(space, mesh, quat);
  88024. quat.toEulerAnglesToRef(result);
  88025. };
  88026. /**
  88027. * Get the quaternion rotation of the bone in either local or world space
  88028. * @param space The space that the rotation should be in
  88029. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88030. * @returns The quaternion rotation
  88031. */
  88032. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  88033. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88034. if (mesh === void 0) { mesh = null; }
  88035. var result = BABYLON.Quaternion.Identity();
  88036. this.getRotationQuaternionToRef(space, mesh, result);
  88037. return result;
  88038. };
  88039. /**
  88040. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  88041. * @param space The space that the rotation should be in
  88042. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88043. * @param result The quaternion that the rotation should be copied to
  88044. */
  88045. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  88046. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88047. if (mesh === void 0) { mesh = null; }
  88048. if (space == BABYLON.Space.LOCAL) {
  88049. this._decompose();
  88050. result.copyFrom(this._localRotation);
  88051. }
  88052. else {
  88053. var mat = Bone._tmpMats[0];
  88054. var amat = this.getAbsoluteTransform();
  88055. if (mesh) {
  88056. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  88057. }
  88058. else {
  88059. mat.copyFrom(amat);
  88060. }
  88061. mat.m[0] *= this._scalingDeterminant;
  88062. mat.m[1] *= this._scalingDeterminant;
  88063. mat.m[2] *= this._scalingDeterminant;
  88064. mat.decompose(undefined, result, undefined);
  88065. }
  88066. };
  88067. /**
  88068. * Get the rotation matrix of the bone in local or world space
  88069. * @param space The space that the rotation should be in
  88070. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88071. * @returns The rotation matrix
  88072. */
  88073. Bone.prototype.getRotationMatrix = function (space, mesh) {
  88074. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88075. var result = BABYLON.Matrix.Identity();
  88076. this.getRotationMatrixToRef(space, mesh, result);
  88077. return result;
  88078. };
  88079. /**
  88080. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  88081. * @param space The space that the rotation should be in
  88082. * @param mesh The mesh that this bone is attached to. This is only used in world space
  88083. * @param result The quaternion that the rotation should be copied to
  88084. */
  88085. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  88086. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  88087. if (space == BABYLON.Space.LOCAL) {
  88088. this.getLocalMatrix().getRotationMatrixToRef(result);
  88089. }
  88090. else {
  88091. var mat = Bone._tmpMats[0];
  88092. var amat = this.getAbsoluteTransform();
  88093. if (mesh) {
  88094. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  88095. }
  88096. else {
  88097. mat.copyFrom(amat);
  88098. }
  88099. mat.m[0] *= this._scalingDeterminant;
  88100. mat.m[1] *= this._scalingDeterminant;
  88101. mat.m[2] *= this._scalingDeterminant;
  88102. mat.getRotationMatrixToRef(result);
  88103. }
  88104. };
  88105. /**
  88106. * Get the world position of a point that is in the local space of the bone
  88107. * @param position The local position
  88108. * @param mesh The mesh that this bone is attached to
  88109. * @returns The world position
  88110. */
  88111. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  88112. if (mesh === void 0) { mesh = null; }
  88113. var result = BABYLON.Vector3.Zero();
  88114. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  88115. return result;
  88116. };
  88117. /**
  88118. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  88119. * @param position The local position
  88120. * @param mesh The mesh that this bone is attached to
  88121. * @param result The vector3 that the world position should be copied to
  88122. */
  88123. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  88124. if (mesh === void 0) { mesh = null; }
  88125. var wm = null;
  88126. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  88127. if (mesh) {
  88128. wm = mesh.getWorldMatrix();
  88129. }
  88130. this._skeleton.computeAbsoluteTransforms();
  88131. var tmat = Bone._tmpMats[0];
  88132. if (mesh && wm) {
  88133. tmat.copyFrom(this.getAbsoluteTransform());
  88134. tmat.multiplyToRef(wm, tmat);
  88135. }
  88136. else {
  88137. tmat = this.getAbsoluteTransform();
  88138. }
  88139. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  88140. };
  88141. /**
  88142. * Get the local position of a point that is in world space
  88143. * @param position The world position
  88144. * @param mesh The mesh that this bone is attached to
  88145. * @returns The local position
  88146. */
  88147. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  88148. if (mesh === void 0) { mesh = null; }
  88149. var result = BABYLON.Vector3.Zero();
  88150. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  88151. return result;
  88152. };
  88153. /**
  88154. * Get the local position of a point that is in world space and copy it to the result param
  88155. * @param position The world position
  88156. * @param mesh The mesh that this bone is attached to
  88157. * @param result The vector3 that the local position should be copied to
  88158. */
  88159. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  88160. if (mesh === void 0) { mesh = null; }
  88161. var wm = null;
  88162. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  88163. if (mesh) {
  88164. wm = mesh.getWorldMatrix();
  88165. }
  88166. this._skeleton.computeAbsoluteTransforms();
  88167. var tmat = Bone._tmpMats[0];
  88168. tmat.copyFrom(this.getAbsoluteTransform());
  88169. if (mesh && wm) {
  88170. tmat.multiplyToRef(wm, tmat);
  88171. }
  88172. tmat.invert();
  88173. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  88174. };
  88175. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88176. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  88177. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  88178. return Bone;
  88179. }(BABYLON.Node));
  88180. BABYLON.Bone = Bone;
  88181. })(BABYLON || (BABYLON = {}));
  88182. //# sourceMappingURL=babylon.bone.js.map
  88183. var BABYLON;
  88184. (function (BABYLON) {
  88185. /**
  88186. * Class used to apply inverse kinematics to bones
  88187. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  88188. */
  88189. var BoneIKController = /** @class */ (function () {
  88190. /**
  88191. * Creates a new BoneIKController
  88192. * @param mesh defines the mesh to control
  88193. * @param bone defines the bone to control
  88194. * @param options defines options to set up the controller
  88195. */
  88196. function BoneIKController(mesh, bone, options) {
  88197. /**
  88198. * Gets or sets the target position
  88199. */
  88200. this.targetPosition = BABYLON.Vector3.Zero();
  88201. /**
  88202. * Gets or sets the pole target position
  88203. */
  88204. this.poleTargetPosition = BABYLON.Vector3.Zero();
  88205. /**
  88206. * Gets or sets the pole target local offset
  88207. */
  88208. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  88209. /**
  88210. * Gets or sets the pole angle
  88211. */
  88212. this.poleAngle = 0;
  88213. /**
  88214. * 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)
  88215. */
  88216. this.slerpAmount = 1;
  88217. this._bone1Quat = BABYLON.Quaternion.Identity();
  88218. this._bone1Mat = BABYLON.Matrix.Identity();
  88219. this._bone2Ang = Math.PI;
  88220. this._maxAngle = Math.PI;
  88221. this._rightHandedSystem = false;
  88222. this._bendAxis = BABYLON.Vector3.Right();
  88223. this._slerping = false;
  88224. this._adjustRoll = 0;
  88225. this._bone2 = bone;
  88226. this._bone1 = bone.getParent();
  88227. if (!this._bone1) {
  88228. return;
  88229. }
  88230. this.mesh = mesh;
  88231. var bonePos = bone.getPosition();
  88232. if (bone.getAbsoluteTransform().determinant() > 0) {
  88233. this._rightHandedSystem = true;
  88234. this._bendAxis.x = 0;
  88235. this._bendAxis.y = 0;
  88236. this._bendAxis.z = -1;
  88237. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  88238. this._adjustRoll = Math.PI * .5;
  88239. this._bendAxis.z = 1;
  88240. }
  88241. }
  88242. if (this._bone1.length) {
  88243. var boneScale1 = this._bone1.getScale();
  88244. var boneScale2 = this._bone2.getScale();
  88245. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  88246. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  88247. }
  88248. else if (this._bone1.children[0]) {
  88249. mesh.computeWorldMatrix(true);
  88250. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  88251. var pos2 = this._bone2.getAbsolutePosition(mesh);
  88252. var pos3 = this._bone1.getAbsolutePosition(mesh);
  88253. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  88254. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  88255. }
  88256. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  88257. this.maxAngle = Math.PI;
  88258. if (options) {
  88259. if (options.targetMesh) {
  88260. this.targetMesh = options.targetMesh;
  88261. this.targetMesh.computeWorldMatrix(true);
  88262. }
  88263. if (options.poleTargetMesh) {
  88264. this.poleTargetMesh = options.poleTargetMesh;
  88265. this.poleTargetMesh.computeWorldMatrix(true);
  88266. }
  88267. else if (options.poleTargetBone) {
  88268. this.poleTargetBone = options.poleTargetBone;
  88269. }
  88270. else if (this._bone1.getParent()) {
  88271. this.poleTargetBone = this._bone1.getParent();
  88272. }
  88273. if (options.poleTargetLocalOffset) {
  88274. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  88275. }
  88276. if (options.poleAngle) {
  88277. this.poleAngle = options.poleAngle;
  88278. }
  88279. if (options.bendAxis) {
  88280. this._bendAxis.copyFrom(options.bendAxis);
  88281. }
  88282. if (options.maxAngle) {
  88283. this.maxAngle = options.maxAngle;
  88284. }
  88285. if (options.slerpAmount) {
  88286. this.slerpAmount = options.slerpAmount;
  88287. }
  88288. }
  88289. }
  88290. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  88291. /**
  88292. * Gets or sets maximum allowed angle
  88293. */
  88294. get: function () {
  88295. return this._maxAngle;
  88296. },
  88297. set: function (value) {
  88298. this._setMaxAngle(value);
  88299. },
  88300. enumerable: true,
  88301. configurable: true
  88302. });
  88303. BoneIKController.prototype._setMaxAngle = function (ang) {
  88304. if (ang < 0) {
  88305. ang = 0;
  88306. }
  88307. if (ang > Math.PI || ang == undefined) {
  88308. ang = Math.PI;
  88309. }
  88310. this._maxAngle = ang;
  88311. var a = this._bone1Length;
  88312. var b = this._bone2Length;
  88313. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  88314. };
  88315. /**
  88316. * Force the controller to update the bones
  88317. */
  88318. BoneIKController.prototype.update = function () {
  88319. var bone1 = this._bone1;
  88320. if (!bone1) {
  88321. return;
  88322. }
  88323. var target = this.targetPosition;
  88324. var poleTarget = this.poleTargetPosition;
  88325. var mat1 = BoneIKController._tmpMats[0];
  88326. var mat2 = BoneIKController._tmpMats[1];
  88327. if (this.targetMesh) {
  88328. target.copyFrom(this.targetMesh.getAbsolutePosition());
  88329. }
  88330. if (this.poleTargetBone) {
  88331. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  88332. }
  88333. else if (this.poleTargetMesh) {
  88334. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  88335. }
  88336. var bonePos = BoneIKController._tmpVecs[0];
  88337. var zaxis = BoneIKController._tmpVecs[1];
  88338. var xaxis = BoneIKController._tmpVecs[2];
  88339. var yaxis = BoneIKController._tmpVecs[3];
  88340. var upAxis = BoneIKController._tmpVecs[4];
  88341. var _tmpQuat = BoneIKController._tmpQuat;
  88342. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  88343. poleTarget.subtractToRef(bonePos, upAxis);
  88344. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  88345. upAxis.y = 1;
  88346. }
  88347. else {
  88348. upAxis.normalize();
  88349. }
  88350. target.subtractToRef(bonePos, yaxis);
  88351. yaxis.normalize();
  88352. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  88353. zaxis.normalize();
  88354. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  88355. xaxis.normalize();
  88356. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  88357. var a = this._bone1Length;
  88358. var b = this._bone2Length;
  88359. var c = BABYLON.Vector3.Distance(bonePos, target);
  88360. if (this._maxReach > 0) {
  88361. c = Math.min(this._maxReach, c);
  88362. }
  88363. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  88364. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  88365. if (acosa > 1) {
  88366. acosa = 1;
  88367. }
  88368. if (acosb > 1) {
  88369. acosb = 1;
  88370. }
  88371. if (acosa < -1) {
  88372. acosa = -1;
  88373. }
  88374. if (acosb < -1) {
  88375. acosb = -1;
  88376. }
  88377. var angA = Math.acos(acosa);
  88378. var angB = Math.acos(acosb);
  88379. var angC = -angA - angB;
  88380. if (this._rightHandedSystem) {
  88381. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  88382. mat2.multiplyToRef(mat1, mat1);
  88383. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  88384. mat2.multiplyToRef(mat1, mat1);
  88385. }
  88386. else {
  88387. var _tmpVec = BoneIKController._tmpVecs[5];
  88388. _tmpVec.copyFrom(this._bendAxis);
  88389. _tmpVec.x *= -1;
  88390. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  88391. mat2.multiplyToRef(mat1, mat1);
  88392. }
  88393. if (this.poleAngle) {
  88394. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  88395. mat1.multiplyToRef(mat2, mat1);
  88396. }
  88397. if (this._bone1) {
  88398. if (this.slerpAmount < 1) {
  88399. if (!this._slerping) {
  88400. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  88401. }
  88402. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  88403. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  88404. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  88405. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  88406. this._slerping = true;
  88407. }
  88408. else {
  88409. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  88410. this._bone1Mat.copyFrom(mat1);
  88411. this._slerping = false;
  88412. }
  88413. }
  88414. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  88415. this._bone2Ang = angC;
  88416. };
  88417. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88418. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  88419. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  88420. return BoneIKController;
  88421. }());
  88422. BABYLON.BoneIKController = BoneIKController;
  88423. })(BABYLON || (BABYLON = {}));
  88424. //# sourceMappingURL=babylon.boneIKController.js.map
  88425. var BABYLON;
  88426. (function (BABYLON) {
  88427. /**
  88428. * Class used to make a bone look toward a point in space
  88429. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  88430. */
  88431. var BoneLookController = /** @class */ (function () {
  88432. /**
  88433. * Create a BoneLookController
  88434. * @param mesh the mesh that the bone belongs to
  88435. * @param bone the bone that will be looking to the target
  88436. * @param target the target Vector3 to look at
  88437. * @param settings optional settings:
  88438. * * maxYaw: the maximum angle the bone will yaw to
  88439. * * minYaw: the minimum angle the bone will yaw to
  88440. * * maxPitch: the maximum angle the bone will pitch to
  88441. * * minPitch: the minimum angle the bone will yaw to
  88442. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  88443. * * upAxis: the up axis of the coordinate system
  88444. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  88445. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  88446. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  88447. * * adjustYaw: used to make an adjustment to the yaw of the bone
  88448. * * adjustPitch: used to make an adjustment to the pitch of the bone
  88449. * * adjustRoll: used to make an adjustment to the roll of the bone
  88450. **/
  88451. function BoneLookController(mesh, bone, target, options) {
  88452. /**
  88453. * The up axis of the coordinate system that is used when the bone is rotated
  88454. */
  88455. this.upAxis = BABYLON.Vector3.Up();
  88456. /**
  88457. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  88458. */
  88459. this.upAxisSpace = BABYLON.Space.LOCAL;
  88460. /**
  88461. * Used to make an adjustment to the yaw of the bone
  88462. */
  88463. this.adjustYaw = 0;
  88464. /**
  88465. * Used to make an adjustment to the pitch of the bone
  88466. */
  88467. this.adjustPitch = 0;
  88468. /**
  88469. * Used to make an adjustment to the roll of the bone
  88470. */
  88471. this.adjustRoll = 0;
  88472. /**
  88473. * 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)
  88474. */
  88475. this.slerpAmount = 1;
  88476. this._boneQuat = BABYLON.Quaternion.Identity();
  88477. this._slerping = false;
  88478. this._firstFrameSkipped = false;
  88479. this._fowardAxis = BABYLON.Vector3.Forward();
  88480. this.mesh = mesh;
  88481. this.bone = bone;
  88482. this.target = target;
  88483. if (options) {
  88484. if (options.adjustYaw) {
  88485. this.adjustYaw = options.adjustYaw;
  88486. }
  88487. if (options.adjustPitch) {
  88488. this.adjustPitch = options.adjustPitch;
  88489. }
  88490. if (options.adjustRoll) {
  88491. this.adjustRoll = options.adjustRoll;
  88492. }
  88493. if (options.maxYaw != null) {
  88494. this.maxYaw = options.maxYaw;
  88495. }
  88496. else {
  88497. this.maxYaw = Math.PI;
  88498. }
  88499. if (options.minYaw != null) {
  88500. this.minYaw = options.minYaw;
  88501. }
  88502. else {
  88503. this.minYaw = -Math.PI;
  88504. }
  88505. if (options.maxPitch != null) {
  88506. this.maxPitch = options.maxPitch;
  88507. }
  88508. else {
  88509. this.maxPitch = Math.PI;
  88510. }
  88511. if (options.minPitch != null) {
  88512. this.minPitch = options.minPitch;
  88513. }
  88514. else {
  88515. this.minPitch = -Math.PI;
  88516. }
  88517. if (options.slerpAmount != null) {
  88518. this.slerpAmount = options.slerpAmount;
  88519. }
  88520. if (options.upAxis != null) {
  88521. this.upAxis = options.upAxis;
  88522. }
  88523. if (options.upAxisSpace != null) {
  88524. this.upAxisSpace = options.upAxisSpace;
  88525. }
  88526. if (options.yawAxis != null || options.pitchAxis != null) {
  88527. var newYawAxis = BABYLON.Axis.Y;
  88528. var newPitchAxis = BABYLON.Axis.X;
  88529. if (options.yawAxis != null) {
  88530. newYawAxis = options.yawAxis.clone();
  88531. newYawAxis.normalize();
  88532. }
  88533. if (options.pitchAxis != null) {
  88534. newPitchAxis = options.pitchAxis.clone();
  88535. newPitchAxis.normalize();
  88536. }
  88537. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  88538. this._transformYawPitch = BABYLON.Matrix.Identity();
  88539. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  88540. this._transformYawPitchInv = this._transformYawPitch.clone();
  88541. this._transformYawPitch.invert();
  88542. }
  88543. }
  88544. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  88545. this.upAxisSpace = BABYLON.Space.LOCAL;
  88546. }
  88547. }
  88548. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  88549. /**
  88550. * Gets or sets the minimum yaw angle that the bone can look to
  88551. */
  88552. get: function () {
  88553. return this._minYaw;
  88554. },
  88555. set: function (value) {
  88556. this._minYaw = value;
  88557. this._minYawSin = Math.sin(value);
  88558. this._minYawCos = Math.cos(value);
  88559. if (this._maxYaw != null) {
  88560. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  88561. this._yawRange = this._maxYaw - this._minYaw;
  88562. }
  88563. },
  88564. enumerable: true,
  88565. configurable: true
  88566. });
  88567. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  88568. /**
  88569. * Gets or sets the maximum yaw angle that the bone can look to
  88570. */
  88571. get: function () {
  88572. return this._maxYaw;
  88573. },
  88574. set: function (value) {
  88575. this._maxYaw = value;
  88576. this._maxYawSin = Math.sin(value);
  88577. this._maxYawCos = Math.cos(value);
  88578. if (this._minYaw != null) {
  88579. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  88580. this._yawRange = this._maxYaw - this._minYaw;
  88581. }
  88582. },
  88583. enumerable: true,
  88584. configurable: true
  88585. });
  88586. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  88587. /**
  88588. * Gets or sets the minimum pitch angle that the bone can look to
  88589. */
  88590. get: function () {
  88591. return this._minPitch;
  88592. },
  88593. set: function (value) {
  88594. this._minPitch = value;
  88595. this._minPitchTan = Math.tan(value);
  88596. },
  88597. enumerable: true,
  88598. configurable: true
  88599. });
  88600. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  88601. /**
  88602. * Gets or sets the maximum pitch angle that the bone can look to
  88603. */
  88604. get: function () {
  88605. return this._maxPitch;
  88606. },
  88607. set: function (value) {
  88608. this._maxPitch = value;
  88609. this._maxPitchTan = Math.tan(value);
  88610. },
  88611. enumerable: true,
  88612. configurable: true
  88613. });
  88614. /**
  88615. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  88616. */
  88617. BoneLookController.prototype.update = function () {
  88618. //skip the first frame when slerping so that the mesh rotation is correct
  88619. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  88620. this._firstFrameSkipped = true;
  88621. return;
  88622. }
  88623. var bone = this.bone;
  88624. var bonePos = BoneLookController._tmpVecs[0];
  88625. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  88626. var target = this.target;
  88627. var _tmpMat1 = BoneLookController._tmpMats[0];
  88628. var _tmpMat2 = BoneLookController._tmpMats[1];
  88629. var mesh = this.mesh;
  88630. var parentBone = bone.getParent();
  88631. var upAxis = BoneLookController._tmpVecs[1];
  88632. upAxis.copyFrom(this.upAxis);
  88633. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  88634. if (this._transformYawPitch) {
  88635. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  88636. }
  88637. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  88638. }
  88639. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  88640. mesh.getDirectionToRef(upAxis, upAxis);
  88641. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  88642. upAxis.normalize();
  88643. }
  88644. }
  88645. var checkYaw = false;
  88646. var checkPitch = false;
  88647. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  88648. checkYaw = true;
  88649. }
  88650. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  88651. checkPitch = true;
  88652. }
  88653. if (checkYaw || checkPitch) {
  88654. var spaceMat = BoneLookController._tmpMats[2];
  88655. var spaceMatInv = BoneLookController._tmpMats[3];
  88656. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  88657. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  88658. }
  88659. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  88660. spaceMat.copyFrom(mesh.getWorldMatrix());
  88661. }
  88662. else {
  88663. var forwardAxis = BoneLookController._tmpVecs[2];
  88664. forwardAxis.copyFrom(this._fowardAxis);
  88665. if (this._transformYawPitch) {
  88666. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  88667. }
  88668. if (parentBone) {
  88669. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  88670. }
  88671. else {
  88672. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  88673. }
  88674. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  88675. rightAxis.normalize();
  88676. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  88677. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  88678. }
  88679. spaceMat.invertToRef(spaceMatInv);
  88680. var xzlen = null;
  88681. if (checkPitch) {
  88682. var localTarget = BoneLookController._tmpVecs[3];
  88683. target.subtractToRef(bonePos, localTarget);
  88684. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  88685. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  88686. var pitch = Math.atan2(localTarget.y, xzlen);
  88687. var newPitch = pitch;
  88688. if (pitch > this._maxPitch) {
  88689. localTarget.y = this._maxPitchTan * xzlen;
  88690. newPitch = this._maxPitch;
  88691. }
  88692. else if (pitch < this._minPitch) {
  88693. localTarget.y = this._minPitchTan * xzlen;
  88694. newPitch = this._minPitch;
  88695. }
  88696. if (pitch != newPitch) {
  88697. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  88698. localTarget.addInPlace(bonePos);
  88699. target = localTarget;
  88700. }
  88701. }
  88702. if (checkYaw) {
  88703. var localTarget = BoneLookController._tmpVecs[4];
  88704. target.subtractToRef(bonePos, localTarget);
  88705. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  88706. var yaw = Math.atan2(localTarget.x, localTarget.z);
  88707. var newYaw = yaw;
  88708. if (yaw > this._maxYaw || yaw < this._minYaw) {
  88709. if (xzlen == null) {
  88710. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  88711. }
  88712. if (this._yawRange > Math.PI) {
  88713. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  88714. localTarget.z = this._maxYawCos * xzlen;
  88715. localTarget.x = this._maxYawSin * xzlen;
  88716. newYaw = this._maxYaw;
  88717. }
  88718. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  88719. localTarget.z = this._minYawCos * xzlen;
  88720. localTarget.x = this._minYawSin * xzlen;
  88721. newYaw = this._minYaw;
  88722. }
  88723. }
  88724. else {
  88725. if (yaw > this._maxYaw) {
  88726. localTarget.z = this._maxYawCos * xzlen;
  88727. localTarget.x = this._maxYawSin * xzlen;
  88728. newYaw = this._maxYaw;
  88729. }
  88730. else if (yaw < this._minYaw) {
  88731. localTarget.z = this._minYawCos * xzlen;
  88732. localTarget.x = this._minYawSin * xzlen;
  88733. newYaw = this._minYaw;
  88734. }
  88735. }
  88736. }
  88737. if (this._slerping && this._yawRange > Math.PI) {
  88738. //are we going to be crossing into the min/max region?
  88739. var boneFwd = BoneLookController._tmpVecs[8];
  88740. boneFwd.copyFrom(BABYLON.Axis.Z);
  88741. if (this._transformYawPitch) {
  88742. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  88743. }
  88744. var boneRotMat = BoneLookController._tmpMats[4];
  88745. this._boneQuat.toRotationMatrix(boneRotMat);
  88746. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  88747. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  88748. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  88749. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  88750. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  88751. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  88752. if (angBtwTar > angBtwMidYaw) {
  88753. if (xzlen == null) {
  88754. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  88755. }
  88756. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  88757. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  88758. if (angBtwMin < angBtwMax) {
  88759. newYaw = boneYaw + Math.PI * .75;
  88760. localTarget.z = Math.cos(newYaw) * xzlen;
  88761. localTarget.x = Math.sin(newYaw) * xzlen;
  88762. }
  88763. else {
  88764. newYaw = boneYaw - Math.PI * .75;
  88765. localTarget.z = Math.cos(newYaw) * xzlen;
  88766. localTarget.x = Math.sin(newYaw) * xzlen;
  88767. }
  88768. }
  88769. }
  88770. if (yaw != newYaw) {
  88771. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  88772. localTarget.addInPlace(bonePos);
  88773. target = localTarget;
  88774. }
  88775. }
  88776. }
  88777. var zaxis = BoneLookController._tmpVecs[5];
  88778. var xaxis = BoneLookController._tmpVecs[6];
  88779. var yaxis = BoneLookController._tmpVecs[7];
  88780. var _tmpQuat = BoneLookController._tmpQuat;
  88781. target.subtractToRef(bonePos, zaxis);
  88782. zaxis.normalize();
  88783. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  88784. xaxis.normalize();
  88785. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  88786. yaxis.normalize();
  88787. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  88788. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  88789. return;
  88790. }
  88791. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  88792. return;
  88793. }
  88794. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  88795. return;
  88796. }
  88797. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  88798. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  88799. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  88800. }
  88801. if (this.slerpAmount < 1) {
  88802. if (!this._slerping) {
  88803. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  88804. }
  88805. if (this._transformYawPitch) {
  88806. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  88807. }
  88808. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  88809. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  88810. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  88811. this._slerping = true;
  88812. }
  88813. else {
  88814. if (this._transformYawPitch) {
  88815. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  88816. }
  88817. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  88818. this._slerping = false;
  88819. }
  88820. };
  88821. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  88822. var angDiff = ang2 - ang1;
  88823. angDiff %= Math.PI * 2;
  88824. if (angDiff > Math.PI) {
  88825. angDiff -= Math.PI * 2;
  88826. }
  88827. else if (angDiff < -Math.PI) {
  88828. angDiff += Math.PI * 2;
  88829. }
  88830. return angDiff;
  88831. };
  88832. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  88833. ang1 %= (2 * Math.PI);
  88834. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  88835. ang2 %= (2 * Math.PI);
  88836. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  88837. var ab = 0;
  88838. if (ang1 < ang2) {
  88839. ab = ang2 - ang1;
  88840. }
  88841. else {
  88842. ab = ang1 - ang2;
  88843. }
  88844. if (ab > Math.PI) {
  88845. ab = Math.PI * 2 - ab;
  88846. }
  88847. return ab;
  88848. };
  88849. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  88850. ang %= (2 * Math.PI);
  88851. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  88852. ang1 %= (2 * Math.PI);
  88853. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  88854. ang2 %= (2 * Math.PI);
  88855. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  88856. if (ang1 < ang2) {
  88857. if (ang > ang1 && ang < ang2) {
  88858. return true;
  88859. }
  88860. }
  88861. else {
  88862. if (ang > ang2 && ang < ang1) {
  88863. return true;
  88864. }
  88865. }
  88866. return false;
  88867. };
  88868. BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88869. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  88870. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  88871. return BoneLookController;
  88872. }());
  88873. BABYLON.BoneLookController = BoneLookController;
  88874. })(BABYLON || (BABYLON = {}));
  88875. //# sourceMappingURL=babylon.boneLookController.js.map
  88876. var BABYLON;
  88877. (function (BABYLON) {
  88878. /**
  88879. * Class used to handle skinning animations
  88880. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  88881. */
  88882. var Skeleton = /** @class */ (function () {
  88883. /**
  88884. * Creates a new skeleton
  88885. * @param name defines the skeleton name
  88886. * @param id defines the skeleton Id
  88887. * @param scene defines the hosting scene
  88888. */
  88889. function Skeleton(
  88890. /** defines the skeleton name */
  88891. name,
  88892. /** defines the skeleton Id */
  88893. id, scene) {
  88894. this.name = name;
  88895. this.id = id;
  88896. /**
  88897. * Gets the list of child bones
  88898. */
  88899. this.bones = new Array();
  88900. /**
  88901. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  88902. */
  88903. this.needInitialSkinMatrix = false;
  88904. this._isDirty = true;
  88905. this._meshesWithPoseMatrix = new Array();
  88906. this._identity = BABYLON.Matrix.Identity();
  88907. this._ranges = {};
  88908. this._lastAbsoluteTransformsUpdateId = -1;
  88909. /**
  88910. * Specifies if the skeleton should be serialized
  88911. */
  88912. this.doNotSerialize = false;
  88913. this._animationPropertiesOverride = null;
  88914. // Events
  88915. /**
  88916. * An observable triggered before computing the skeleton's matrices
  88917. */
  88918. this.onBeforeComputeObservable = new BABYLON.Observable();
  88919. this.bones = [];
  88920. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88921. scene.skeletons.push(this);
  88922. //make sure it will recalculate the matrix next time prepare is called.
  88923. this._isDirty = true;
  88924. }
  88925. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  88926. /**
  88927. * Gets or sets the animation properties override
  88928. */
  88929. get: function () {
  88930. if (!this._animationPropertiesOverride) {
  88931. return this._scene.animationPropertiesOverride;
  88932. }
  88933. return this._animationPropertiesOverride;
  88934. },
  88935. set: function (value) {
  88936. this._animationPropertiesOverride = value;
  88937. },
  88938. enumerable: true,
  88939. configurable: true
  88940. });
  88941. // Members
  88942. /**
  88943. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  88944. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  88945. * @returns a Float32Array containing matrices data
  88946. */
  88947. Skeleton.prototype.getTransformMatrices = function (mesh) {
  88948. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  88949. return mesh._bonesTransformMatrices;
  88950. }
  88951. if (!this._transformMatrices) {
  88952. this.prepare();
  88953. }
  88954. return this._transformMatrices;
  88955. };
  88956. /**
  88957. * Gets the current hosting scene
  88958. * @returns a scene object
  88959. */
  88960. Skeleton.prototype.getScene = function () {
  88961. return this._scene;
  88962. };
  88963. // Methods
  88964. /**
  88965. * Gets a string representing the current skeleton data
  88966. * @param fullDetails defines a boolean indicating if we want a verbose version
  88967. * @returns a string representing the current skeleton data
  88968. */
  88969. Skeleton.prototype.toString = function (fullDetails) {
  88970. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  88971. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  88972. if (fullDetails) {
  88973. ret += ", Ranges: {";
  88974. var first = true;
  88975. for (var name_1 in this._ranges) {
  88976. if (first) {
  88977. ret += ", ";
  88978. first = false;
  88979. }
  88980. ret += name_1;
  88981. }
  88982. ret += "}";
  88983. }
  88984. return ret;
  88985. };
  88986. /**
  88987. * Get bone's index searching by name
  88988. * @param name defines bone's name to search for
  88989. * @return the indice of the bone. Returns -1 if not found
  88990. */
  88991. Skeleton.prototype.getBoneIndexByName = function (name) {
  88992. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  88993. if (this.bones[boneIndex].name === name) {
  88994. return boneIndex;
  88995. }
  88996. }
  88997. return -1;
  88998. };
  88999. /**
  89000. * Creater a new animation range
  89001. * @param name defines the name of the range
  89002. * @param from defines the start key
  89003. * @param to defines the end key
  89004. */
  89005. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  89006. // check name not already in use
  89007. if (!this._ranges[name]) {
  89008. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  89009. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  89010. if (this.bones[i].animations[0]) {
  89011. this.bones[i].animations[0].createRange(name, from, to);
  89012. }
  89013. }
  89014. }
  89015. };
  89016. /**
  89017. * Delete a specific animation range
  89018. * @param name defines the name of the range
  89019. * @param deleteFrames defines if frames must be removed as well
  89020. */
  89021. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  89022. if (deleteFrames === void 0) { deleteFrames = true; }
  89023. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  89024. if (this.bones[i].animations[0]) {
  89025. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  89026. }
  89027. }
  89028. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  89029. };
  89030. /**
  89031. * Gets a specific animation range
  89032. * @param name defines the name of the range to look for
  89033. * @returns the requested animation range or null if not found
  89034. */
  89035. Skeleton.prototype.getAnimationRange = function (name) {
  89036. return this._ranges[name];
  89037. };
  89038. /**
  89039. * Gets the list of all animation ranges defined on this skeleton
  89040. * @returns an array
  89041. */
  89042. Skeleton.prototype.getAnimationRanges = function () {
  89043. var animationRanges = [];
  89044. var name;
  89045. var i = 0;
  89046. for (name in this._ranges) {
  89047. animationRanges[i] = this._ranges[name];
  89048. i++;
  89049. }
  89050. return animationRanges;
  89051. };
  89052. /**
  89053. * Copy animation range from a source skeleton.
  89054. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  89055. * @param source defines the source skeleton
  89056. * @param name defines the name of the range to copy
  89057. * @param rescaleAsRequired defines if rescaling must be applied if required
  89058. * @returns true if operation was successful
  89059. */
  89060. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  89061. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  89062. if (this._ranges[name] || !source.getAnimationRange(name)) {
  89063. return false;
  89064. }
  89065. var ret = true;
  89066. var frameOffset = this._getHighestAnimationFrame() + 1;
  89067. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  89068. var boneDict = {};
  89069. var sourceBones = source.bones;
  89070. var nBones;
  89071. var i;
  89072. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  89073. boneDict[sourceBones[i].name] = sourceBones[i];
  89074. }
  89075. if (this.bones.length !== sourceBones.length) {
  89076. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  89077. ret = false;
  89078. }
  89079. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  89080. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  89081. var boneName = this.bones[i].name;
  89082. var sourceBone = boneDict[boneName];
  89083. if (sourceBone) {
  89084. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  89085. }
  89086. else {
  89087. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  89088. ret = false;
  89089. }
  89090. }
  89091. // do not call createAnimationRange(), since it also is done to bones, which was already done
  89092. var range = source.getAnimationRange(name);
  89093. if (range) {
  89094. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  89095. }
  89096. return ret;
  89097. };
  89098. /**
  89099. * Forces the skeleton to go to rest pose
  89100. */
  89101. Skeleton.prototype.returnToRest = function () {
  89102. for (var index = 0; index < this.bones.length; index++) {
  89103. this.bones[index].returnToRest();
  89104. }
  89105. };
  89106. Skeleton.prototype._getHighestAnimationFrame = function () {
  89107. var ret = 0;
  89108. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  89109. if (this.bones[i].animations[0]) {
  89110. var highest = this.bones[i].animations[0].getHighestFrame();
  89111. if (ret < highest) {
  89112. ret = highest;
  89113. }
  89114. }
  89115. }
  89116. return ret;
  89117. };
  89118. /**
  89119. * Begin a specific animation range
  89120. * @param name defines the name of the range to start
  89121. * @param loop defines if looping must be turned on (false by default)
  89122. * @param speedRatio defines the speed ratio to apply (1 by default)
  89123. * @param onAnimationEnd defines a callback which will be called when animation will end
  89124. * @returns a new animatable
  89125. */
  89126. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  89127. var range = this.getAnimationRange(name);
  89128. if (!range) {
  89129. return null;
  89130. }
  89131. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  89132. };
  89133. /** @hidden */
  89134. Skeleton.prototype._markAsDirty = function () {
  89135. this._isDirty = true;
  89136. };
  89137. /** @hidden */
  89138. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  89139. this._meshesWithPoseMatrix.push(mesh);
  89140. };
  89141. /** @hidden */
  89142. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  89143. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  89144. if (index > -1) {
  89145. this._meshesWithPoseMatrix.splice(index, 1);
  89146. }
  89147. };
  89148. /** @hidden */
  89149. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  89150. this.onBeforeComputeObservable.notifyObservers(this);
  89151. for (var index = 0; index < this.bones.length; index++) {
  89152. var bone = this.bones[index];
  89153. var parentBone = bone.getParent();
  89154. if (parentBone) {
  89155. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  89156. }
  89157. else {
  89158. if (initialSkinMatrix) {
  89159. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  89160. }
  89161. else {
  89162. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  89163. }
  89164. }
  89165. if (bone._index !== -1) {
  89166. var mappedIndex = bone._index === null ? index : bone._index;
  89167. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  89168. }
  89169. }
  89170. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  89171. };
  89172. /**
  89173. * Build all resources required to render a skeleton
  89174. */
  89175. Skeleton.prototype.prepare = function () {
  89176. if (!this._isDirty) {
  89177. return;
  89178. }
  89179. if (this.needInitialSkinMatrix) {
  89180. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  89181. var mesh = this._meshesWithPoseMatrix[index];
  89182. var poseMatrix = mesh.getPoseMatrix();
  89183. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  89184. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  89185. }
  89186. if (this._synchronizedWithMesh !== mesh) {
  89187. this._synchronizedWithMesh = mesh;
  89188. // Prepare bones
  89189. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  89190. var bone = this.bones[boneIndex];
  89191. if (!bone.getParent()) {
  89192. var matrix = bone.getBaseMatrix();
  89193. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  89194. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  89195. }
  89196. }
  89197. }
  89198. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  89199. }
  89200. }
  89201. else {
  89202. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  89203. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  89204. }
  89205. this._computeTransformMatrices(this._transformMatrices, null);
  89206. }
  89207. this._isDirty = false;
  89208. this._scene._activeBones.addCount(this.bones.length, false);
  89209. };
  89210. /**
  89211. * Gets the list of animatables currently running for this skeleton
  89212. * @returns an array of animatables
  89213. */
  89214. Skeleton.prototype.getAnimatables = function () {
  89215. if (!this._animatables || this._animatables.length !== this.bones.length) {
  89216. this._animatables = [];
  89217. for (var index = 0; index < this.bones.length; index++) {
  89218. this._animatables.push(this.bones[index]);
  89219. }
  89220. }
  89221. return this._animatables;
  89222. };
  89223. /**
  89224. * Clone the current skeleton
  89225. * @param name defines the name of the new skeleton
  89226. * @param id defines the id of the enw skeleton
  89227. * @returns the new skeleton
  89228. */
  89229. Skeleton.prototype.clone = function (name, id) {
  89230. var result = new Skeleton(name, id || name, this._scene);
  89231. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  89232. for (var index = 0; index < this.bones.length; index++) {
  89233. var source = this.bones[index];
  89234. var parentBone = null;
  89235. var parent_1 = source.getParent();
  89236. if (parent_1) {
  89237. var parentIndex = this.bones.indexOf(parent_1);
  89238. parentBone = result.bones[parentIndex];
  89239. }
  89240. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  89241. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  89242. }
  89243. if (this._ranges) {
  89244. result._ranges = {};
  89245. for (var rangeName in this._ranges) {
  89246. var range = this._ranges[rangeName];
  89247. if (range) {
  89248. result._ranges[rangeName] = range.clone();
  89249. }
  89250. }
  89251. }
  89252. this._isDirty = true;
  89253. return result;
  89254. };
  89255. /**
  89256. * Enable animation blending for this skeleton
  89257. * @param blendingSpeed defines the blending speed to apply
  89258. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  89259. */
  89260. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  89261. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  89262. this.bones.forEach(function (bone) {
  89263. bone.animations.forEach(function (animation) {
  89264. animation.enableBlending = true;
  89265. animation.blendingSpeed = blendingSpeed;
  89266. });
  89267. });
  89268. };
  89269. /**
  89270. * Releases all resources associated with the current skeleton
  89271. */
  89272. Skeleton.prototype.dispose = function () {
  89273. this._meshesWithPoseMatrix = [];
  89274. // Animations
  89275. this.getScene().stopAnimation(this);
  89276. // Remove from scene
  89277. this.getScene().removeSkeleton(this);
  89278. };
  89279. /**
  89280. * Serialize the skeleton in a JSON object
  89281. * @returns a JSON object
  89282. */
  89283. Skeleton.prototype.serialize = function () {
  89284. var serializationObject = {};
  89285. serializationObject.name = this.name;
  89286. serializationObject.id = this.id;
  89287. if (this.dimensionsAtRest) {
  89288. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  89289. }
  89290. serializationObject.bones = [];
  89291. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  89292. for (var index = 0; index < this.bones.length; index++) {
  89293. var bone = this.bones[index];
  89294. var parent_2 = bone.getParent();
  89295. var serializedBone = {
  89296. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  89297. name: bone.name,
  89298. matrix: bone.getBaseMatrix().toArray(),
  89299. rest: bone.getRestPose().toArray()
  89300. };
  89301. serializationObject.bones.push(serializedBone);
  89302. if (bone.length) {
  89303. serializedBone.length = bone.length;
  89304. }
  89305. if (bone.metadata) {
  89306. serializedBone.metadata = bone.metadata;
  89307. }
  89308. if (bone.animations && bone.animations.length > 0) {
  89309. serializedBone.animation = bone.animations[0].serialize();
  89310. }
  89311. serializationObject.ranges = [];
  89312. for (var name in this._ranges) {
  89313. var source = this._ranges[name];
  89314. if (!source) {
  89315. continue;
  89316. }
  89317. var range = {};
  89318. range.name = name;
  89319. range.from = source.from;
  89320. range.to = source.to;
  89321. serializationObject.ranges.push(range);
  89322. }
  89323. }
  89324. return serializationObject;
  89325. };
  89326. /**
  89327. * Creates a new skeleton from serialized data
  89328. * @param parsedSkeleton defines the serialized data
  89329. * @param scene defines the hosting scene
  89330. * @returns a new skeleton
  89331. */
  89332. Skeleton.Parse = function (parsedSkeleton, scene) {
  89333. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  89334. if (parsedSkeleton.dimensionsAtRest) {
  89335. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  89336. }
  89337. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  89338. var index;
  89339. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  89340. var parsedBone = parsedSkeleton.bones[index];
  89341. var parentBone = null;
  89342. if (parsedBone.parentBoneIndex > -1) {
  89343. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  89344. }
  89345. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  89346. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  89347. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  89348. bone.id = parsedBone.id;
  89349. }
  89350. if (parsedBone.length) {
  89351. bone.length = parsedBone.length;
  89352. }
  89353. if (parsedBone.metadata) {
  89354. bone.metadata = parsedBone.metadata;
  89355. }
  89356. if (parsedBone.animation) {
  89357. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  89358. }
  89359. }
  89360. // placed after bones, so createAnimationRange can cascade down
  89361. if (parsedSkeleton.ranges) {
  89362. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  89363. var data = parsedSkeleton.ranges[index];
  89364. skeleton.createAnimationRange(data.name, data.from, data.to);
  89365. }
  89366. }
  89367. return skeleton;
  89368. };
  89369. /**
  89370. * Compute all node absolute transforms
  89371. * @param forceUpdate defines if computation must be done even if cache is up to date
  89372. */
  89373. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  89374. if (forceUpdate === void 0) { forceUpdate = false; }
  89375. var renderId = this._scene.getRenderId();
  89376. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  89377. this.bones[0].computeAbsoluteTransforms();
  89378. this._lastAbsoluteTransformsUpdateId = renderId;
  89379. }
  89380. };
  89381. /**
  89382. * Gets the root pose matrix
  89383. * @returns a matrix
  89384. */
  89385. Skeleton.prototype.getPoseMatrix = function () {
  89386. var poseMatrix = null;
  89387. if (this._meshesWithPoseMatrix.length > 0) {
  89388. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  89389. }
  89390. return poseMatrix;
  89391. };
  89392. /**
  89393. * Sorts bones per internal index
  89394. */
  89395. Skeleton.prototype.sortBones = function () {
  89396. var bones = new Array();
  89397. var visited = new Array(this.bones.length);
  89398. for (var index = 0; index < this.bones.length; index++) {
  89399. this._sortBones(index, bones, visited);
  89400. }
  89401. this.bones = bones;
  89402. };
  89403. Skeleton.prototype._sortBones = function (index, bones, visited) {
  89404. if (visited[index]) {
  89405. return;
  89406. }
  89407. visited[index] = true;
  89408. var bone = this.bones[index];
  89409. if (bone._index === undefined) {
  89410. bone._index = index;
  89411. }
  89412. var parentBone = bone.getParent();
  89413. if (parentBone) {
  89414. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  89415. }
  89416. bones.push(bone);
  89417. };
  89418. return Skeleton;
  89419. }());
  89420. BABYLON.Skeleton = Skeleton;
  89421. })(BABYLON || (BABYLON = {}));
  89422. //# sourceMappingURL=babylon.skeleton.js.map
  89423. var BABYLON;
  89424. (function (BABYLON) {
  89425. ;
  89426. /**
  89427. * This groups tools to convert HDR texture to native colors array.
  89428. */
  89429. var HDRTools = /** @class */ (function () {
  89430. function HDRTools() {
  89431. }
  89432. HDRTools.Ldexp = function (mantissa, exponent) {
  89433. if (exponent > 1023) {
  89434. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  89435. }
  89436. if (exponent < -1074) {
  89437. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  89438. }
  89439. return mantissa * Math.pow(2, exponent);
  89440. };
  89441. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  89442. if (exponent > 0) { /*nonzero pixel*/
  89443. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  89444. float32array[index + 0] = red * exponent;
  89445. float32array[index + 1] = green * exponent;
  89446. float32array[index + 2] = blue * exponent;
  89447. }
  89448. else {
  89449. float32array[index + 0] = 0;
  89450. float32array[index + 1] = 0;
  89451. float32array[index + 2] = 0;
  89452. }
  89453. };
  89454. HDRTools.readStringLine = function (uint8array, startIndex) {
  89455. var line = "";
  89456. var character = "";
  89457. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  89458. character = String.fromCharCode(uint8array[i]);
  89459. if (character == "\n") {
  89460. break;
  89461. }
  89462. line += character;
  89463. }
  89464. return line;
  89465. };
  89466. /**
  89467. * Reads header information from an RGBE texture stored in a native array.
  89468. * More information on this format are available here:
  89469. * https://en.wikipedia.org/wiki/RGBE_image_format
  89470. *
  89471. * @param uint8array The binary file stored in native array.
  89472. * @return The header information.
  89473. */
  89474. HDRTools.RGBE_ReadHeader = function (uint8array) {
  89475. var height = 0;
  89476. var width = 0;
  89477. var line = this.readStringLine(uint8array, 0);
  89478. if (line[0] != '#' || line[1] != '?') {
  89479. throw "Bad HDR Format.";
  89480. }
  89481. var endOfHeader = false;
  89482. var findFormat = false;
  89483. var lineIndex = 0;
  89484. do {
  89485. lineIndex += (line.length + 1);
  89486. line = this.readStringLine(uint8array, lineIndex);
  89487. if (line == "FORMAT=32-bit_rle_rgbe") {
  89488. findFormat = true;
  89489. }
  89490. else if (line.length == 0) {
  89491. endOfHeader = true;
  89492. }
  89493. } while (!endOfHeader);
  89494. if (!findFormat) {
  89495. throw "HDR Bad header format, unsupported FORMAT";
  89496. }
  89497. lineIndex += (line.length + 1);
  89498. line = this.readStringLine(uint8array, lineIndex);
  89499. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  89500. var match = sizeRegexp.exec(line);
  89501. // TODO. Support +Y and -X if needed.
  89502. if (!match || match.length < 3) {
  89503. throw "HDR Bad header format, no size";
  89504. }
  89505. width = parseInt(match[2]);
  89506. height = parseInt(match[1]);
  89507. if (width < 8 || width > 0x7fff) {
  89508. throw "HDR Bad header format, unsupported size";
  89509. }
  89510. lineIndex += (line.length + 1);
  89511. return {
  89512. height: height,
  89513. width: width,
  89514. dataPosition: lineIndex
  89515. };
  89516. };
  89517. /**
  89518. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  89519. * This RGBE texture needs to store the information as a panorama.
  89520. *
  89521. * More information on this format are available here:
  89522. * https://en.wikipedia.org/wiki/RGBE_image_format
  89523. *
  89524. * @param buffer The binary file stored in an array buffer.
  89525. * @param size The expected size of the extracted cubemap.
  89526. * @return The Cube Map information.
  89527. */
  89528. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  89529. var uint8array = new Uint8Array(buffer);
  89530. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  89531. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  89532. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  89533. return cubeMapData;
  89534. };
  89535. /**
  89536. * Returns the pixels data extracted from an RGBE texture.
  89537. * This pixels will be stored left to right up to down in the R G B order in one array.
  89538. *
  89539. * More information on this format are available here:
  89540. * https://en.wikipedia.org/wiki/RGBE_image_format
  89541. *
  89542. * @param uint8array The binary file stored in an array buffer.
  89543. * @param hdrInfo The header information of the file.
  89544. * @return The pixels data in RGB right to left up to down order.
  89545. */
  89546. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  89547. // Keep for multi format supports.
  89548. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  89549. };
  89550. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  89551. var num_scanlines = hdrInfo.height;
  89552. var scanline_width = hdrInfo.width;
  89553. var a, b, c, d, count;
  89554. var dataIndex = hdrInfo.dataPosition;
  89555. var index = 0, endIndex = 0, i = 0;
  89556. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  89557. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  89558. // 3 channels of 4 bytes per pixel in float.
  89559. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  89560. var resultArray = new Float32Array(resultBuffer);
  89561. // read in each successive scanline
  89562. while (num_scanlines > 0) {
  89563. a = uint8array[dataIndex++];
  89564. b = uint8array[dataIndex++];
  89565. c = uint8array[dataIndex++];
  89566. d = uint8array[dataIndex++];
  89567. if (a != 2 || b != 2 || (c & 0x80)) {
  89568. // this file is not run length encoded
  89569. throw "HDR Bad header format, not RLE";
  89570. }
  89571. if (((c << 8) | d) != scanline_width) {
  89572. throw "HDR Bad header format, wrong scan line width";
  89573. }
  89574. index = 0;
  89575. // read each of the four channels for the scanline into the buffer
  89576. for (i = 0; i < 4; i++) {
  89577. endIndex = (i + 1) * scanline_width;
  89578. while (index < endIndex) {
  89579. a = uint8array[dataIndex++];
  89580. b = uint8array[dataIndex++];
  89581. if (a > 128) {
  89582. // a run of the same value
  89583. count = a - 128;
  89584. if ((count == 0) || (count > endIndex - index)) {
  89585. throw "HDR Bad Format, bad scanline data (run)";
  89586. }
  89587. while (count-- > 0) {
  89588. scanLineArray[index++] = b;
  89589. }
  89590. }
  89591. else {
  89592. // a non-run
  89593. count = a;
  89594. if ((count == 0) || (count > endIndex - index)) {
  89595. throw "HDR Bad Format, bad scanline data (non-run)";
  89596. }
  89597. scanLineArray[index++] = b;
  89598. if (--count > 0) {
  89599. for (var j = 0; j < count; j++) {
  89600. scanLineArray[index++] = uint8array[dataIndex++];
  89601. }
  89602. }
  89603. }
  89604. }
  89605. }
  89606. // now convert data from buffer into floats
  89607. for (i = 0; i < scanline_width; i++) {
  89608. a = scanLineArray[i];
  89609. b = scanLineArray[i + scanline_width];
  89610. c = scanLineArray[i + 2 * scanline_width];
  89611. d = scanLineArray[i + 3 * scanline_width];
  89612. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  89613. }
  89614. num_scanlines--;
  89615. }
  89616. return resultArray;
  89617. };
  89618. return HDRTools;
  89619. }());
  89620. BABYLON.HDRTools = HDRTools;
  89621. })(BABYLON || (BABYLON = {}));
  89622. //# sourceMappingURL=babylon.hdr.js.map
  89623. var BABYLON;
  89624. (function (BABYLON) {
  89625. /**
  89626. * This represents a texture coming from an HDR input.
  89627. *
  89628. * The only supported format is currently panorama picture stored in RGBE format.
  89629. * Example of such files can be found on HDRLib: http://hdrlib.com/
  89630. */
  89631. var HDRCubeTexture = /** @class */ (function (_super) {
  89632. __extends(HDRCubeTexture, _super);
  89633. /**
  89634. * Instantiates an HDRTexture from the following parameters.
  89635. *
  89636. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  89637. * @param scene The scene the texture will be used in
  89638. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  89639. * @param noMipmap Forces to not generate the mipmap if true
  89640. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  89641. * @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)
  89642. * @param reserved Reserved flag for internal use.
  89643. */
  89644. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  89645. if (noMipmap === void 0) { noMipmap = false; }
  89646. if (generateHarmonics === void 0) { generateHarmonics = true; }
  89647. if (gammaSpace === void 0) { gammaSpace = false; }
  89648. if (reserved === void 0) { reserved = false; }
  89649. if (onLoad === void 0) { onLoad = null; }
  89650. if (onError === void 0) { onError = null; }
  89651. var _this = _super.call(this, scene) || this;
  89652. _this._generateHarmonics = true;
  89653. _this._onLoad = null;
  89654. _this._onError = null;
  89655. /**
  89656. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  89657. */
  89658. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  89659. _this._isBlocking = true;
  89660. _this._rotationY = 0;
  89661. /**
  89662. * Gets or sets the center of the bounding box associated with the cube texture
  89663. * It must define where the camera used to render the texture was set
  89664. */
  89665. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  89666. if (!url) {
  89667. return _this;
  89668. }
  89669. _this.name = url;
  89670. _this.url = url;
  89671. _this.hasAlpha = false;
  89672. _this.isCube = true;
  89673. _this._textureMatrix = BABYLON.Matrix.Identity();
  89674. _this._onLoad = onLoad;
  89675. _this._onError = onError;
  89676. _this.gammaSpace = gammaSpace;
  89677. _this._noMipmap = noMipmap;
  89678. _this._size = size;
  89679. _this._texture = _this._getFromCache(url, _this._noMipmap);
  89680. if (!_this._texture) {
  89681. if (!scene.useDelayedTextureLoading) {
  89682. _this.loadTexture();
  89683. }
  89684. else {
  89685. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  89686. }
  89687. }
  89688. return _this;
  89689. }
  89690. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  89691. /**
  89692. * Gets wether or not the texture is blocking during loading.
  89693. */
  89694. get: function () {
  89695. return this._isBlocking;
  89696. },
  89697. /**
  89698. * Sets wether or not the texture is blocking during loading.
  89699. */
  89700. set: function (value) {
  89701. this._isBlocking = value;
  89702. },
  89703. enumerable: true,
  89704. configurable: true
  89705. });
  89706. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  89707. /**
  89708. * Gets texture matrix rotation angle around Y axis radians.
  89709. */
  89710. get: function () {
  89711. return this._rotationY;
  89712. },
  89713. /**
  89714. * Sets texture matrix rotation angle around Y axis in radians.
  89715. */
  89716. set: function (value) {
  89717. this._rotationY = value;
  89718. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  89719. },
  89720. enumerable: true,
  89721. configurable: true
  89722. });
  89723. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  89724. get: function () {
  89725. return this._boundingBoxSize;
  89726. },
  89727. /**
  89728. * Gets or sets the size of the bounding box associated with the cube texture
  89729. * When defined, the cubemap will switch to local mode
  89730. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  89731. * @example https://www.babylonjs-playground.com/#RNASML
  89732. */
  89733. set: function (value) {
  89734. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  89735. return;
  89736. }
  89737. this._boundingBoxSize = value;
  89738. var scene = this.getScene();
  89739. if (scene) {
  89740. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  89741. }
  89742. },
  89743. enumerable: true,
  89744. configurable: true
  89745. });
  89746. /**
  89747. * Occurs when the file is raw .hdr file.
  89748. */
  89749. HDRCubeTexture.prototype.loadTexture = function () {
  89750. var _this = this;
  89751. var callback = function (buffer) {
  89752. _this.lodGenerationOffset = 0.0;
  89753. _this.lodGenerationScale = 0.8;
  89754. var scene = _this.getScene();
  89755. if (!scene) {
  89756. return null;
  89757. }
  89758. // Extract the raw linear data.
  89759. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  89760. // Generate harmonics if needed.
  89761. if (_this._generateHarmonics) {
  89762. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  89763. _this.sphericalPolynomial = sphericalPolynomial;
  89764. }
  89765. var results = [];
  89766. var byteArray = null;
  89767. // Push each faces.
  89768. for (var j = 0; j < 6; j++) {
  89769. // Create uintarray fallback.
  89770. if (!scene.getEngine().getCaps().textureFloat) {
  89771. // 3 channels of 1 bytes per pixel in bytes.
  89772. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  89773. byteArray = new Uint8Array(byteBuffer);
  89774. }
  89775. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  89776. // If special cases.
  89777. if (_this.gammaSpace || byteArray) {
  89778. for (var i = 0; i < _this._size * _this._size; i++) {
  89779. // Put in gamma space if requested.
  89780. if (_this.gammaSpace) {
  89781. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  89782. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  89783. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  89784. }
  89785. // Convert to int texture for fallback.
  89786. if (byteArray) {
  89787. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  89788. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  89789. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  89790. // May use luminance instead if the result is not accurate.
  89791. var max = Math.max(Math.max(r, g), b);
  89792. if (max > 255) {
  89793. var scale = 255 / max;
  89794. r *= scale;
  89795. g *= scale;
  89796. b *= scale;
  89797. }
  89798. byteArray[(i * 3) + 0] = r;
  89799. byteArray[(i * 3) + 1] = g;
  89800. byteArray[(i * 3) + 2] = b;
  89801. }
  89802. }
  89803. }
  89804. if (byteArray) {
  89805. results.push(byteArray);
  89806. }
  89807. else {
  89808. results.push(dataFace);
  89809. }
  89810. }
  89811. return results;
  89812. };
  89813. var scene = this.getScene();
  89814. if (scene) {
  89815. 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);
  89816. }
  89817. };
  89818. HDRCubeTexture.prototype.clone = function () {
  89819. var scene = this.getScene();
  89820. if (!scene) {
  89821. return this;
  89822. }
  89823. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  89824. // Base texture
  89825. newTexture.level = this.level;
  89826. newTexture.wrapU = this.wrapU;
  89827. newTexture.wrapV = this.wrapV;
  89828. newTexture.coordinatesIndex = this.coordinatesIndex;
  89829. newTexture.coordinatesMode = this.coordinatesMode;
  89830. return newTexture;
  89831. };
  89832. // Methods
  89833. HDRCubeTexture.prototype.delayLoad = function () {
  89834. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  89835. return;
  89836. }
  89837. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  89838. this._texture = this._getFromCache(this.url, this._noMipmap);
  89839. if (!this._texture) {
  89840. this.loadTexture();
  89841. }
  89842. };
  89843. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  89844. return this._textureMatrix;
  89845. };
  89846. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  89847. this._textureMatrix = value;
  89848. };
  89849. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  89850. var texture = null;
  89851. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  89852. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  89853. texture.name = parsedTexture.name;
  89854. texture.hasAlpha = parsedTexture.hasAlpha;
  89855. texture.level = parsedTexture.level;
  89856. texture.coordinatesMode = parsedTexture.coordinatesMode;
  89857. texture.isBlocking = parsedTexture.isBlocking;
  89858. }
  89859. if (texture) {
  89860. if (parsedTexture.boundingBoxPosition) {
  89861. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  89862. }
  89863. if (parsedTexture.boundingBoxSize) {
  89864. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  89865. }
  89866. if (parsedTexture.rotationY) {
  89867. texture.rotationY = parsedTexture.rotationY;
  89868. }
  89869. }
  89870. return texture;
  89871. };
  89872. HDRCubeTexture.prototype.serialize = function () {
  89873. if (!this.name) {
  89874. return null;
  89875. }
  89876. var serializationObject = {};
  89877. serializationObject.name = this.name;
  89878. serializationObject.hasAlpha = this.hasAlpha;
  89879. serializationObject.isCube = true;
  89880. serializationObject.level = this.level;
  89881. serializationObject.size = this._size;
  89882. serializationObject.coordinatesMode = this.coordinatesMode;
  89883. serializationObject.useInGammaSpace = this.gammaSpace;
  89884. serializationObject.generateHarmonics = this._generateHarmonics;
  89885. serializationObject.customType = "BABYLON.HDRCubeTexture";
  89886. serializationObject.noMipmap = this._noMipmap;
  89887. serializationObject.isBlocking = this._isBlocking;
  89888. serializationObject.rotationY = this._rotationY;
  89889. return serializationObject;
  89890. };
  89891. HDRCubeTexture._facesMapping = [
  89892. "right",
  89893. "left",
  89894. "up",
  89895. "down",
  89896. "front",
  89897. "back"
  89898. ];
  89899. return HDRCubeTexture;
  89900. }(BABYLON.BaseTexture));
  89901. BABYLON.HDRCubeTexture = HDRCubeTexture;
  89902. })(BABYLON || (BABYLON = {}));
  89903. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  89904. var BABYLON;
  89905. (function (BABYLON) {
  89906. /**
  89907. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  89908. */
  89909. var PanoramaToCubeMapTools = /** @class */ (function () {
  89910. function PanoramaToCubeMapTools() {
  89911. }
  89912. /**
  89913. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  89914. *
  89915. * @param float32Array The source data.
  89916. * @param inputWidth The width of the input panorama.
  89917. * @param inputhHeight The height of the input panorama.
  89918. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  89919. * @return The cubemap data
  89920. */
  89921. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  89922. if (!float32Array) {
  89923. throw "ConvertPanoramaToCubemap: input cannot be null";
  89924. }
  89925. if (float32Array.length != inputWidth * inputHeight * 3) {
  89926. throw "ConvertPanoramaToCubemap: input size is wrong";
  89927. }
  89928. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  89929. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  89930. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  89931. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  89932. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  89933. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  89934. return {
  89935. front: textureFront,
  89936. back: textureBack,
  89937. left: textureLeft,
  89938. right: textureRight,
  89939. up: textureUp,
  89940. down: textureDown,
  89941. size: size,
  89942. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  89943. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  89944. gammaSpace: false,
  89945. };
  89946. };
  89947. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  89948. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  89949. var textureArray = new Float32Array(buffer);
  89950. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  89951. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  89952. var dy = 1 / texSize;
  89953. var fy = 0;
  89954. for (var y = 0; y < texSize; y++) {
  89955. var xv1 = faceData[0];
  89956. var xv2 = faceData[2];
  89957. for (var x = 0; x < texSize; x++) {
  89958. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  89959. v.normalize();
  89960. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  89961. // 3 channels per pixels
  89962. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  89963. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  89964. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  89965. xv1 = xv1.add(rotDX1);
  89966. xv2 = xv2.add(rotDX2);
  89967. }
  89968. fy += dy;
  89969. }
  89970. return textureArray;
  89971. };
  89972. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  89973. var theta = Math.atan2(vDir.z, vDir.x);
  89974. var phi = Math.acos(vDir.y);
  89975. while (theta < -Math.PI)
  89976. theta += 2 * Math.PI;
  89977. while (theta > Math.PI)
  89978. theta -= 2 * Math.PI;
  89979. var dx = theta / Math.PI;
  89980. var dy = phi / Math.PI;
  89981. // recenter.
  89982. dx = dx * 0.5 + 0.5;
  89983. var px = Math.round(dx * inputWidth);
  89984. if (px < 0)
  89985. px = 0;
  89986. else if (px >= inputWidth)
  89987. px = inputWidth - 1;
  89988. var py = Math.round(dy * inputHeight);
  89989. if (py < 0)
  89990. py = 0;
  89991. else if (py >= inputHeight)
  89992. py = inputHeight - 1;
  89993. var inputY = (inputHeight - py - 1);
  89994. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  89995. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  89996. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  89997. return {
  89998. r: r,
  89999. g: g,
  90000. b: b
  90001. };
  90002. };
  90003. PanoramaToCubeMapTools.FACE_FRONT = [
  90004. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  90005. new BABYLON.Vector3(1.0, -1.0, -1.0),
  90006. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  90007. new BABYLON.Vector3(1.0, 1.0, -1.0)
  90008. ];
  90009. PanoramaToCubeMapTools.FACE_BACK = [
  90010. new BABYLON.Vector3(1.0, -1.0, 1.0),
  90011. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  90012. new BABYLON.Vector3(1.0, 1.0, 1.0),
  90013. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  90014. ];
  90015. PanoramaToCubeMapTools.FACE_RIGHT = [
  90016. new BABYLON.Vector3(1.0, -1.0, -1.0),
  90017. new BABYLON.Vector3(1.0, -1.0, 1.0),
  90018. new BABYLON.Vector3(1.0, 1.0, -1.0),
  90019. new BABYLON.Vector3(1.0, 1.0, 1.0)
  90020. ];
  90021. PanoramaToCubeMapTools.FACE_LEFT = [
  90022. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  90023. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  90024. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  90025. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  90026. ];
  90027. PanoramaToCubeMapTools.FACE_DOWN = [
  90028. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  90029. new BABYLON.Vector3(1.0, 1.0, -1.0),
  90030. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  90031. new BABYLON.Vector3(1.0, 1.0, 1.0)
  90032. ];
  90033. PanoramaToCubeMapTools.FACE_UP = [
  90034. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  90035. new BABYLON.Vector3(1.0, -1.0, 1.0),
  90036. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  90037. new BABYLON.Vector3(1.0, -1.0, -1.0)
  90038. ];
  90039. return PanoramaToCubeMapTools;
  90040. }());
  90041. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  90042. })(BABYLON || (BABYLON = {}));
  90043. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  90044. var BABYLON;
  90045. (function (BABYLON) {
  90046. var IndexedVector2 = /** @class */ (function (_super) {
  90047. __extends(IndexedVector2, _super);
  90048. function IndexedVector2(original, index) {
  90049. var _this = _super.call(this, original.x, original.y) || this;
  90050. _this.index = index;
  90051. return _this;
  90052. }
  90053. return IndexedVector2;
  90054. }(BABYLON.Vector2));
  90055. var PolygonPoints = /** @class */ (function () {
  90056. function PolygonPoints() {
  90057. this.elements = new Array();
  90058. }
  90059. PolygonPoints.prototype.add = function (originalPoints) {
  90060. var _this = this;
  90061. var result = new Array();
  90062. originalPoints.forEach(function (point) {
  90063. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  90064. var newPoint = new IndexedVector2(point, _this.elements.length);
  90065. result.push(newPoint);
  90066. _this.elements.push(newPoint);
  90067. }
  90068. });
  90069. return result;
  90070. };
  90071. PolygonPoints.prototype.computeBounds = function () {
  90072. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  90073. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  90074. this.elements.forEach(function (point) {
  90075. // x
  90076. if (point.x < lmin.x) {
  90077. lmin.x = point.x;
  90078. }
  90079. else if (point.x > lmax.x) {
  90080. lmax.x = point.x;
  90081. }
  90082. // y
  90083. if (point.y < lmin.y) {
  90084. lmin.y = point.y;
  90085. }
  90086. else if (point.y > lmax.y) {
  90087. lmax.y = point.y;
  90088. }
  90089. });
  90090. return {
  90091. min: lmin,
  90092. max: lmax,
  90093. width: lmax.x - lmin.x,
  90094. height: lmax.y - lmin.y
  90095. };
  90096. };
  90097. return PolygonPoints;
  90098. }());
  90099. var Polygon = /** @class */ (function () {
  90100. function Polygon() {
  90101. }
  90102. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  90103. return [
  90104. new BABYLON.Vector2(xmin, ymin),
  90105. new BABYLON.Vector2(xmax, ymin),
  90106. new BABYLON.Vector2(xmax, ymax),
  90107. new BABYLON.Vector2(xmin, ymax)
  90108. ];
  90109. };
  90110. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  90111. if (cx === void 0) { cx = 0; }
  90112. if (cy === void 0) { cy = 0; }
  90113. if (numberOfSides === void 0) { numberOfSides = 32; }
  90114. var result = new Array();
  90115. var angle = 0;
  90116. var increment = (Math.PI * 2) / numberOfSides;
  90117. for (var i = 0; i < numberOfSides; i++) {
  90118. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  90119. angle -= increment;
  90120. }
  90121. return result;
  90122. };
  90123. Polygon.Parse = function (input) {
  90124. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  90125. var i, result = [];
  90126. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  90127. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  90128. }
  90129. return result;
  90130. };
  90131. Polygon.StartingAt = function (x, y) {
  90132. return BABYLON.Path2.StartingAt(x, y);
  90133. };
  90134. return Polygon;
  90135. }());
  90136. BABYLON.Polygon = Polygon;
  90137. var PolygonMeshBuilder = /** @class */ (function () {
  90138. function PolygonMeshBuilder(name, contours, scene) {
  90139. this._points = new PolygonPoints();
  90140. this._outlinepoints = new PolygonPoints();
  90141. this._holes = new Array();
  90142. this._epoints = new Array();
  90143. this._eholes = new Array();
  90144. this._name = name;
  90145. this._scene = scene;
  90146. var points;
  90147. if (contours instanceof BABYLON.Path2) {
  90148. points = contours.getPoints();
  90149. }
  90150. else {
  90151. points = contours;
  90152. }
  90153. this._addToepoint(points);
  90154. this._points.add(points);
  90155. this._outlinepoints.add(points);
  90156. if (typeof earcut === 'undefined') {
  90157. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  90158. }
  90159. }
  90160. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  90161. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  90162. var p = points_1[_i];
  90163. this._epoints.push(p.x, p.y);
  90164. }
  90165. };
  90166. PolygonMeshBuilder.prototype.addHole = function (hole) {
  90167. this._points.add(hole);
  90168. var holepoints = new PolygonPoints();
  90169. holepoints.add(hole);
  90170. this._holes.push(holepoints);
  90171. this._eholes.push(this._epoints.length / 2);
  90172. this._addToepoint(hole);
  90173. return this;
  90174. };
  90175. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  90176. var _this = this;
  90177. if (updatable === void 0) { updatable = false; }
  90178. if (depth === void 0) { depth = 0; }
  90179. var result = new BABYLON.Mesh(this._name, this._scene);
  90180. var normals = new Array();
  90181. var positions = new Array();
  90182. var uvs = new Array();
  90183. var bounds = this._points.computeBounds();
  90184. this._points.elements.forEach(function (p) {
  90185. normals.push(0, 1.0, 0);
  90186. positions.push(p.x, 0, p.y);
  90187. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  90188. });
  90189. var indices = new Array();
  90190. var res = earcut(this._epoints, this._eholes, 2);
  90191. for (var i = 0; i < res.length; i++) {
  90192. indices.push(res[i]);
  90193. }
  90194. if (depth > 0) {
  90195. var positionscount = (positions.length / 3); //get the current pointcount
  90196. this._points.elements.forEach(function (p) {
  90197. normals.push(0, -1.0, 0);
  90198. positions.push(p.x, -depth, p.y);
  90199. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  90200. });
  90201. var totalCount = indices.length;
  90202. for (var i = 0; i < totalCount; i += 3) {
  90203. var i0 = indices[i + 0];
  90204. var i1 = indices[i + 1];
  90205. var i2 = indices[i + 2];
  90206. indices.push(i2 + positionscount);
  90207. indices.push(i1 + positionscount);
  90208. indices.push(i0 + positionscount);
  90209. }
  90210. //Add the sides
  90211. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  90212. this._holes.forEach(function (hole) {
  90213. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  90214. });
  90215. }
  90216. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  90217. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  90218. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  90219. result.setIndices(indices);
  90220. return result;
  90221. };
  90222. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  90223. var StartIndex = positions.length / 3;
  90224. var ulength = 0;
  90225. for (var i = 0; i < points.elements.length; i++) {
  90226. var p = points.elements[i];
  90227. var p1;
  90228. if ((i + 1) > points.elements.length - 1) {
  90229. p1 = points.elements[0];
  90230. }
  90231. else {
  90232. p1 = points.elements[i + 1];
  90233. }
  90234. positions.push(p.x, 0, p.y);
  90235. positions.push(p.x, -depth, p.y);
  90236. positions.push(p1.x, 0, p1.y);
  90237. positions.push(p1.x, -depth, p1.y);
  90238. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  90239. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  90240. var v3 = v2.subtract(v1);
  90241. var v4 = new BABYLON.Vector3(0, 1, 0);
  90242. var vn = BABYLON.Vector3.Cross(v3, v4);
  90243. vn = vn.normalize();
  90244. uvs.push(ulength / bounds.width, 0);
  90245. uvs.push(ulength / bounds.width, 1);
  90246. ulength += v3.length();
  90247. uvs.push((ulength / bounds.width), 0);
  90248. uvs.push((ulength / bounds.width), 1);
  90249. if (!flip) {
  90250. normals.push(-vn.x, -vn.y, -vn.z);
  90251. normals.push(-vn.x, -vn.y, -vn.z);
  90252. normals.push(-vn.x, -vn.y, -vn.z);
  90253. normals.push(-vn.x, -vn.y, -vn.z);
  90254. indices.push(StartIndex);
  90255. indices.push(StartIndex + 1);
  90256. indices.push(StartIndex + 2);
  90257. indices.push(StartIndex + 1);
  90258. indices.push(StartIndex + 3);
  90259. indices.push(StartIndex + 2);
  90260. }
  90261. else {
  90262. normals.push(vn.x, vn.y, vn.z);
  90263. normals.push(vn.x, vn.y, vn.z);
  90264. normals.push(vn.x, vn.y, vn.z);
  90265. normals.push(vn.x, vn.y, vn.z);
  90266. indices.push(StartIndex);
  90267. indices.push(StartIndex + 2);
  90268. indices.push(StartIndex + 1);
  90269. indices.push(StartIndex + 1);
  90270. indices.push(StartIndex + 2);
  90271. indices.push(StartIndex + 3);
  90272. }
  90273. StartIndex += 4;
  90274. }
  90275. ;
  90276. };
  90277. return PolygonMeshBuilder;
  90278. }());
  90279. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  90280. })(BABYLON || (BABYLON = {}));
  90281. //# sourceMappingURL=babylon.polygonMesh.js.map
  90282. var BABYLON;
  90283. (function (BABYLON) {
  90284. /**
  90285. * Unique ID when we import meshes from Babylon to CSG
  90286. */
  90287. var currentCSGMeshId = 0;
  90288. /**
  90289. * Represents a vertex of a polygon. Use your own vertex class instead of this
  90290. * one to provide additional features like texture coordinates and vertex
  90291. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  90292. * `flip()`, and `interpolate()` methods that behave analogous to the ones
  90293. * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  90294. * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  90295. * is not used anywhere else.
  90296. * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  90297. */
  90298. var Vertex = /** @class */ (function () {
  90299. /**
  90300. * Initializes the vertex
  90301. * @param pos The position of the vertex
  90302. * @param normal The normal of the vertex
  90303. * @param uv The texture coordinate of the vertex
  90304. */
  90305. function Vertex(
  90306. /**
  90307. * The position of the vertex
  90308. */
  90309. pos,
  90310. /**
  90311. * The normal of the vertex
  90312. */
  90313. normal,
  90314. /**
  90315. * The texture coordinate of the vertex
  90316. */
  90317. uv) {
  90318. this.pos = pos;
  90319. this.normal = normal;
  90320. this.uv = uv;
  90321. }
  90322. /**
  90323. * Make a clone, or deep copy, of the vertex
  90324. * @returns A new Vertex
  90325. */
  90326. Vertex.prototype.clone = function () {
  90327. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  90328. };
  90329. /**
  90330. * Invert all orientation-specific data (e.g. vertex normal). Called when the
  90331. * orientation of a polygon is flipped.
  90332. */
  90333. Vertex.prototype.flip = function () {
  90334. this.normal = this.normal.scale(-1);
  90335. };
  90336. /**
  90337. * Create a new vertex between this vertex and `other` by linearly
  90338. * interpolating all properties using a parameter of `t`. Subclasses should
  90339. * override this to interpolate additional properties.
  90340. * @param other the vertex to interpolate against
  90341. * @param t The factor used to linearly interpolate between the vertices
  90342. */
  90343. Vertex.prototype.interpolate = function (other, t) {
  90344. 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));
  90345. };
  90346. return Vertex;
  90347. }());
  90348. /**
  90349. * Represents a plane in 3D space.
  90350. */
  90351. var Plane = /** @class */ (function () {
  90352. /**
  90353. * Initializes the plane
  90354. * @param normal The normal for the plane
  90355. * @param w
  90356. */
  90357. function Plane(normal, w) {
  90358. this.normal = normal;
  90359. this.w = w;
  90360. }
  90361. /**
  90362. * Construct a plane from three points
  90363. * @param a Point a
  90364. * @param b Point b
  90365. * @param c Point c
  90366. */
  90367. Plane.FromPoints = function (a, b, c) {
  90368. var v0 = c.subtract(a);
  90369. var v1 = b.subtract(a);
  90370. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  90371. return null;
  90372. }
  90373. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  90374. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  90375. };
  90376. /**
  90377. * Clone, or make a deep copy of the plane
  90378. * @returns a new Plane
  90379. */
  90380. Plane.prototype.clone = function () {
  90381. return new Plane(this.normal.clone(), this.w);
  90382. };
  90383. /**
  90384. * Flip the face of the plane
  90385. */
  90386. Plane.prototype.flip = function () {
  90387. this.normal.scaleInPlace(-1);
  90388. this.w = -this.w;
  90389. };
  90390. /**
  90391. * Split `polygon` by this plane if needed, then put the polygon or polygon
  90392. * fragments in the appropriate lists. Coplanar polygons go into either
  90393. `* coplanarFront` or `coplanarBack` depending on their orientation with
  90394. * respect to this plane. Polygons in front or in back of this plane go into
  90395. * either `front` or `back`
  90396. * @param polygon The polygon to be split
  90397. * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
  90398. * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
  90399. * @param front Will contain the polygons in front of the plane
  90400. * @param back Will contain the polygons begind the plane
  90401. */
  90402. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  90403. var COPLANAR = 0;
  90404. var FRONT = 1;
  90405. var BACK = 2;
  90406. var SPANNING = 3;
  90407. // Classify each point as well as the entire polygon into one of the above
  90408. // four classes.
  90409. var polygonType = 0;
  90410. var types = [];
  90411. var i;
  90412. var t;
  90413. for (i = 0; i < polygon.vertices.length; i++) {
  90414. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  90415. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  90416. polygonType |= type;
  90417. types.push(type);
  90418. }
  90419. // Put the polygon in the correct list, splitting it when necessary
  90420. switch (polygonType) {
  90421. case COPLANAR:
  90422. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  90423. break;
  90424. case FRONT:
  90425. front.push(polygon);
  90426. break;
  90427. case BACK:
  90428. back.push(polygon);
  90429. break;
  90430. case SPANNING:
  90431. var f = [], b = [];
  90432. for (i = 0; i < polygon.vertices.length; i++) {
  90433. var j = (i + 1) % polygon.vertices.length;
  90434. var ti = types[i], tj = types[j];
  90435. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  90436. if (ti !== BACK)
  90437. f.push(vi);
  90438. if (ti !== FRONT)
  90439. b.push(ti !== BACK ? vi.clone() : vi);
  90440. if ((ti | tj) === SPANNING) {
  90441. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  90442. var v = vi.interpolate(vj, t);
  90443. f.push(v);
  90444. b.push(v.clone());
  90445. }
  90446. }
  90447. var poly;
  90448. if (f.length >= 3) {
  90449. poly = new Polygon(f, polygon.shared);
  90450. if (poly.plane)
  90451. front.push(poly);
  90452. }
  90453. if (b.length >= 3) {
  90454. poly = new Polygon(b, polygon.shared);
  90455. if (poly.plane)
  90456. back.push(poly);
  90457. }
  90458. break;
  90459. }
  90460. };
  90461. /**
  90462. * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  90463. * point is on the plane
  90464. */
  90465. Plane.EPSILON = 1e-5;
  90466. return Plane;
  90467. }());
  90468. /**
  90469. * Represents a convex polygon. The vertices used to initialize a polygon must
  90470. * be coplanar and form a convex loop.
  90471. *
  90472. * Each convex polygon has a `shared` property, which is shared between all
  90473. * polygons that are clones of each other or were split from the same polygon.
  90474. * This can be used to define per-polygon properties (such as surface color)
  90475. */
  90476. var Polygon = /** @class */ (function () {
  90477. /**
  90478. * Initializes the polygon
  90479. * @param vertices The vertices of the polygon
  90480. * @param shared The properties shared across all polygons
  90481. */
  90482. function Polygon(vertices, shared) {
  90483. this.vertices = vertices;
  90484. this.shared = shared;
  90485. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  90486. }
  90487. /**
  90488. * Clones, or makes a deep copy, or the polygon
  90489. */
  90490. Polygon.prototype.clone = function () {
  90491. var vertices = this.vertices.map(function (v) { return v.clone(); });
  90492. return new Polygon(vertices, this.shared);
  90493. };
  90494. /**
  90495. * Flips the faces of the polygon
  90496. */
  90497. Polygon.prototype.flip = function () {
  90498. this.vertices.reverse().map(function (v) { v.flip(); });
  90499. this.plane.flip();
  90500. };
  90501. return Polygon;
  90502. }());
  90503. /**
  90504. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  90505. * by picking a polygon to split along. That polygon (and all other coplanar
  90506. * polygons) are added directly to that node and the other polygons are added to
  90507. * the front and/or back subtrees. This is not a leafy BSP tree since there is
  90508. * no distinction between internal and leaf nodes
  90509. */
  90510. var Node = /** @class */ (function () {
  90511. /**
  90512. * Initializes the node
  90513. * @param polygons A collection of polygons held in the node
  90514. */
  90515. function Node(polygons) {
  90516. this.plane = null;
  90517. this.front = null;
  90518. this.back = null;
  90519. this.polygons = new Array();
  90520. if (polygons) {
  90521. this.build(polygons);
  90522. }
  90523. }
  90524. /**
  90525. * Clones, or makes a deep copy, of the node
  90526. * @returns The cloned node
  90527. */
  90528. Node.prototype.clone = function () {
  90529. var node = new Node();
  90530. node.plane = this.plane && this.plane.clone();
  90531. node.front = this.front && this.front.clone();
  90532. node.back = this.back && this.back.clone();
  90533. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  90534. return node;
  90535. };
  90536. /**
  90537. * Convert solid space to empty space and empty space to solid space
  90538. */
  90539. Node.prototype.invert = function () {
  90540. for (var i = 0; i < this.polygons.length; i++) {
  90541. this.polygons[i].flip();
  90542. }
  90543. if (this.plane) {
  90544. this.plane.flip();
  90545. }
  90546. if (this.front) {
  90547. this.front.invert();
  90548. }
  90549. if (this.back) {
  90550. this.back.invert();
  90551. }
  90552. var temp = this.front;
  90553. this.front = this.back;
  90554. this.back = temp;
  90555. };
  90556. /**
  90557. * Recursively remove all polygons in `polygons` that are inside this BSP
  90558. * tree.
  90559. * @param polygons Polygons to remove from the BSP
  90560. * @returns Polygons clipped from the BSP
  90561. */
  90562. Node.prototype.clipPolygons = function (polygons) {
  90563. if (!this.plane)
  90564. return polygons.slice();
  90565. var front = new Array(), back = new Array();
  90566. for (var i = 0; i < polygons.length; i++) {
  90567. this.plane.splitPolygon(polygons[i], front, back, front, back);
  90568. }
  90569. if (this.front) {
  90570. front = this.front.clipPolygons(front);
  90571. }
  90572. if (this.back) {
  90573. back = this.back.clipPolygons(back);
  90574. }
  90575. else {
  90576. back = [];
  90577. }
  90578. return front.concat(back);
  90579. };
  90580. /**
  90581. * Remove all polygons in this BSP tree that are inside the other BSP tree
  90582. * `bsp`.
  90583. * @param bsp BSP containing polygons to remove from this BSP
  90584. */
  90585. Node.prototype.clipTo = function (bsp) {
  90586. this.polygons = bsp.clipPolygons(this.polygons);
  90587. if (this.front)
  90588. this.front.clipTo(bsp);
  90589. if (this.back)
  90590. this.back.clipTo(bsp);
  90591. };
  90592. /**
  90593. * Return a list of all polygons in this BSP tree
  90594. * @returns List of all polygons in this BSP tree
  90595. */
  90596. Node.prototype.allPolygons = function () {
  90597. var polygons = this.polygons.slice();
  90598. if (this.front)
  90599. polygons = polygons.concat(this.front.allPolygons());
  90600. if (this.back)
  90601. polygons = polygons.concat(this.back.allPolygons());
  90602. return polygons;
  90603. };
  90604. /**
  90605. * Build a BSP tree out of `polygons`. When called on an existing tree, the
  90606. * new polygons are filtered down to the bottom of the tree and become new
  90607. * nodes there. Each set of polygons is partitioned using the first polygon
  90608. * (no heuristic is used to pick a good split)
  90609. * @param polygons Polygons used to construct the BSP tree
  90610. */
  90611. Node.prototype.build = function (polygons) {
  90612. if (!polygons.length)
  90613. return;
  90614. if (!this.plane)
  90615. this.plane = polygons[0].plane.clone();
  90616. var front = new Array(), back = new Array();
  90617. for (var i = 0; i < polygons.length; i++) {
  90618. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  90619. }
  90620. if (front.length) {
  90621. if (!this.front)
  90622. this.front = new Node();
  90623. this.front.build(front);
  90624. }
  90625. if (back.length) {
  90626. if (!this.back)
  90627. this.back = new Node();
  90628. this.back.build(back);
  90629. }
  90630. };
  90631. return Node;
  90632. }());
  90633. /**
  90634. * Class for building Constructive Solid Geometry
  90635. */
  90636. var CSG = /** @class */ (function () {
  90637. function CSG() {
  90638. this.polygons = new Array();
  90639. }
  90640. /**
  90641. * Convert the BABYLON.Mesh to BABYLON.CSG
  90642. * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
  90643. * @returns A new BABYLON.CSG from the BABYLON.Mesh
  90644. */
  90645. CSG.FromMesh = function (mesh) {
  90646. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  90647. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  90648. if (mesh instanceof BABYLON.Mesh) {
  90649. mesh.computeWorldMatrix(true);
  90650. matrix = mesh.getWorldMatrix();
  90651. meshPosition = mesh.position.clone();
  90652. meshRotation = mesh.rotation.clone();
  90653. if (mesh.rotationQuaternion) {
  90654. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  90655. }
  90656. meshScaling = mesh.scaling.clone();
  90657. }
  90658. else {
  90659. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  90660. }
  90661. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  90662. var subMeshes = mesh.subMeshes;
  90663. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  90664. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  90665. vertices = [];
  90666. for (var j = 0; j < 3; j++) {
  90667. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  90668. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  90669. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  90670. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  90671. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  90672. vertex = new Vertex(position, normal, uv);
  90673. vertices.push(vertex);
  90674. }
  90675. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  90676. // To handle the case of degenerated triangle
  90677. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  90678. if (polygon.plane)
  90679. polygons.push(polygon);
  90680. }
  90681. }
  90682. var csg = CSG.FromPolygons(polygons);
  90683. csg.matrix = matrix;
  90684. csg.position = meshPosition;
  90685. csg.rotation = meshRotation;
  90686. csg.scaling = meshScaling;
  90687. csg.rotationQuaternion = meshRotationQuaternion;
  90688. currentCSGMeshId++;
  90689. return csg;
  90690. };
  90691. /**
  90692. * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  90693. * @param polygons Polygons used to construct a BABYLON.CSG solid
  90694. */
  90695. CSG.FromPolygons = function (polygons) {
  90696. var csg = new CSG();
  90697. csg.polygons = polygons;
  90698. return csg;
  90699. };
  90700. /**
  90701. * Clones, or makes a deep copy, of the BABYLON.CSG
  90702. * @returns A new BABYLON.CSG
  90703. */
  90704. CSG.prototype.clone = function () {
  90705. var csg = new CSG();
  90706. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  90707. csg.copyTransformAttributes(this);
  90708. return csg;
  90709. };
  90710. /**
  90711. * Unions this CSG with another CSG
  90712. * @param csg The CSG to union against this CSG
  90713. * @returns The unioned CSG
  90714. */
  90715. CSG.prototype.union = function (csg) {
  90716. var a = new Node(this.clone().polygons);
  90717. var b = new Node(csg.clone().polygons);
  90718. a.clipTo(b);
  90719. b.clipTo(a);
  90720. b.invert();
  90721. b.clipTo(a);
  90722. b.invert();
  90723. a.build(b.allPolygons());
  90724. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  90725. };
  90726. /**
  90727. * Unions this CSG with another CSG in place
  90728. * @param csg The CSG to union against this CSG
  90729. */
  90730. CSG.prototype.unionInPlace = function (csg) {
  90731. var a = new Node(this.polygons);
  90732. var b = new Node(csg.polygons);
  90733. a.clipTo(b);
  90734. b.clipTo(a);
  90735. b.invert();
  90736. b.clipTo(a);
  90737. b.invert();
  90738. a.build(b.allPolygons());
  90739. this.polygons = a.allPolygons();
  90740. };
  90741. /**
  90742. * Subtracts this CSG with another CSG
  90743. * @param csg The CSG to subtract against this CSG
  90744. * @returns A new BABYLON.CSG
  90745. */
  90746. CSG.prototype.subtract = function (csg) {
  90747. var a = new Node(this.clone().polygons);
  90748. var b = new Node(csg.clone().polygons);
  90749. a.invert();
  90750. a.clipTo(b);
  90751. b.clipTo(a);
  90752. b.invert();
  90753. b.clipTo(a);
  90754. b.invert();
  90755. a.build(b.allPolygons());
  90756. a.invert();
  90757. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  90758. };
  90759. /**
  90760. * Subtracts this CSG with another CSG in place
  90761. * @param csg The CSG to subtact against this CSG
  90762. */
  90763. CSG.prototype.subtractInPlace = function (csg) {
  90764. var a = new Node(this.polygons);
  90765. var b = new Node(csg.polygons);
  90766. a.invert();
  90767. a.clipTo(b);
  90768. b.clipTo(a);
  90769. b.invert();
  90770. b.clipTo(a);
  90771. b.invert();
  90772. a.build(b.allPolygons());
  90773. a.invert();
  90774. this.polygons = a.allPolygons();
  90775. };
  90776. /**
  90777. * Intersect this CSG with another CSG
  90778. * @param csg The CSG to intersect against this CSG
  90779. * @returns A new BABYLON.CSG
  90780. */
  90781. CSG.prototype.intersect = function (csg) {
  90782. var a = new Node(this.clone().polygons);
  90783. var b = new Node(csg.clone().polygons);
  90784. a.invert();
  90785. b.clipTo(a);
  90786. b.invert();
  90787. a.clipTo(b);
  90788. b.clipTo(a);
  90789. a.build(b.allPolygons());
  90790. a.invert();
  90791. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  90792. };
  90793. /**
  90794. * Intersects this CSG with another CSG in place
  90795. * @param csg The CSG to intersect against this CSG
  90796. */
  90797. CSG.prototype.intersectInPlace = function (csg) {
  90798. var a = new Node(this.polygons);
  90799. var b = new Node(csg.polygons);
  90800. a.invert();
  90801. b.clipTo(a);
  90802. b.invert();
  90803. a.clipTo(b);
  90804. b.clipTo(a);
  90805. a.build(b.allPolygons());
  90806. a.invert();
  90807. this.polygons = a.allPolygons();
  90808. };
  90809. /**
  90810. * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  90811. * not modified.
  90812. * @returns A new BABYLON.CSG solid with solid and empty space switched
  90813. */
  90814. CSG.prototype.inverse = function () {
  90815. var csg = this.clone();
  90816. csg.inverseInPlace();
  90817. return csg;
  90818. };
  90819. /**
  90820. * Inverses the BABYLON.CSG in place
  90821. */
  90822. CSG.prototype.inverseInPlace = function () {
  90823. this.polygons.map(function (p) { p.flip(); });
  90824. };
  90825. /**
  90826. * This is used to keep meshes transformations so they can be restored
  90827. * when we build back a Babylon Mesh
  90828. * NB : All CSG operations are performed in world coordinates
  90829. * @param csg The BABYLON.CSG to copy the transform attributes from
  90830. * @returns This BABYLON.CSG
  90831. */
  90832. CSG.prototype.copyTransformAttributes = function (csg) {
  90833. this.matrix = csg.matrix;
  90834. this.position = csg.position;
  90835. this.rotation = csg.rotation;
  90836. this.scaling = csg.scaling;
  90837. this.rotationQuaternion = csg.rotationQuaternion;
  90838. return this;
  90839. };
  90840. /**
  90841. * Build Raw mesh from CSG
  90842. * Coordinates here are in world space
  90843. * @param name The name of the mesh geometry
  90844. * @param scene The BABYLON.Scene
  90845. * @param keepSubMeshes Specifies if the submeshes should be kept
  90846. * @returns A new BABYLON.Mesh
  90847. */
  90848. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  90849. var matrix = this.matrix.clone();
  90850. matrix.invert();
  90851. 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;
  90852. if (keepSubMeshes) {
  90853. // Sort Polygons, since subMeshes are indices range
  90854. polygons.sort(function (a, b) {
  90855. if (a.shared.meshId === b.shared.meshId) {
  90856. return a.shared.subMeshId - b.shared.subMeshId;
  90857. }
  90858. else {
  90859. return a.shared.meshId - b.shared.meshId;
  90860. }
  90861. });
  90862. }
  90863. for (var i = 0, il = polygons.length; i < il; i++) {
  90864. polygon = polygons[i];
  90865. // Building SubMeshes
  90866. if (!subMesh_dict[polygon.shared.meshId]) {
  90867. subMesh_dict[polygon.shared.meshId] = {};
  90868. }
  90869. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  90870. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  90871. indexStart: +Infinity,
  90872. indexEnd: -Infinity,
  90873. materialIndex: polygon.shared.materialIndex
  90874. };
  90875. }
  90876. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  90877. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  90878. polygonIndices[0] = 0;
  90879. polygonIndices[1] = j - 1;
  90880. polygonIndices[2] = j;
  90881. for (var k = 0; k < 3; k++) {
  90882. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  90883. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  90884. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  90885. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  90886. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  90887. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  90888. // Check if 2 points can be merged
  90889. if (!(typeof vertex_idx !== 'undefined' &&
  90890. normals[vertex_idx * 3] === localNormal.x &&
  90891. normals[vertex_idx * 3 + 1] === localNormal.y &&
  90892. normals[vertex_idx * 3 + 2] === localNormal.z &&
  90893. uvs[vertex_idx * 2] === uv.x &&
  90894. uvs[vertex_idx * 2 + 1] === uv.y)) {
  90895. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  90896. uvs.push(uv.x, uv.y);
  90897. normals.push(normal.x, normal.y, normal.z);
  90898. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  90899. }
  90900. indices.push(vertex_idx);
  90901. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  90902. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  90903. currentIndex++;
  90904. }
  90905. }
  90906. }
  90907. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  90908. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  90909. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  90910. mesh.setIndices(indices, null);
  90911. if (keepSubMeshes) {
  90912. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  90913. var materialIndexOffset = 0, materialMaxIndex;
  90914. mesh.subMeshes = new Array();
  90915. for (var m in subMesh_dict) {
  90916. materialMaxIndex = -1;
  90917. for (var sm in subMesh_dict[m]) {
  90918. subMesh_obj = subMesh_dict[m][sm];
  90919. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  90920. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  90921. }
  90922. materialIndexOffset += ++materialMaxIndex;
  90923. }
  90924. }
  90925. return mesh;
  90926. };
  90927. /**
  90928. * Build Mesh from CSG taking material and transforms into account
  90929. * @param name The name of the BABYLON.Mesh
  90930. * @param material The material of the BABYLON.Mesh
  90931. * @param scene The BABYLON.Scene
  90932. * @param keepSubMeshes Specifies if submeshes should be kept
  90933. * @returns The new BABYLON.Mesh
  90934. */
  90935. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  90936. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  90937. mesh.material = material;
  90938. mesh.position.copyFrom(this.position);
  90939. mesh.rotation.copyFrom(this.rotation);
  90940. if (this.rotationQuaternion) {
  90941. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  90942. }
  90943. mesh.scaling.copyFrom(this.scaling);
  90944. mesh.computeWorldMatrix(true);
  90945. return mesh;
  90946. };
  90947. return CSG;
  90948. }());
  90949. BABYLON.CSG = CSG;
  90950. })(BABYLON || (BABYLON = {}));
  90951. //# sourceMappingURL=babylon.csg.js.map
  90952. var BABYLON;
  90953. (function (BABYLON) {
  90954. /**
  90955. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  90956. * It controls one of the indiviual texture used in the effect.
  90957. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90958. */
  90959. var LensFlare = /** @class */ (function () {
  90960. /**
  90961. * Instantiates a new Lens Flare.
  90962. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  90963. * It controls one of the indiviual texture used in the effect.
  90964. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90965. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  90966. * @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.
  90967. * @param color Define the lens color
  90968. * @param imgUrl Define the lens texture url
  90969. * @param system Define the `lensFlareSystem` this flare is part of
  90970. */
  90971. function LensFlare(
  90972. /**
  90973. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  90974. */
  90975. size,
  90976. /**
  90977. * 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.
  90978. */
  90979. position, color, imgUrl, system) {
  90980. this.size = size;
  90981. this.position = position;
  90982. /**
  90983. * Define the alpha mode to render this particular lens.
  90984. */
  90985. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  90986. this.color = color || new BABYLON.Color3(1, 1, 1);
  90987. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  90988. this._system = system;
  90989. system.lensFlares.push(this);
  90990. }
  90991. /**
  90992. * Creates a new Lens Flare.
  90993. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  90994. * It controls one of the indiviual texture used in the effect.
  90995. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90996. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  90997. * @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.
  90998. * @param color Define the lens color
  90999. * @param imgUrl Define the lens texture url
  91000. * @param system Define the `lensFlareSystem` this flare is part of
  91001. * @returns The newly created Lens Flare
  91002. */
  91003. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  91004. return new LensFlare(size, position, color, imgUrl, system);
  91005. };
  91006. /**
  91007. * Dispose and release the lens flare with its associated resources.
  91008. */
  91009. LensFlare.prototype.dispose = function () {
  91010. if (this.texture) {
  91011. this.texture.dispose();
  91012. }
  91013. // Remove from scene
  91014. var index = this._system.lensFlares.indexOf(this);
  91015. this._system.lensFlares.splice(index, 1);
  91016. };
  91017. ;
  91018. return LensFlare;
  91019. }());
  91020. BABYLON.LensFlare = LensFlare;
  91021. })(BABYLON || (BABYLON = {}));
  91022. //# sourceMappingURL=babylon.lensFlare.js.map
  91023. var BABYLON;
  91024. (function (BABYLON) {
  91025. // Adds the parser to the scene parsers.
  91026. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  91027. // Lens flares
  91028. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  91029. if (!container.lensFlareSystems) {
  91030. container.lensFlareSystems = new Array();
  91031. }
  91032. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  91033. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  91034. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  91035. container.lensFlareSystems.push(lf);
  91036. }
  91037. }
  91038. });
  91039. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  91040. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  91041. if (this.lensFlareSystems[index].name === name) {
  91042. return this.lensFlareSystems[index];
  91043. }
  91044. }
  91045. return null;
  91046. };
  91047. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  91048. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  91049. if (this.lensFlareSystems[index].id === id) {
  91050. return this.lensFlareSystems[index];
  91051. }
  91052. }
  91053. return null;
  91054. };
  91055. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  91056. var index = this.lensFlareSystems.indexOf(toRemove);
  91057. if (index !== -1) {
  91058. this.lensFlareSystems.splice(index, 1);
  91059. }
  91060. return index;
  91061. };
  91062. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  91063. this.lensFlareSystems.push(newLensFlareSystem);
  91064. };
  91065. /**
  91066. * Defines the lens flare scene component responsible to manage any lens flares
  91067. * in a given scene.
  91068. */
  91069. var LensFlareSystemSceneComponent = /** @class */ (function () {
  91070. /**
  91071. * Creates a new instance of the component for the given scene
  91072. * @param scene Defines the scene to register the component in
  91073. */
  91074. function LensFlareSystemSceneComponent(scene) {
  91075. /**
  91076. * The component name helpfull to identify the component in the list of scene components.
  91077. */
  91078. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  91079. this.scene = scene;
  91080. scene.lensFlareSystems = new Array();
  91081. }
  91082. /**
  91083. * Registers the component in a given scene
  91084. */
  91085. LensFlareSystemSceneComponent.prototype.register = function () {
  91086. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  91087. };
  91088. /**
  91089. * Rebuilds the elements related to this component in case of
  91090. * context lost for instance.
  91091. */
  91092. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  91093. // Nothing to do for lens flare
  91094. };
  91095. /**
  91096. * Adds all the element from the container to the scene
  91097. * @param container the container holding the elements
  91098. */
  91099. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  91100. var _this = this;
  91101. if (!container.lensFlareSystems) {
  91102. return;
  91103. }
  91104. container.lensFlareSystems.forEach(function (o) {
  91105. _this.scene.addLensFlareSystem(o);
  91106. });
  91107. };
  91108. /**
  91109. * Removes all the elements in the container from the scene
  91110. * @param container contains the elements to remove
  91111. */
  91112. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  91113. var _this = this;
  91114. if (!container.lensFlareSystems) {
  91115. return;
  91116. }
  91117. container.lensFlareSystems.forEach(function (o) {
  91118. _this.scene.removeLensFlareSystem(o);
  91119. });
  91120. };
  91121. /**
  91122. * Serializes the component data to the specified json object
  91123. * @param serializationObject The object to serialize to
  91124. */
  91125. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  91126. // Lens flares
  91127. serializationObject.lensFlareSystems = [];
  91128. var lensFlareSystems = this.scene.lensFlareSystems;
  91129. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  91130. var lensFlareSystem = lensFlareSystems_1[_i];
  91131. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  91132. }
  91133. };
  91134. /**
  91135. * Disposes the component and the associated ressources.
  91136. */
  91137. LensFlareSystemSceneComponent.prototype.dispose = function () {
  91138. var lensFlareSystems = this.scene.lensFlareSystems;
  91139. while (lensFlareSystems.length) {
  91140. lensFlareSystems[0].dispose();
  91141. }
  91142. };
  91143. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  91144. // Lens flares
  91145. if (this.scene.lensFlaresEnabled) {
  91146. var lensFlareSystems = this.scene.lensFlareSystems;
  91147. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  91148. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  91149. var lensFlareSystem = lensFlareSystems_2[_i];
  91150. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  91151. lensFlareSystem.render();
  91152. }
  91153. }
  91154. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  91155. }
  91156. };
  91157. return LensFlareSystemSceneComponent;
  91158. }());
  91159. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  91160. })(BABYLON || (BABYLON = {}));
  91161. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  91162. var BABYLON;
  91163. (function (BABYLON) {
  91164. /**
  91165. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  91166. * It is usually composed of several `BABYLON.lensFlare`.
  91167. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  91168. */
  91169. var LensFlareSystem = /** @class */ (function () {
  91170. /**
  91171. * Instantiates a lens flare system.
  91172. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  91173. * It is usually composed of several `BABYLON.lensFlare`.
  91174. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  91175. * @param name Define the name of the lens flare system in the scene
  91176. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  91177. * @param scene Define the scene the lens flare system belongs to
  91178. */
  91179. function LensFlareSystem(
  91180. /**
  91181. * Define the name of the lens flare system
  91182. */
  91183. name, emitter, scene) {
  91184. this.name = name;
  91185. /**
  91186. * List of lens flares used in this system.
  91187. */
  91188. this.lensFlares = new Array();
  91189. /**
  91190. * Define a limit from the border the lens flare can be visible.
  91191. */
  91192. this.borderLimit = 300;
  91193. /**
  91194. * Define a viewport border we do not want to see the lens flare in.
  91195. */
  91196. this.viewportBorder = 0;
  91197. /**
  91198. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  91199. */
  91200. this.layerMask = 0x0FFFFFFF;
  91201. this._vertexBuffers = {};
  91202. this._isEnabled = true;
  91203. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91204. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  91205. if (!component) {
  91206. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  91207. scene._addComponent(component);
  91208. }
  91209. this._emitter = emitter;
  91210. this.id = name;
  91211. scene.lensFlareSystems.push(this);
  91212. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  91213. var engine = scene.getEngine();
  91214. // VBO
  91215. var vertices = [];
  91216. vertices.push(1, 1);
  91217. vertices.push(-1, 1);
  91218. vertices.push(-1, -1);
  91219. vertices.push(1, -1);
  91220. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91221. // Indices
  91222. var indices = [];
  91223. indices.push(0);
  91224. indices.push(1);
  91225. indices.push(2);
  91226. indices.push(0);
  91227. indices.push(2);
  91228. indices.push(3);
  91229. this._indexBuffer = engine.createIndexBuffer(indices);
  91230. // Effects
  91231. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  91232. }
  91233. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  91234. /**
  91235. * Define if the lens flare system is enabled.
  91236. */
  91237. get: function () {
  91238. return this._isEnabled;
  91239. },
  91240. set: function (value) {
  91241. this._isEnabled = value;
  91242. },
  91243. enumerable: true,
  91244. configurable: true
  91245. });
  91246. /**
  91247. * Get the scene the effects belongs to.
  91248. * @returns the scene holding the lens flare system
  91249. */
  91250. LensFlareSystem.prototype.getScene = function () {
  91251. return this._scene;
  91252. };
  91253. /**
  91254. * Get the emitter of the lens flare system.
  91255. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  91256. * @returns the emitter of the lens flare system
  91257. */
  91258. LensFlareSystem.prototype.getEmitter = function () {
  91259. return this._emitter;
  91260. };
  91261. /**
  91262. * Set the emitter of the lens flare system.
  91263. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  91264. * @param newEmitter Define the new emitter of the system
  91265. */
  91266. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  91267. this._emitter = newEmitter;
  91268. };
  91269. /**
  91270. * Get the lens flare system emitter position.
  91271. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  91272. * @returns the position
  91273. */
  91274. LensFlareSystem.prototype.getEmitterPosition = function () {
  91275. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  91276. };
  91277. /**
  91278. * @hidden
  91279. */
  91280. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  91281. var position = this.getEmitterPosition();
  91282. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  91283. this._positionX = position.x;
  91284. this._positionY = position.y;
  91285. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  91286. if (this.viewportBorder > 0) {
  91287. globalViewport.x -= this.viewportBorder;
  91288. globalViewport.y -= this.viewportBorder;
  91289. globalViewport.width += this.viewportBorder * 2;
  91290. globalViewport.height += this.viewportBorder * 2;
  91291. position.x += this.viewportBorder;
  91292. position.y += this.viewportBorder;
  91293. this._positionX += this.viewportBorder;
  91294. this._positionY += this.viewportBorder;
  91295. }
  91296. if (position.z > 0) {
  91297. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  91298. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  91299. return true;
  91300. }
  91301. return true;
  91302. }
  91303. return false;
  91304. };
  91305. /** @hidden */
  91306. LensFlareSystem.prototype._isVisible = function () {
  91307. if (!this._isEnabled || !this._scene.activeCamera) {
  91308. return false;
  91309. }
  91310. var emitterPosition = this.getEmitterPosition();
  91311. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  91312. var distance = direction.length();
  91313. direction.normalize();
  91314. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  91315. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  91316. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  91317. };
  91318. /**
  91319. * @hidden
  91320. */
  91321. LensFlareSystem.prototype.render = function () {
  91322. if (!this._effect.isReady() || !this._scene.activeCamera)
  91323. return false;
  91324. var engine = this._scene.getEngine();
  91325. var viewport = this._scene.activeCamera.viewport;
  91326. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  91327. // Position
  91328. if (!this.computeEffectivePosition(globalViewport)) {
  91329. return false;
  91330. }
  91331. // Visibility
  91332. if (!this._isVisible()) {
  91333. return false;
  91334. }
  91335. // Intensity
  91336. var awayX;
  91337. var awayY;
  91338. if (this._positionX < this.borderLimit + globalViewport.x) {
  91339. awayX = this.borderLimit + globalViewport.x - this._positionX;
  91340. }
  91341. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  91342. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  91343. }
  91344. else {
  91345. awayX = 0;
  91346. }
  91347. if (this._positionY < this.borderLimit + globalViewport.y) {
  91348. awayY = this.borderLimit + globalViewport.y - this._positionY;
  91349. }
  91350. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  91351. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  91352. }
  91353. else {
  91354. awayY = 0;
  91355. }
  91356. var away = (awayX > awayY) ? awayX : awayY;
  91357. away -= this.viewportBorder;
  91358. if (away > this.borderLimit) {
  91359. away = this.borderLimit;
  91360. }
  91361. var intensity = 1.0 - (away / this.borderLimit);
  91362. if (intensity < 0) {
  91363. return false;
  91364. }
  91365. if (intensity > 1.0) {
  91366. intensity = 1.0;
  91367. }
  91368. if (this.viewportBorder > 0) {
  91369. globalViewport.x += this.viewportBorder;
  91370. globalViewport.y += this.viewportBorder;
  91371. globalViewport.width -= this.viewportBorder * 2;
  91372. globalViewport.height -= this.viewportBorder * 2;
  91373. this._positionX -= this.viewportBorder;
  91374. this._positionY -= this.viewportBorder;
  91375. }
  91376. // Position
  91377. var centerX = globalViewport.x + globalViewport.width / 2;
  91378. var centerY = globalViewport.y + globalViewport.height / 2;
  91379. var distX = centerX - this._positionX;
  91380. var distY = centerY - this._positionY;
  91381. // Effects
  91382. engine.enableEffect(this._effect);
  91383. engine.setState(false);
  91384. engine.setDepthBuffer(false);
  91385. // VBOs
  91386. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  91387. // Flares
  91388. for (var index = 0; index < this.lensFlares.length; index++) {
  91389. var flare = this.lensFlares[index];
  91390. engine.setAlphaMode(flare.alphaMode);
  91391. var x = centerX - (distX * flare.position);
  91392. var y = centerY - (distY * flare.position);
  91393. var cw = flare.size;
  91394. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  91395. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  91396. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  91397. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  91398. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  91399. // Texture
  91400. this._effect.setTexture("textureSampler", flare.texture);
  91401. // Color
  91402. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  91403. // Draw order
  91404. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91405. }
  91406. engine.setDepthBuffer(true);
  91407. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  91408. return true;
  91409. };
  91410. /**
  91411. * Dispose and release the lens flare with its associated resources.
  91412. */
  91413. LensFlareSystem.prototype.dispose = function () {
  91414. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91415. if (vertexBuffer) {
  91416. vertexBuffer.dispose();
  91417. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91418. }
  91419. if (this._indexBuffer) {
  91420. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91421. this._indexBuffer = null;
  91422. }
  91423. while (this.lensFlares.length) {
  91424. this.lensFlares[0].dispose();
  91425. }
  91426. // Remove from scene
  91427. var index = this._scene.lensFlareSystems.indexOf(this);
  91428. this._scene.lensFlareSystems.splice(index, 1);
  91429. };
  91430. /**
  91431. * Parse a lens flare system from a JSON repressentation
  91432. * @param parsedLensFlareSystem Define the JSON to parse
  91433. * @param scene Define the scene the parsed system should be instantiated in
  91434. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  91435. * @returns the parsed system
  91436. */
  91437. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  91438. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  91439. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  91440. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  91441. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  91442. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  91443. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  91444. var parsedFlare = parsedLensFlareSystem.flares[index];
  91445. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  91446. }
  91447. return lensFlareSystem;
  91448. };
  91449. /**
  91450. * Serialize the current Lens Flare System into a JSON representation.
  91451. * @returns the serialized JSON
  91452. */
  91453. LensFlareSystem.prototype.serialize = function () {
  91454. var serializationObject = {};
  91455. serializationObject.id = this.id;
  91456. serializationObject.name = this.name;
  91457. serializationObject.emitterId = this.getEmitter().id;
  91458. serializationObject.borderLimit = this.borderLimit;
  91459. serializationObject.flares = [];
  91460. for (var index = 0; index < this.lensFlares.length; index++) {
  91461. var flare = this.lensFlares[index];
  91462. serializationObject.flares.push({
  91463. size: flare.size,
  91464. position: flare.position,
  91465. color: flare.color.asArray(),
  91466. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  91467. });
  91468. }
  91469. return serializationObject;
  91470. };
  91471. return LensFlareSystem;
  91472. }());
  91473. BABYLON.LensFlareSystem = LensFlareSystem;
  91474. })(BABYLON || (BABYLON = {}));
  91475. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  91476. var BABYLON;
  91477. (function (BABYLON) {
  91478. /**
  91479. * This is a holder class for the physics joint created by the physics plugin.
  91480. * It holds a set of functions to control the underlying joint.
  91481. */
  91482. var PhysicsJoint = /** @class */ (function () {
  91483. function PhysicsJoint(type, jointData) {
  91484. this.type = type;
  91485. this.jointData = jointData;
  91486. jointData.nativeParams = jointData.nativeParams || {};
  91487. }
  91488. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  91489. get: function () {
  91490. return this._physicsJoint;
  91491. },
  91492. set: function (newJoint) {
  91493. if (this._physicsJoint) {
  91494. //remove from the wolrd
  91495. }
  91496. this._physicsJoint = newJoint;
  91497. },
  91498. enumerable: true,
  91499. configurable: true
  91500. });
  91501. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  91502. set: function (physicsPlugin) {
  91503. this._physicsPlugin = physicsPlugin;
  91504. },
  91505. enumerable: true,
  91506. configurable: true
  91507. });
  91508. /**
  91509. * Execute a function that is physics-plugin specific.
  91510. * @param {Function} func the function that will be executed.
  91511. * It accepts two parameters: the physics world and the physics joint.
  91512. */
  91513. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  91514. func(this._physicsPlugin.world, this._physicsJoint);
  91515. };
  91516. //TODO check if the native joints are the same
  91517. //Joint Types
  91518. PhysicsJoint.DistanceJoint = 0;
  91519. PhysicsJoint.HingeJoint = 1;
  91520. PhysicsJoint.BallAndSocketJoint = 2;
  91521. PhysicsJoint.WheelJoint = 3;
  91522. PhysicsJoint.SliderJoint = 4;
  91523. //OIMO
  91524. PhysicsJoint.PrismaticJoint = 5;
  91525. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  91526. PhysicsJoint.UniversalJoint = 6;
  91527. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  91528. //Cannon
  91529. //Similar to a Ball-Joint. Different in params
  91530. PhysicsJoint.PointToPointJoint = 8;
  91531. //Cannon only at the moment
  91532. PhysicsJoint.SpringJoint = 9;
  91533. PhysicsJoint.LockJoint = 10;
  91534. return PhysicsJoint;
  91535. }());
  91536. BABYLON.PhysicsJoint = PhysicsJoint;
  91537. /**
  91538. * A class representing a physics distance joint.
  91539. */
  91540. var DistanceJoint = /** @class */ (function (_super) {
  91541. __extends(DistanceJoint, _super);
  91542. function DistanceJoint(jointData) {
  91543. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  91544. }
  91545. /**
  91546. * Update the predefined distance.
  91547. */
  91548. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  91549. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  91550. };
  91551. return DistanceJoint;
  91552. }(PhysicsJoint));
  91553. BABYLON.DistanceJoint = DistanceJoint;
  91554. var MotorEnabledJoint = /** @class */ (function (_super) {
  91555. __extends(MotorEnabledJoint, _super);
  91556. function MotorEnabledJoint(type, jointData) {
  91557. return _super.call(this, type, jointData) || this;
  91558. }
  91559. /**
  91560. * Set the motor values.
  91561. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91562. * @param {number} force the force to apply
  91563. * @param {number} maxForce max force for this motor.
  91564. */
  91565. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  91566. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  91567. };
  91568. /**
  91569. * Set the motor's limits.
  91570. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91571. */
  91572. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  91573. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  91574. };
  91575. return MotorEnabledJoint;
  91576. }(PhysicsJoint));
  91577. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  91578. /**
  91579. * This class represents a single hinge physics joint
  91580. */
  91581. var HingeJoint = /** @class */ (function (_super) {
  91582. __extends(HingeJoint, _super);
  91583. function HingeJoint(jointData) {
  91584. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  91585. }
  91586. /**
  91587. * Set the motor values.
  91588. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91589. * @param {number} force the force to apply
  91590. * @param {number} maxForce max force for this motor.
  91591. */
  91592. HingeJoint.prototype.setMotor = function (force, maxForce) {
  91593. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  91594. };
  91595. /**
  91596. * Set the motor's limits.
  91597. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91598. */
  91599. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  91600. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  91601. };
  91602. return HingeJoint;
  91603. }(MotorEnabledJoint));
  91604. BABYLON.HingeJoint = HingeJoint;
  91605. /**
  91606. * This class represents a dual hinge physics joint (same as wheel joint)
  91607. */
  91608. var Hinge2Joint = /** @class */ (function (_super) {
  91609. __extends(Hinge2Joint, _super);
  91610. function Hinge2Joint(jointData) {
  91611. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  91612. }
  91613. /**
  91614. * Set the motor values.
  91615. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91616. * @param {number} force the force to apply
  91617. * @param {number} maxForce max force for this motor.
  91618. * @param {motorIndex} the motor's index, 0 or 1.
  91619. */
  91620. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  91621. if (motorIndex === void 0) { motorIndex = 0; }
  91622. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  91623. };
  91624. /**
  91625. * Set the motor limits.
  91626. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91627. * @param {number} upperLimit the upper limit
  91628. * @param {number} lowerLimit lower limit
  91629. * @param {motorIndex} the motor's index, 0 or 1.
  91630. */
  91631. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  91632. if (motorIndex === void 0) { motorIndex = 0; }
  91633. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  91634. };
  91635. return Hinge2Joint;
  91636. }(MotorEnabledJoint));
  91637. BABYLON.Hinge2Joint = Hinge2Joint;
  91638. })(BABYLON || (BABYLON = {}));
  91639. //# sourceMappingURL=babylon.physicsJoint.js.map
  91640. var BABYLON;
  91641. (function (BABYLON) {
  91642. var PhysicsImpostor = /** @class */ (function () {
  91643. function PhysicsImpostor(object, type, _options, _scene) {
  91644. if (_options === void 0) { _options = { mass: 0 }; }
  91645. var _this = this;
  91646. this.object = object;
  91647. this.type = type;
  91648. this._options = _options;
  91649. this._scene = _scene;
  91650. this._bodyUpdateRequired = false;
  91651. this._onBeforePhysicsStepCallbacks = new Array();
  91652. this._onAfterPhysicsStepCallbacks = new Array();
  91653. this._onPhysicsCollideCallbacks = [];
  91654. this._deltaPosition = BABYLON.Vector3.Zero();
  91655. this._isDisposed = false;
  91656. //temp variables for parent rotation calculations
  91657. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  91658. this._tmpQuat = new BABYLON.Quaternion();
  91659. this._tmpQuat2 = new BABYLON.Quaternion();
  91660. /**
  91661. * this function is executed by the physics engine.
  91662. */
  91663. this.beforeStep = function () {
  91664. if (!_this._physicsEngine) {
  91665. return;
  91666. }
  91667. _this.object.translate(_this._deltaPosition, -1);
  91668. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  91669. _this.object.computeWorldMatrix(false);
  91670. if (_this.object.parent && _this.object.rotationQuaternion) {
  91671. _this.getParentsRotation();
  91672. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  91673. }
  91674. else {
  91675. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  91676. }
  91677. if (!_this._options.disableBidirectionalTransformation) {
  91678. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  91679. }
  91680. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  91681. func(_this);
  91682. });
  91683. };
  91684. /**
  91685. * this function is executed by the physics engine.
  91686. */
  91687. this.afterStep = function () {
  91688. if (!_this._physicsEngine) {
  91689. return;
  91690. }
  91691. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  91692. func(_this);
  91693. });
  91694. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  91695. // object has now its world rotation. needs to be converted to local.
  91696. if (_this.object.parent && _this.object.rotationQuaternion) {
  91697. _this.getParentsRotation();
  91698. _this._tmpQuat.conjugateInPlace();
  91699. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  91700. }
  91701. // take the position set and make it the absolute position of this object.
  91702. _this.object.setAbsolutePosition(_this.object.position);
  91703. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  91704. _this.object.translate(_this._deltaPosition, 1);
  91705. };
  91706. /**
  91707. * Legacy collision detection event support
  91708. */
  91709. this.onCollideEvent = null;
  91710. //event and body object due to cannon's event-based architecture.
  91711. this.onCollide = function (e) {
  91712. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  91713. return;
  91714. }
  91715. if (!_this._physicsEngine) {
  91716. return;
  91717. }
  91718. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  91719. if (otherImpostor) {
  91720. // Legacy collision detection event support
  91721. if (_this.onCollideEvent) {
  91722. _this.onCollideEvent(_this, otherImpostor);
  91723. }
  91724. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  91725. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  91726. }).forEach(function (obj) {
  91727. obj.callback(_this, otherImpostor);
  91728. });
  91729. }
  91730. };
  91731. //sanity check!
  91732. if (!this.object) {
  91733. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  91734. return;
  91735. }
  91736. //legacy support for old syntax.
  91737. if (!this._scene && object.getScene) {
  91738. this._scene = object.getScene();
  91739. }
  91740. if (!this._scene) {
  91741. return;
  91742. }
  91743. this._physicsEngine = this._scene.getPhysicsEngine();
  91744. if (!this._physicsEngine) {
  91745. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  91746. }
  91747. else {
  91748. //set the object's quaternion, if not set
  91749. if (!this.object.rotationQuaternion) {
  91750. if (this.object.rotation) {
  91751. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  91752. }
  91753. else {
  91754. this.object.rotationQuaternion = new BABYLON.Quaternion();
  91755. }
  91756. }
  91757. //default options params
  91758. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  91759. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  91760. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  91761. this._joints = [];
  91762. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  91763. if (!this.object.parent || this._options.ignoreParent) {
  91764. this._init();
  91765. }
  91766. else if (this.object.parent.physicsImpostor) {
  91767. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  91768. }
  91769. }
  91770. }
  91771. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  91772. get: function () {
  91773. return this._isDisposed;
  91774. },
  91775. enumerable: true,
  91776. configurable: true
  91777. });
  91778. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  91779. get: function () {
  91780. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  91781. },
  91782. set: function (value) {
  91783. this.setMass(value);
  91784. },
  91785. enumerable: true,
  91786. configurable: true
  91787. });
  91788. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  91789. get: function () {
  91790. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  91791. },
  91792. set: function (value) {
  91793. if (!this._physicsEngine) {
  91794. return;
  91795. }
  91796. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  91797. },
  91798. enumerable: true,
  91799. configurable: true
  91800. });
  91801. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  91802. get: function () {
  91803. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  91804. },
  91805. set: function (value) {
  91806. if (!this._physicsEngine) {
  91807. return;
  91808. }
  91809. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  91810. },
  91811. enumerable: true,
  91812. configurable: true
  91813. });
  91814. /**
  91815. * This function will completly initialize this impostor.
  91816. * It will create a new body - but only if this mesh has no parent.
  91817. * If it has, this impostor will not be used other than to define the impostor
  91818. * of the child mesh.
  91819. * @hidden
  91820. */
  91821. PhysicsImpostor.prototype._init = function () {
  91822. if (!this._physicsEngine) {
  91823. return;
  91824. }
  91825. this._physicsEngine.removeImpostor(this);
  91826. this.physicsBody = null;
  91827. this._parent = this._parent || this._getPhysicsParent();
  91828. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  91829. this._physicsEngine.addImpostor(this);
  91830. }
  91831. };
  91832. PhysicsImpostor.prototype._getPhysicsParent = function () {
  91833. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  91834. var parentMesh = this.object.parent;
  91835. return parentMesh.physicsImpostor;
  91836. }
  91837. return null;
  91838. };
  91839. /**
  91840. * Should a new body be generated.
  91841. */
  91842. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  91843. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  91844. };
  91845. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  91846. this.forceUpdate();
  91847. };
  91848. /**
  91849. * Force a regeneration of this or the parent's impostor's body.
  91850. * Use under cautious - This will remove all joints already implemented.
  91851. */
  91852. PhysicsImpostor.prototype.forceUpdate = function () {
  91853. this._init();
  91854. if (this.parent && !this._options.ignoreParent) {
  91855. this.parent.forceUpdate();
  91856. }
  91857. };
  91858. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  91859. /*public get mesh(): AbstractMesh {
  91860. return this._mesh;
  91861. }*/
  91862. /**
  91863. * Gets the body that holds this impostor. Either its own, or its parent.
  91864. */
  91865. get: function () {
  91866. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  91867. },
  91868. /**
  91869. * Set the physics body. Used mainly by the physics engine/plugin
  91870. */
  91871. set: function (physicsBody) {
  91872. if (this._physicsBody && this._physicsEngine) {
  91873. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  91874. }
  91875. this._physicsBody = physicsBody;
  91876. this.resetUpdateFlags();
  91877. },
  91878. enumerable: true,
  91879. configurable: true
  91880. });
  91881. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  91882. get: function () {
  91883. return !this._options.ignoreParent && this._parent ? this._parent : null;
  91884. },
  91885. set: function (value) {
  91886. this._parent = value;
  91887. },
  91888. enumerable: true,
  91889. configurable: true
  91890. });
  91891. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  91892. this._bodyUpdateRequired = false;
  91893. };
  91894. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  91895. if (this.object.getBoundingInfo) {
  91896. var q = this.object.rotationQuaternion;
  91897. //reset rotation
  91898. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  91899. //calculate the world matrix with no rotation
  91900. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  91901. var boundingInfo = this.object.getBoundingInfo();
  91902. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  91903. //bring back the rotation
  91904. this.object.rotationQuaternion = q;
  91905. //calculate the world matrix with the new rotation
  91906. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  91907. return size;
  91908. }
  91909. else {
  91910. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  91911. }
  91912. };
  91913. PhysicsImpostor.prototype.getObjectCenter = function () {
  91914. if (this.object.getBoundingInfo) {
  91915. var boundingInfo = this.object.getBoundingInfo();
  91916. return boundingInfo.boundingBox.centerWorld;
  91917. }
  91918. else {
  91919. return this.object.position;
  91920. }
  91921. };
  91922. /**
  91923. * Get a specific parametes from the options parameter.
  91924. */
  91925. PhysicsImpostor.prototype.getParam = function (paramName) {
  91926. return this._options[paramName];
  91927. };
  91928. /**
  91929. * Sets a specific parameter in the options given to the physics plugin
  91930. */
  91931. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  91932. this._options[paramName] = value;
  91933. this._bodyUpdateRequired = true;
  91934. };
  91935. /**
  91936. * Specifically change the body's mass option. Won't recreate the physics body object
  91937. */
  91938. PhysicsImpostor.prototype.setMass = function (mass) {
  91939. if (this.getParam("mass") !== mass) {
  91940. this.setParam("mass", mass);
  91941. }
  91942. if (this._physicsEngine) {
  91943. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  91944. }
  91945. };
  91946. PhysicsImpostor.prototype.getLinearVelocity = function () {
  91947. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  91948. };
  91949. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  91950. if (this._physicsEngine) {
  91951. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  91952. }
  91953. };
  91954. PhysicsImpostor.prototype.getAngularVelocity = function () {
  91955. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  91956. };
  91957. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  91958. if (this._physicsEngine) {
  91959. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  91960. }
  91961. };
  91962. /**
  91963. * Execute a function with the physics plugin native code.
  91964. * Provide a function the will have two variables - the world object and the physics body object.
  91965. */
  91966. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  91967. if (this._physicsEngine) {
  91968. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  91969. }
  91970. };
  91971. /**
  91972. * Register a function that will be executed before the physics world is stepping forward.
  91973. */
  91974. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  91975. this._onBeforePhysicsStepCallbacks.push(func);
  91976. };
  91977. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  91978. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  91979. if (index > -1) {
  91980. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  91981. }
  91982. else {
  91983. BABYLON.Tools.Warn("Function to remove was not found");
  91984. }
  91985. };
  91986. /**
  91987. * Register a function that will be executed after the physics step
  91988. */
  91989. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  91990. this._onAfterPhysicsStepCallbacks.push(func);
  91991. };
  91992. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  91993. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  91994. if (index > -1) {
  91995. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  91996. }
  91997. else {
  91998. BABYLON.Tools.Warn("Function to remove was not found");
  91999. }
  92000. };
  92001. /**
  92002. * register a function that will be executed when this impostor collides against a different body.
  92003. */
  92004. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  92005. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  92006. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  92007. };
  92008. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  92009. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  92010. var index = -1;
  92011. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  92012. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  92013. // chcek the arrays match
  92014. var sameList = cbDef.otherImpostors.every(function (impostor) {
  92015. return collidedAgainstList.indexOf(impostor) > -1;
  92016. });
  92017. if (sameList) {
  92018. index = idx;
  92019. }
  92020. return sameList;
  92021. }
  92022. return false;
  92023. });
  92024. if (found) {
  92025. this._onPhysicsCollideCallbacks.splice(index, 1);
  92026. }
  92027. else {
  92028. BABYLON.Tools.Warn("Function to remove was not found");
  92029. }
  92030. };
  92031. PhysicsImpostor.prototype.getParentsRotation = function () {
  92032. var parent = this.object.parent;
  92033. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  92034. while (parent) {
  92035. if (parent.rotationQuaternion) {
  92036. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  92037. }
  92038. else {
  92039. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  92040. }
  92041. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  92042. parent = parent.parent;
  92043. }
  92044. return this._tmpQuat;
  92045. };
  92046. /**
  92047. * Apply a force
  92048. */
  92049. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  92050. if (this._physicsEngine) {
  92051. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  92052. }
  92053. return this;
  92054. };
  92055. /**
  92056. * Apply an impulse
  92057. */
  92058. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  92059. if (this._physicsEngine) {
  92060. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  92061. }
  92062. return this;
  92063. };
  92064. /**
  92065. * A help function to create a joint.
  92066. */
  92067. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  92068. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  92069. this.addJoint(otherImpostor, joint);
  92070. return this;
  92071. };
  92072. /**
  92073. * Add a joint to this impostor with a different impostor.
  92074. */
  92075. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  92076. this._joints.push({
  92077. otherImpostor: otherImpostor,
  92078. joint: joint
  92079. });
  92080. if (this._physicsEngine) {
  92081. this._physicsEngine.addJoint(this, otherImpostor, joint);
  92082. }
  92083. return this;
  92084. };
  92085. /**
  92086. * Will keep this body still, in a sleep mode.
  92087. */
  92088. PhysicsImpostor.prototype.sleep = function () {
  92089. if (this._physicsEngine) {
  92090. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  92091. }
  92092. return this;
  92093. };
  92094. /**
  92095. * Wake the body up.
  92096. */
  92097. PhysicsImpostor.prototype.wakeUp = function () {
  92098. if (this._physicsEngine) {
  92099. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  92100. }
  92101. return this;
  92102. };
  92103. PhysicsImpostor.prototype.clone = function (newObject) {
  92104. if (!newObject)
  92105. return null;
  92106. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  92107. };
  92108. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  92109. var _this = this;
  92110. //no dispose if no physics engine is available.
  92111. if (!this._physicsEngine) {
  92112. return;
  92113. }
  92114. this._joints.forEach(function (j) {
  92115. if (_this._physicsEngine) {
  92116. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  92117. }
  92118. });
  92119. //dispose the physics body
  92120. this._physicsEngine.removeImpostor(this);
  92121. if (this.parent) {
  92122. this.parent.forceUpdate();
  92123. }
  92124. else {
  92125. /*this._object.getChildMeshes().forEach(function(mesh) {
  92126. if (mesh.physicsImpostor) {
  92127. if (disposeChildren) {
  92128. mesh.physicsImpostor.dispose();
  92129. mesh.physicsImpostor = null;
  92130. }
  92131. }
  92132. })*/
  92133. }
  92134. this._isDisposed = true;
  92135. };
  92136. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  92137. this._deltaPosition.copyFrom(position);
  92138. };
  92139. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  92140. if (!this._deltaRotation) {
  92141. this._deltaRotation = new BABYLON.Quaternion();
  92142. }
  92143. this._deltaRotation.copyFrom(rotation);
  92144. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  92145. };
  92146. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  92147. if (this._physicsEngine) {
  92148. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  92149. }
  92150. return this;
  92151. };
  92152. PhysicsImpostor.prototype.getRadius = function () {
  92153. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  92154. };
  92155. /**
  92156. * Sync a bone with this impostor
  92157. * @param bone The bone to sync to the impostor.
  92158. * @param boneMesh The mesh that the bone is influencing.
  92159. * @param jointPivot The pivot of the joint / bone in local space.
  92160. * @param distToJoint Optional distance from the impostor to the joint.
  92161. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  92162. */
  92163. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  92164. var tempVec = PhysicsImpostor._tmpVecs[0];
  92165. var mesh = this.object;
  92166. if (mesh.rotationQuaternion) {
  92167. if (adjustRotation) {
  92168. var tempQuat = PhysicsImpostor._tmpQuat;
  92169. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  92170. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  92171. }
  92172. else {
  92173. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  92174. }
  92175. }
  92176. tempVec.x = 0;
  92177. tempVec.y = 0;
  92178. tempVec.z = 0;
  92179. if (jointPivot) {
  92180. tempVec.x = jointPivot.x;
  92181. tempVec.y = jointPivot.y;
  92182. tempVec.z = jointPivot.z;
  92183. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  92184. if (distToJoint === undefined || distToJoint === null) {
  92185. distToJoint = jointPivot.length();
  92186. }
  92187. tempVec.x *= distToJoint;
  92188. tempVec.y *= distToJoint;
  92189. tempVec.z *= distToJoint;
  92190. }
  92191. if (bone.getParent()) {
  92192. tempVec.addInPlace(mesh.getAbsolutePosition());
  92193. bone.setAbsolutePosition(tempVec, boneMesh);
  92194. }
  92195. else {
  92196. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  92197. boneMesh.position.x -= tempVec.x;
  92198. boneMesh.position.y -= tempVec.y;
  92199. boneMesh.position.z -= tempVec.z;
  92200. }
  92201. };
  92202. /**
  92203. * Sync impostor to a bone
  92204. * @param bone The bone that the impostor will be synced to.
  92205. * @param boneMesh The mesh that the bone is influencing.
  92206. * @param jointPivot The pivot of the joint / bone in local space.
  92207. * @param distToJoint Optional distance from the impostor to the joint.
  92208. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  92209. * @param boneAxis Optional vector3 axis the bone is aligned with
  92210. */
  92211. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  92212. var mesh = this.object;
  92213. if (mesh.rotationQuaternion) {
  92214. if (adjustRotation) {
  92215. var tempQuat = PhysicsImpostor._tmpQuat;
  92216. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  92217. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  92218. }
  92219. else {
  92220. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  92221. }
  92222. }
  92223. var pos = PhysicsImpostor._tmpVecs[0];
  92224. var boneDir = PhysicsImpostor._tmpVecs[1];
  92225. if (!boneAxis) {
  92226. boneAxis = PhysicsImpostor._tmpVecs[2];
  92227. boneAxis.x = 0;
  92228. boneAxis.y = 1;
  92229. boneAxis.z = 0;
  92230. }
  92231. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  92232. bone.getAbsolutePositionToRef(boneMesh, pos);
  92233. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  92234. distToJoint = jointPivot.length();
  92235. }
  92236. if (distToJoint !== undefined && distToJoint !== null) {
  92237. pos.x += boneDir.x * distToJoint;
  92238. pos.y += boneDir.y * distToJoint;
  92239. pos.z += boneDir.z * distToJoint;
  92240. }
  92241. mesh.setAbsolutePosition(pos);
  92242. };
  92243. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  92244. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  92245. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  92246. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  92247. //Impostor types
  92248. PhysicsImpostor.NoImpostor = 0;
  92249. PhysicsImpostor.SphereImpostor = 1;
  92250. PhysicsImpostor.BoxImpostor = 2;
  92251. PhysicsImpostor.PlaneImpostor = 3;
  92252. PhysicsImpostor.MeshImpostor = 4;
  92253. PhysicsImpostor.CylinderImpostor = 7;
  92254. PhysicsImpostor.ParticleImpostor = 8;
  92255. PhysicsImpostor.HeightmapImpostor = 9;
  92256. return PhysicsImpostor;
  92257. }());
  92258. BABYLON.PhysicsImpostor = PhysicsImpostor;
  92259. })(BABYLON || (BABYLON = {}));
  92260. //# sourceMappingURL=babylon.physicsImpostor.js.map
  92261. var BABYLON;
  92262. (function (BABYLON) {
  92263. /**
  92264. * Class used to control physics engine
  92265. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  92266. */
  92267. var PhysicsEngine = /** @class */ (function () {
  92268. /**
  92269. * Creates a new Physics Engine
  92270. * @param gravity defines the gravity vector used by the simulation
  92271. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  92272. */
  92273. function PhysicsEngine(gravity, _physicsPlugin) {
  92274. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  92275. this._physicsPlugin = _physicsPlugin;
  92276. this._impostors = [];
  92277. this._joints = [];
  92278. if (!this._physicsPlugin.isSupported()) {
  92279. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  92280. + "Please make sure it is included.");
  92281. }
  92282. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  92283. this.setGravity(gravity);
  92284. this.setTimeStep();
  92285. }
  92286. /**
  92287. * Sets the gravity vector used by the simulation
  92288. * @param gravity defines the gravity vector to use
  92289. */
  92290. PhysicsEngine.prototype.setGravity = function (gravity) {
  92291. this.gravity = gravity;
  92292. this._physicsPlugin.setGravity(this.gravity);
  92293. };
  92294. /**
  92295. * Set the time step of the physics engine.
  92296. * Default is 1/60.
  92297. * To slow it down, enter 1/600 for example.
  92298. * To speed it up, 1/30
  92299. * @param newTimeStep defines the new timestep to apply to this world.
  92300. */
  92301. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  92302. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  92303. this._physicsPlugin.setTimeStep(newTimeStep);
  92304. };
  92305. /**
  92306. * Get the time step of the physics engine.
  92307. * @returns the current time step
  92308. */
  92309. PhysicsEngine.prototype.getTimeStep = function () {
  92310. return this._physicsPlugin.getTimeStep();
  92311. };
  92312. /**
  92313. * Release all resources
  92314. */
  92315. PhysicsEngine.prototype.dispose = function () {
  92316. this._impostors.forEach(function (impostor) {
  92317. impostor.dispose();
  92318. });
  92319. this._physicsPlugin.dispose();
  92320. };
  92321. /**
  92322. * Gets the name of the current physics plugin
  92323. * @returns the name of the plugin
  92324. */
  92325. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  92326. return this._physicsPlugin.name;
  92327. };
  92328. /**
  92329. * Adding a new impostor for the impostor tracking.
  92330. * This will be done by the impostor itself.
  92331. * @param impostor the impostor to add
  92332. */
  92333. PhysicsEngine.prototype.addImpostor = function (impostor) {
  92334. impostor.uniqueId = this._impostors.push(impostor);
  92335. //if no parent, generate the body
  92336. if (!impostor.parent) {
  92337. this._physicsPlugin.generatePhysicsBody(impostor);
  92338. }
  92339. };
  92340. /**
  92341. * Remove an impostor from the engine.
  92342. * This impostor and its mesh will not longer be updated by the physics engine.
  92343. * @param impostor the impostor to remove
  92344. */
  92345. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  92346. var index = this._impostors.indexOf(impostor);
  92347. if (index > -1) {
  92348. var removed = this._impostors.splice(index, 1);
  92349. //Is it needed?
  92350. if (removed.length) {
  92351. //this will also remove it from the world.
  92352. removed[0].physicsBody = null;
  92353. }
  92354. }
  92355. };
  92356. /**
  92357. * Add a joint to the physics engine
  92358. * @param mainImpostor defines the main impostor to which the joint is added.
  92359. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  92360. * @param joint defines the joint that will connect both impostors.
  92361. */
  92362. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  92363. var impostorJoint = {
  92364. mainImpostor: mainImpostor,
  92365. connectedImpostor: connectedImpostor,
  92366. joint: joint
  92367. };
  92368. joint.physicsPlugin = this._physicsPlugin;
  92369. this._joints.push(impostorJoint);
  92370. this._physicsPlugin.generateJoint(impostorJoint);
  92371. };
  92372. /**
  92373. * Removes a joint from the simulation
  92374. * @param mainImpostor defines the impostor used with the joint
  92375. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  92376. * @param joint defines the joint to remove
  92377. */
  92378. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  92379. var matchingJoints = this._joints.filter(function (impostorJoint) {
  92380. return (impostorJoint.connectedImpostor === connectedImpostor
  92381. && impostorJoint.joint === joint
  92382. && impostorJoint.mainImpostor === mainImpostor);
  92383. });
  92384. if (matchingJoints.length) {
  92385. this._physicsPlugin.removeJoint(matchingJoints[0]);
  92386. //TODO remove it from the list as well
  92387. }
  92388. };
  92389. /**
  92390. * Called by the scene. No need to call it.
  92391. * @param delta defines the timespam between frames
  92392. */
  92393. PhysicsEngine.prototype._step = function (delta) {
  92394. var _this = this;
  92395. //check if any mesh has no body / requires an update
  92396. this._impostors.forEach(function (impostor) {
  92397. if (impostor.isBodyInitRequired()) {
  92398. _this._physicsPlugin.generatePhysicsBody(impostor);
  92399. }
  92400. });
  92401. if (delta > 0.1) {
  92402. delta = 0.1;
  92403. }
  92404. else if (delta <= 0) {
  92405. delta = 1.0 / 60.0;
  92406. }
  92407. this._physicsPlugin.executeStep(delta, this._impostors);
  92408. };
  92409. /**
  92410. * Gets the current plugin used to run the simulation
  92411. * @returns current plugin
  92412. */
  92413. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  92414. return this._physicsPlugin;
  92415. };
  92416. /**
  92417. * Gets the list of physic impostors
  92418. * @returns an array of PhysicsImpostor
  92419. */
  92420. PhysicsEngine.prototype.getImpostors = function () {
  92421. return this._impostors;
  92422. };
  92423. /**
  92424. * Gets the impostor for a physics enabled object
  92425. * @param object defines the object impersonated by the impostor
  92426. * @returns the PhysicsImpostor or null if not found
  92427. */
  92428. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  92429. for (var i = 0; i < this._impostors.length; ++i) {
  92430. if (this._impostors[i].object === object) {
  92431. return this._impostors[i];
  92432. }
  92433. }
  92434. return null;
  92435. };
  92436. /**
  92437. * Gets the impostor for a physics body object
  92438. * @param body defines physics body used by the impostor
  92439. * @returns the PhysicsImpostor or null if not found
  92440. */
  92441. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  92442. for (var i = 0; i < this._impostors.length; ++i) {
  92443. if (this._impostors[i].physicsBody === body) {
  92444. return this._impostors[i];
  92445. }
  92446. }
  92447. return null;
  92448. };
  92449. /**
  92450. * Global value used to control the smallest number supported by the simulation
  92451. */
  92452. PhysicsEngine.Epsilon = 0.001;
  92453. return PhysicsEngine;
  92454. }());
  92455. BABYLON.PhysicsEngine = PhysicsEngine;
  92456. })(BABYLON || (BABYLON = {}));
  92457. //# sourceMappingURL=babylon.physicsEngine.js.map
  92458. var BABYLON;
  92459. (function (BABYLON) {
  92460. var PhysicsHelper = /** @class */ (function () {
  92461. function PhysicsHelper(scene) {
  92462. this._scene = scene;
  92463. this._physicsEngine = this._scene.getPhysicsEngine();
  92464. if (!this._physicsEngine) {
  92465. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  92466. }
  92467. }
  92468. /**
  92469. * @param {Vector3} origin the origin of the explosion
  92470. * @param {number} radius the explosion radius
  92471. * @param {number} strength the explosion strength
  92472. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  92473. */
  92474. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  92475. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  92476. if (!this._physicsEngine) {
  92477. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  92478. return null;
  92479. }
  92480. var impostors = this._physicsEngine.getImpostors();
  92481. if (impostors.length === 0) {
  92482. return null;
  92483. }
  92484. var event = new PhysicsRadialExplosionEvent(this._scene);
  92485. impostors.forEach(function (impostor) {
  92486. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  92487. if (!impostorForceAndContactPoint) {
  92488. return;
  92489. }
  92490. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  92491. });
  92492. event.dispose(false);
  92493. return event;
  92494. };
  92495. /**
  92496. * @param {Vector3} origin the origin of the explosion
  92497. * @param {number} radius the explosion radius
  92498. * @param {number} strength the explosion strength
  92499. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  92500. */
  92501. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  92502. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  92503. if (!this._physicsEngine) {
  92504. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  92505. return null;
  92506. }
  92507. var impostors = this._physicsEngine.getImpostors();
  92508. if (impostors.length === 0) {
  92509. return null;
  92510. }
  92511. var event = new PhysicsRadialExplosionEvent(this._scene);
  92512. impostors.forEach(function (impostor) {
  92513. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  92514. if (!impostorForceAndContactPoint) {
  92515. return;
  92516. }
  92517. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  92518. });
  92519. event.dispose(false);
  92520. return event;
  92521. };
  92522. /**
  92523. * @param {Vector3} origin the origin of the explosion
  92524. * @param {number} radius the explosion radius
  92525. * @param {number} strength the explosion strength
  92526. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  92527. */
  92528. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  92529. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  92530. if (!this._physicsEngine) {
  92531. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  92532. return null;
  92533. }
  92534. var impostors = this._physicsEngine.getImpostors();
  92535. if (impostors.length === 0) {
  92536. return null;
  92537. }
  92538. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  92539. event.dispose(false);
  92540. return event;
  92541. };
  92542. /**
  92543. * @param {Vector3} origin the origin of the updraft
  92544. * @param {number} radius the radius of the updraft
  92545. * @param {number} strength the strength of the updraft
  92546. * @param {number} height the height of the updraft
  92547. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  92548. */
  92549. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  92550. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  92551. if (!this._physicsEngine) {
  92552. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  92553. return null;
  92554. }
  92555. if (this._physicsEngine.getImpostors().length === 0) {
  92556. return null;
  92557. }
  92558. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  92559. event.dispose(false);
  92560. return event;
  92561. };
  92562. /**
  92563. * @param {Vector3} origin the of the vortex
  92564. * @param {number} radius the radius of the vortex
  92565. * @param {number} strength the strength of the vortex
  92566. * @param {number} height the height of the vortex
  92567. */
  92568. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  92569. if (!this._physicsEngine) {
  92570. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  92571. return null;
  92572. }
  92573. if (this._physicsEngine.getImpostors().length === 0) {
  92574. return null;
  92575. }
  92576. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  92577. event.dispose(false);
  92578. return event;
  92579. };
  92580. return PhysicsHelper;
  92581. }());
  92582. BABYLON.PhysicsHelper = PhysicsHelper;
  92583. /***** Radial explosion *****/
  92584. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  92585. function PhysicsRadialExplosionEvent(scene) {
  92586. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  92587. this._rays = [];
  92588. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  92589. this._scene = scene;
  92590. }
  92591. /**
  92592. * Returns the data related to the radial explosion event (sphere & rays).
  92593. * @returns {PhysicsRadialExplosionEventData}
  92594. */
  92595. PhysicsRadialExplosionEvent.prototype.getData = function () {
  92596. this._dataFetched = true;
  92597. return {
  92598. sphere: this._sphere,
  92599. rays: this._rays,
  92600. };
  92601. };
  92602. /**
  92603. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  92604. * @param impostor
  92605. * @param {Vector3} origin the origin of the explosion
  92606. * @param {number} radius the explosion radius
  92607. * @param {number} strength the explosion strength
  92608. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  92609. * @returns {Nullable<PhysicsForceAndContactPoint>}
  92610. */
  92611. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  92612. if (impostor.mass === 0) {
  92613. return null;
  92614. }
  92615. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  92616. return null;
  92617. }
  92618. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  92619. return null;
  92620. }
  92621. var impostorObjectCenter = impostor.getObjectCenter();
  92622. var direction = impostorObjectCenter.subtract(origin);
  92623. var ray = new BABYLON.Ray(origin, direction, radius);
  92624. this._rays.push(ray);
  92625. var hit = ray.intersectsMesh(impostor.object);
  92626. var contactPoint = hit.pickedPoint;
  92627. if (!contactPoint) {
  92628. return null;
  92629. }
  92630. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  92631. if (distanceFromOrigin > radius) {
  92632. return null;
  92633. }
  92634. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  92635. ? strength
  92636. : strength * (1 - (distanceFromOrigin / radius));
  92637. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  92638. return { force: force, contactPoint: contactPoint };
  92639. };
  92640. /**
  92641. * Disposes the sphere.
  92642. * @param {bolean} force
  92643. */
  92644. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  92645. var _this = this;
  92646. if (force === void 0) { force = true; }
  92647. if (force) {
  92648. this._sphere.dispose();
  92649. }
  92650. else {
  92651. setTimeout(function () {
  92652. if (!_this._dataFetched) {
  92653. _this._sphere.dispose();
  92654. }
  92655. }, 0);
  92656. }
  92657. };
  92658. /*** Helpers ***/
  92659. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  92660. if (!this._sphere) {
  92661. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  92662. this._sphere.isVisible = false;
  92663. }
  92664. };
  92665. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  92666. var impostorObject = impostor.object;
  92667. this._prepareSphere();
  92668. this._sphere.position = origin;
  92669. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  92670. this._sphere._updateBoundingInfo();
  92671. this._sphere.computeWorldMatrix(true);
  92672. return this._sphere.intersectsMesh(impostorObject, true);
  92673. };
  92674. return PhysicsRadialExplosionEvent;
  92675. }());
  92676. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  92677. /***** Gravitational Field *****/
  92678. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  92679. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  92680. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  92681. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  92682. this._physicsHelper = physicsHelper;
  92683. this._scene = scene;
  92684. this._origin = origin;
  92685. this._radius = radius;
  92686. this._strength = strength;
  92687. this._falloff = falloff;
  92688. this._tickCallback = this._tick.bind(this);
  92689. }
  92690. /**
  92691. * Returns the data related to the gravitational field event (sphere).
  92692. * @returns {PhysicsGravitationalFieldEventData}
  92693. */
  92694. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  92695. this._dataFetched = true;
  92696. return {
  92697. sphere: this._sphere,
  92698. };
  92699. };
  92700. /**
  92701. * Enables the gravitational field.
  92702. */
  92703. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  92704. this._tickCallback.call(this);
  92705. this._scene.registerBeforeRender(this._tickCallback);
  92706. };
  92707. /**
  92708. * Disables the gravitational field.
  92709. */
  92710. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  92711. this._scene.unregisterBeforeRender(this._tickCallback);
  92712. };
  92713. /**
  92714. * Disposes the sphere.
  92715. * @param {bolean} force
  92716. */
  92717. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  92718. var _this = this;
  92719. if (force === void 0) { force = true; }
  92720. if (force) {
  92721. this._sphere.dispose();
  92722. }
  92723. else {
  92724. setTimeout(function () {
  92725. if (!_this._dataFetched) {
  92726. _this._sphere.dispose();
  92727. }
  92728. }, 0);
  92729. }
  92730. };
  92731. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  92732. // Since the params won't change, we fetch the event only once
  92733. if (this._sphere) {
  92734. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  92735. }
  92736. else {
  92737. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  92738. if (radialExplosionEvent) {
  92739. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  92740. }
  92741. }
  92742. };
  92743. return PhysicsGravitationalFieldEvent;
  92744. }());
  92745. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  92746. /***** Updraft *****/
  92747. var PhysicsUpdraftEvent = /** @class */ (function () {
  92748. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  92749. this._scene = _scene;
  92750. this._origin = _origin;
  92751. this._radius = _radius;
  92752. this._strength = _strength;
  92753. this._height = _height;
  92754. this._updraftMode = _updraftMode;
  92755. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  92756. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  92757. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  92758. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  92759. this._physicsEngine = this._scene.getPhysicsEngine();
  92760. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  92761. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  92762. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  92763. this._originDirection = this._origin.subtract(this._originTop).normalize();
  92764. }
  92765. this._tickCallback = this._tick.bind(this);
  92766. }
  92767. /**
  92768. * Returns the data related to the updraft event (cylinder).
  92769. * @returns {PhysicsUpdraftEventData}
  92770. */
  92771. PhysicsUpdraftEvent.prototype.getData = function () {
  92772. this._dataFetched = true;
  92773. return {
  92774. cylinder: this._cylinder,
  92775. };
  92776. };
  92777. /**
  92778. * Enables the updraft.
  92779. */
  92780. PhysicsUpdraftEvent.prototype.enable = function () {
  92781. this._tickCallback.call(this);
  92782. this._scene.registerBeforeRender(this._tickCallback);
  92783. };
  92784. /**
  92785. * Disables the cortex.
  92786. */
  92787. PhysicsUpdraftEvent.prototype.disable = function () {
  92788. this._scene.unregisterBeforeRender(this._tickCallback);
  92789. };
  92790. /**
  92791. * Disposes the sphere.
  92792. * @param {bolean} force
  92793. */
  92794. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  92795. var _this = this;
  92796. if (force === void 0) { force = true; }
  92797. if (force) {
  92798. this._cylinder.dispose();
  92799. }
  92800. else {
  92801. setTimeout(function () {
  92802. if (!_this._dataFetched) {
  92803. _this._cylinder.dispose();
  92804. }
  92805. }, 0);
  92806. }
  92807. };
  92808. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  92809. if (impostor.mass === 0) {
  92810. return null;
  92811. }
  92812. if (!this._intersectsWithCylinder(impostor)) {
  92813. return null;
  92814. }
  92815. var impostorObjectCenter = impostor.getObjectCenter();
  92816. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  92817. var direction = this._originDirection;
  92818. }
  92819. else {
  92820. var direction = impostorObjectCenter.subtract(this._originTop);
  92821. }
  92822. var multiplier = this._strength * -1;
  92823. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  92824. return { force: force, contactPoint: impostorObjectCenter };
  92825. };
  92826. PhysicsUpdraftEvent.prototype._tick = function () {
  92827. var _this = this;
  92828. this._physicsEngine.getImpostors().forEach(function (impostor) {
  92829. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  92830. if (!impostorForceAndContactPoint) {
  92831. return;
  92832. }
  92833. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  92834. });
  92835. };
  92836. /*** Helpers ***/
  92837. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  92838. if (!this._cylinder) {
  92839. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  92840. height: this._height,
  92841. diameter: this._radius * 2,
  92842. }, this._scene);
  92843. this._cylinder.isVisible = false;
  92844. }
  92845. };
  92846. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  92847. var impostorObject = impostor.object;
  92848. this._prepareCylinder();
  92849. this._cylinder.position = this._cylinderPosition;
  92850. return this._cylinder.intersectsMesh(impostorObject, true);
  92851. };
  92852. return PhysicsUpdraftEvent;
  92853. }());
  92854. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  92855. /***** Vortex *****/
  92856. var PhysicsVortexEvent = /** @class */ (function () {
  92857. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  92858. this._scene = _scene;
  92859. this._origin = _origin;
  92860. this._radius = _radius;
  92861. this._strength = _strength;
  92862. this._height = _height;
  92863. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  92864. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  92865. this._updraftMultiplier = 0.02;
  92866. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  92867. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  92868. this._physicsEngine = this._scene.getPhysicsEngine();
  92869. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  92870. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  92871. this._tickCallback = this._tick.bind(this);
  92872. }
  92873. /**
  92874. * Returns the data related to the vortex event (cylinder).
  92875. * @returns {PhysicsVortexEventData}
  92876. */
  92877. PhysicsVortexEvent.prototype.getData = function () {
  92878. this._dataFetched = true;
  92879. return {
  92880. cylinder: this._cylinder,
  92881. };
  92882. };
  92883. /**
  92884. * Enables the vortex.
  92885. */
  92886. PhysicsVortexEvent.prototype.enable = function () {
  92887. this._tickCallback.call(this);
  92888. this._scene.registerBeforeRender(this._tickCallback);
  92889. };
  92890. /**
  92891. * Disables the cortex.
  92892. */
  92893. PhysicsVortexEvent.prototype.disable = function () {
  92894. this._scene.unregisterBeforeRender(this._tickCallback);
  92895. };
  92896. /**
  92897. * Disposes the sphere.
  92898. * @param {bolean} force
  92899. */
  92900. PhysicsVortexEvent.prototype.dispose = function (force) {
  92901. var _this = this;
  92902. if (force === void 0) { force = true; }
  92903. if (force) {
  92904. this._cylinder.dispose();
  92905. }
  92906. else {
  92907. setTimeout(function () {
  92908. if (!_this._dataFetched) {
  92909. _this._cylinder.dispose();
  92910. }
  92911. }, 0);
  92912. }
  92913. };
  92914. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  92915. if (impostor.mass === 0) {
  92916. return null;
  92917. }
  92918. if (!this._intersectsWithCylinder(impostor)) {
  92919. return null;
  92920. }
  92921. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  92922. return null;
  92923. }
  92924. var impostorObjectCenter = impostor.getObjectCenter();
  92925. 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)
  92926. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  92927. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  92928. var hit = ray.intersectsMesh(impostor.object);
  92929. var contactPoint = hit.pickedPoint;
  92930. if (!contactPoint) {
  92931. return null;
  92932. }
  92933. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  92934. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  92935. var directionToOrigin = contactPoint.normalize();
  92936. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  92937. directionToOrigin = directionToOrigin.negate();
  92938. }
  92939. // TODO: find a more physically based solution
  92940. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  92941. var forceX = directionToOrigin.x * this._strength / 8;
  92942. var forceY = directionToOrigin.y * this._updraftMultiplier;
  92943. var forceZ = directionToOrigin.z * this._strength / 8;
  92944. }
  92945. else {
  92946. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  92947. var forceY = this._originTop.y * this._updraftMultiplier;
  92948. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  92949. }
  92950. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  92951. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  92952. return { force: force, contactPoint: impostorObjectCenter };
  92953. };
  92954. PhysicsVortexEvent.prototype._tick = function () {
  92955. var _this = this;
  92956. this._physicsEngine.getImpostors().forEach(function (impostor) {
  92957. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  92958. if (!impostorForceAndContactPoint) {
  92959. return;
  92960. }
  92961. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  92962. });
  92963. };
  92964. /*** Helpers ***/
  92965. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  92966. if (!this._cylinder) {
  92967. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  92968. height: this._height,
  92969. diameter: this._radius * 2,
  92970. }, this._scene);
  92971. this._cylinder.isVisible = false;
  92972. }
  92973. };
  92974. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  92975. var impostorObject = impostor.object;
  92976. this._prepareCylinder();
  92977. this._cylinder.position = this._cylinderPosition;
  92978. return this._cylinder.intersectsMesh(impostorObject, true);
  92979. };
  92980. return PhysicsVortexEvent;
  92981. }());
  92982. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  92983. /***** Enums *****/
  92984. /**
  92985. * The strenght of the force in correspondence to the distance of the affected object
  92986. */
  92987. var PhysicsRadialImpulseFalloff;
  92988. (function (PhysicsRadialImpulseFalloff) {
  92989. /** Defines that impulse is constant in strength across it's whole radius */
  92990. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  92991. /** DEfines that impulse gets weaker if it's further from the origin */
  92992. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  92993. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  92994. /**
  92995. * The strenght of the force in correspondence to the distance of the affected object
  92996. */
  92997. var PhysicsUpdraftMode;
  92998. (function (PhysicsUpdraftMode) {
  92999. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  93000. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  93001. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  93002. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  93003. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  93004. })(BABYLON || (BABYLON = {}));
  93005. //# sourceMappingURL=babylon.physicsHelper.js.map
  93006. var BABYLON;
  93007. (function (BABYLON) {
  93008. /** @hidden */
  93009. var CannonJSPlugin = /** @class */ (function () {
  93010. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  93011. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  93012. if (iterations === void 0) { iterations = 10; }
  93013. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  93014. this.name = "CannonJSPlugin";
  93015. this._physicsMaterials = new Array();
  93016. this._fixedTimeStep = 1 / 60;
  93017. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  93018. this.BJSCANNON = CANNON;
  93019. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  93020. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  93021. this._tmpPosition = BABYLON.Vector3.Zero();
  93022. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  93023. this._tmpUnityRotation = new BABYLON.Quaternion();
  93024. if (!this.isSupported()) {
  93025. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  93026. return;
  93027. }
  93028. this._extendNamespace();
  93029. this.world = new this.BJSCANNON.World();
  93030. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  93031. this.world.solver.iterations = iterations;
  93032. }
  93033. CannonJSPlugin.prototype.setGravity = function (gravity) {
  93034. this.world.gravity.copy(gravity);
  93035. };
  93036. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  93037. this._fixedTimeStep = timeStep;
  93038. };
  93039. CannonJSPlugin.prototype.getTimeStep = function () {
  93040. return this._fixedTimeStep;
  93041. };
  93042. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  93043. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  93044. };
  93045. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  93046. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  93047. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  93048. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  93049. };
  93050. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  93051. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  93052. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  93053. impostor.physicsBody.applyForce(impulse, worldPoint);
  93054. };
  93055. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  93056. //parent-child relationship. Does this impostor has a parent impostor?
  93057. if (impostor.parent) {
  93058. if (impostor.physicsBody) {
  93059. this.removePhysicsBody(impostor);
  93060. //TODO is that needed?
  93061. impostor.forceUpdate();
  93062. }
  93063. return;
  93064. }
  93065. //should a new body be created for this impostor?
  93066. if (impostor.isBodyInitRequired()) {
  93067. var shape = this._createShape(impostor);
  93068. //unregister events, if body is being changed
  93069. var oldBody = impostor.physicsBody;
  93070. if (oldBody) {
  93071. this.removePhysicsBody(impostor);
  93072. }
  93073. //create the body and material
  93074. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  93075. var bodyCreationObject = {
  93076. mass: impostor.getParam("mass"),
  93077. material: material
  93078. };
  93079. // A simple extend, in case native options were used.
  93080. var nativeOptions = impostor.getParam("nativeOptions");
  93081. for (var key in nativeOptions) {
  93082. if (nativeOptions.hasOwnProperty(key)) {
  93083. bodyCreationObject[key] = nativeOptions[key];
  93084. }
  93085. }
  93086. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  93087. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  93088. this.world.addEventListener("preStep", impostor.beforeStep);
  93089. this.world.addEventListener("postStep", impostor.afterStep);
  93090. impostor.physicsBody.addShape(shape);
  93091. this.world.add(impostor.physicsBody);
  93092. //try to keep the body moving in the right direction by taking old properties.
  93093. //Should be tested!
  93094. if (oldBody) {
  93095. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  93096. impostor.physicsBody[param].copy(oldBody[param]);
  93097. });
  93098. }
  93099. this._processChildMeshes(impostor);
  93100. }
  93101. //now update the body's transformation
  93102. this._updatePhysicsBodyTransformation(impostor);
  93103. };
  93104. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  93105. var _this = this;
  93106. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  93107. var currentRotation = mainImpostor.object.rotationQuaternion;
  93108. if (meshChildren.length) {
  93109. var processMesh = function (localPosition, mesh) {
  93110. if (!currentRotation || !mesh.rotationQuaternion) {
  93111. return;
  93112. }
  93113. var childImpostor = mesh.getPhysicsImpostor();
  93114. if (childImpostor) {
  93115. var parent = childImpostor.parent;
  93116. if (parent !== mainImpostor) {
  93117. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  93118. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  93119. if (childImpostor.physicsBody) {
  93120. _this.removePhysicsBody(childImpostor);
  93121. childImpostor.physicsBody = null;
  93122. }
  93123. childImpostor.parent = mainImpostor;
  93124. childImpostor.resetUpdateFlags();
  93125. 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));
  93126. //Add the mass of the children.
  93127. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  93128. }
  93129. }
  93130. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  93131. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  93132. };
  93133. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  93134. }
  93135. };
  93136. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  93137. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  93138. this.world.removeEventListener("preStep", impostor.beforeStep);
  93139. this.world.removeEventListener("postStep", impostor.afterStep);
  93140. this.world.remove(impostor.physicsBody);
  93141. };
  93142. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  93143. var mainBody = impostorJoint.mainImpostor.physicsBody;
  93144. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  93145. if (!mainBody || !connectedBody) {
  93146. return;
  93147. }
  93148. var constraint;
  93149. var jointData = impostorJoint.joint.jointData;
  93150. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  93151. var constraintData = {
  93152. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  93153. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  93154. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  93155. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  93156. maxForce: jointData.nativeParams.maxForce,
  93157. collideConnected: !!jointData.collision
  93158. };
  93159. switch (impostorJoint.joint.type) {
  93160. case BABYLON.PhysicsJoint.HingeJoint:
  93161. case BABYLON.PhysicsJoint.Hinge2Joint:
  93162. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  93163. break;
  93164. case BABYLON.PhysicsJoint.DistanceJoint:
  93165. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  93166. break;
  93167. case BABYLON.PhysicsJoint.SpringJoint:
  93168. var springData = jointData;
  93169. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  93170. restLength: springData.length,
  93171. stiffness: springData.stiffness,
  93172. damping: springData.damping,
  93173. localAnchorA: constraintData.pivotA,
  93174. localAnchorB: constraintData.pivotB
  93175. });
  93176. break;
  93177. case BABYLON.PhysicsJoint.LockJoint:
  93178. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  93179. break;
  93180. case BABYLON.PhysicsJoint.PointToPointJoint:
  93181. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  93182. default:
  93183. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  93184. break;
  93185. }
  93186. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  93187. constraint.collideConnected = !!jointData.collision;
  93188. impostorJoint.joint.physicsJoint = constraint;
  93189. //don't add spring as constraint, as it is not one.
  93190. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  93191. this.world.addConstraint(constraint);
  93192. }
  93193. else {
  93194. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  93195. constraint.applyForce();
  93196. };
  93197. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  93198. }
  93199. };
  93200. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  93201. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  93202. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  93203. }
  93204. else {
  93205. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  93206. }
  93207. };
  93208. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  93209. var index;
  93210. var mat;
  93211. for (index = 0; index < this._physicsMaterials.length; index++) {
  93212. mat = this._physicsMaterials[index];
  93213. if (mat.friction === friction && mat.restitution === restitution) {
  93214. return mat;
  93215. }
  93216. }
  93217. var currentMat = new this.BJSCANNON.Material(name);
  93218. currentMat.friction = friction;
  93219. currentMat.restitution = restitution;
  93220. this._physicsMaterials.push(currentMat);
  93221. return currentMat;
  93222. };
  93223. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  93224. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  93225. };
  93226. CannonJSPlugin.prototype._createShape = function (impostor) {
  93227. var object = impostor.object;
  93228. var returnValue;
  93229. var extendSize = impostor.getObjectExtendSize();
  93230. switch (impostor.type) {
  93231. case BABYLON.PhysicsImpostor.SphereImpostor:
  93232. var radiusX = extendSize.x;
  93233. var radiusY = extendSize.y;
  93234. var radiusZ = extendSize.z;
  93235. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  93236. break;
  93237. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  93238. case BABYLON.PhysicsImpostor.CylinderImpostor:
  93239. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  93240. break;
  93241. case BABYLON.PhysicsImpostor.BoxImpostor:
  93242. var box = extendSize.scale(0.5);
  93243. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  93244. break;
  93245. case BABYLON.PhysicsImpostor.PlaneImpostor:
  93246. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  93247. returnValue = new this.BJSCANNON.Plane();
  93248. break;
  93249. case BABYLON.PhysicsImpostor.MeshImpostor:
  93250. // should transform the vertex data to world coordinates!!
  93251. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  93252. var rawFaces = object.getIndices ? object.getIndices() : [];
  93253. if (!rawVerts)
  93254. return;
  93255. // get only scale! so the object could transform correctly.
  93256. var oldPosition = object.position.clone();
  93257. var oldRotation = object.rotation && object.rotation.clone();
  93258. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  93259. object.position.copyFromFloats(0, 0, 0);
  93260. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  93261. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  93262. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  93263. var transform = object.computeWorldMatrix(true);
  93264. // convert rawVerts to object space
  93265. var temp = new Array();
  93266. var index;
  93267. for (index = 0; index < rawVerts.length; index += 3) {
  93268. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  93269. }
  93270. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  93271. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  93272. //now set back the transformation!
  93273. object.position.copyFrom(oldPosition);
  93274. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  93275. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  93276. break;
  93277. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  93278. var oldPosition2 = object.position.clone();
  93279. var oldRotation2 = object.rotation && object.rotation.clone();
  93280. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  93281. object.position.copyFromFloats(0, 0, 0);
  93282. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  93283. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  93284. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  93285. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  93286. returnValue = this._createHeightmap(object);
  93287. object.position.copyFrom(oldPosition2);
  93288. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  93289. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  93290. object.computeWorldMatrix(true);
  93291. break;
  93292. case BABYLON.PhysicsImpostor.ParticleImpostor:
  93293. returnValue = new this.BJSCANNON.Particle();
  93294. break;
  93295. }
  93296. return returnValue;
  93297. };
  93298. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  93299. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  93300. var transform = object.computeWorldMatrix(true);
  93301. // convert rawVerts to object space
  93302. var temp = new Array();
  93303. var index;
  93304. for (index = 0; index < pos.length; index += 3) {
  93305. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  93306. }
  93307. pos = temp;
  93308. var matrix = new Array();
  93309. //For now pointDepth will not be used and will be automatically calculated.
  93310. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  93311. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  93312. var boundingInfo = object.getBoundingInfo();
  93313. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  93314. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  93315. var elementSize = dim * 2 / arraySize;
  93316. for (var i = 0; i < pos.length; i = i + 3) {
  93317. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  93318. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  93319. var y = -pos[i + 2] + minY;
  93320. if (!matrix[x]) {
  93321. matrix[x] = [];
  93322. }
  93323. if (!matrix[x][z]) {
  93324. matrix[x][z] = y;
  93325. }
  93326. matrix[x][z] = Math.max(y, matrix[x][z]);
  93327. }
  93328. for (var x = 0; x <= arraySize; ++x) {
  93329. if (!matrix[x]) {
  93330. var loc = 1;
  93331. while (!matrix[(x + loc) % arraySize]) {
  93332. loc++;
  93333. }
  93334. matrix[x] = matrix[(x + loc) % arraySize].slice();
  93335. //console.log("missing x", x);
  93336. }
  93337. for (var z = 0; z <= arraySize; ++z) {
  93338. if (!matrix[x][z]) {
  93339. var loc = 1;
  93340. var newValue;
  93341. while (newValue === undefined) {
  93342. newValue = matrix[x][(z + loc++) % arraySize];
  93343. }
  93344. matrix[x][z] = newValue;
  93345. }
  93346. }
  93347. }
  93348. var shape = new this.BJSCANNON.Heightfield(matrix, {
  93349. elementSize: elementSize
  93350. });
  93351. //For future reference, needed for body transformation
  93352. shape.minY = minY;
  93353. return shape;
  93354. };
  93355. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  93356. var object = impostor.object;
  93357. //make sure it is updated...
  93358. object.computeWorldMatrix && object.computeWorldMatrix(true);
  93359. // The delta between the mesh position and the mesh bounding box center
  93360. var bInfo = object.getBoundingInfo();
  93361. if (!bInfo)
  93362. return;
  93363. var center = impostor.getObjectCenter();
  93364. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  93365. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  93366. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  93367. this._tmpPosition.copyFrom(center);
  93368. var quaternion = object.rotationQuaternion;
  93369. if (!quaternion) {
  93370. return;
  93371. }
  93372. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  93373. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  93374. //-90 DEG in X, precalculated
  93375. quaternion = quaternion.multiply(this._minus90X);
  93376. //Invert! (Precalculated, 90 deg in X)
  93377. //No need to clone. this will never change.
  93378. impostor.setDeltaRotation(this._plus90X);
  93379. }
  93380. //If it is a heightfield, if should be centered.
  93381. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  93382. var mesh = object;
  93383. var boundingInfo = mesh.getBoundingInfo();
  93384. //calculate the correct body position:
  93385. var rotationQuaternion = mesh.rotationQuaternion;
  93386. mesh.rotationQuaternion = this._tmpUnityRotation;
  93387. mesh.computeWorldMatrix(true);
  93388. //get original center with no rotation
  93389. var c = center.clone();
  93390. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  93391. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  93392. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  93393. mesh.setPreTransformMatrix(p);
  93394. mesh.computeWorldMatrix(true);
  93395. //calculate the translation
  93396. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  93397. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  93398. //add it inverted to the delta
  93399. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  93400. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  93401. //rotation is back
  93402. mesh.rotationQuaternion = rotationQuaternion;
  93403. mesh.setPreTransformMatrix(oldPivot);
  93404. mesh.computeWorldMatrix(true);
  93405. }
  93406. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  93407. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  93408. //this._tmpPosition.copyFrom(object.position);
  93409. }
  93410. impostor.setDeltaPosition(this._tmpDeltaPosition);
  93411. //Now update the impostor object
  93412. impostor.physicsBody.position.copy(this._tmpPosition);
  93413. impostor.physicsBody.quaternion.copy(quaternion);
  93414. };
  93415. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  93416. impostor.object.position.copyFrom(impostor.physicsBody.position);
  93417. if (impostor.object.rotationQuaternion) {
  93418. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  93419. }
  93420. };
  93421. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  93422. impostor.physicsBody.position.copy(newPosition);
  93423. impostor.physicsBody.quaternion.copy(newRotation);
  93424. };
  93425. CannonJSPlugin.prototype.isSupported = function () {
  93426. return this.BJSCANNON !== undefined;
  93427. };
  93428. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  93429. impostor.physicsBody.velocity.copy(velocity);
  93430. };
  93431. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  93432. impostor.physicsBody.angularVelocity.copy(velocity);
  93433. };
  93434. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  93435. var v = impostor.physicsBody.velocity;
  93436. if (!v) {
  93437. return null;
  93438. }
  93439. return new BABYLON.Vector3(v.x, v.y, v.z);
  93440. };
  93441. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  93442. var v = impostor.physicsBody.angularVelocity;
  93443. if (!v) {
  93444. return null;
  93445. }
  93446. return new BABYLON.Vector3(v.x, v.y, v.z);
  93447. };
  93448. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  93449. impostor.physicsBody.mass = mass;
  93450. impostor.physicsBody.updateMassProperties();
  93451. };
  93452. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  93453. return impostor.physicsBody.mass;
  93454. };
  93455. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  93456. return impostor.physicsBody.material.friction;
  93457. };
  93458. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  93459. impostor.physicsBody.material.friction = friction;
  93460. };
  93461. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  93462. return impostor.physicsBody.material.restitution;
  93463. };
  93464. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  93465. impostor.physicsBody.material.restitution = restitution;
  93466. };
  93467. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  93468. impostor.physicsBody.sleep();
  93469. };
  93470. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  93471. impostor.physicsBody.wakeUp();
  93472. };
  93473. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  93474. joint.physicsJoint.distance = maxDistance;
  93475. };
  93476. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  93477. // if (!motorIndex) {
  93478. // joint.physicsJoint.enableMotor();
  93479. // }
  93480. // }
  93481. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  93482. // if (!motorIndex) {
  93483. // joint.physicsJoint.disableMotor();
  93484. // }
  93485. // }
  93486. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  93487. if (!motorIndex) {
  93488. joint.physicsJoint.enableMotor();
  93489. joint.physicsJoint.setMotorSpeed(speed);
  93490. if (maxForce) {
  93491. this.setLimit(joint, maxForce);
  93492. }
  93493. }
  93494. };
  93495. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  93496. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  93497. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  93498. };
  93499. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  93500. var body = impostor.physicsBody;
  93501. mesh.position.x = body.position.x;
  93502. mesh.position.y = body.position.y;
  93503. mesh.position.z = body.position.z;
  93504. if (mesh.rotationQuaternion) {
  93505. mesh.rotationQuaternion.x = body.quaternion.x;
  93506. mesh.rotationQuaternion.y = body.quaternion.y;
  93507. mesh.rotationQuaternion.z = body.quaternion.z;
  93508. mesh.rotationQuaternion.w = body.quaternion.w;
  93509. }
  93510. };
  93511. CannonJSPlugin.prototype.getRadius = function (impostor) {
  93512. var shape = impostor.physicsBody.shapes[0];
  93513. return shape.boundingSphereRadius;
  93514. };
  93515. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  93516. var shape = impostor.physicsBody.shapes[0];
  93517. result.x = shape.halfExtents.x * 2;
  93518. result.y = shape.halfExtents.y * 2;
  93519. result.z = shape.halfExtents.z * 2;
  93520. };
  93521. CannonJSPlugin.prototype.dispose = function () {
  93522. };
  93523. CannonJSPlugin.prototype._extendNamespace = function () {
  93524. //this will force cannon to execute at least one step when using interpolation
  93525. var step_tmp1 = new this.BJSCANNON.Vec3();
  93526. var Engine = this.BJSCANNON;
  93527. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  93528. maxSubSteps = maxSubSteps || 10;
  93529. timeSinceLastCalled = timeSinceLastCalled || 0;
  93530. if (timeSinceLastCalled === 0) {
  93531. this.internalStep(dt);
  93532. this.time += dt;
  93533. }
  93534. else {
  93535. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  93536. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  93537. var t0 = performance.now();
  93538. for (var i = 0; i !== internalSteps; i++) {
  93539. this.internalStep(dt);
  93540. if (performance.now() - t0 > dt * 1000) {
  93541. break;
  93542. }
  93543. }
  93544. this.time += timeSinceLastCalled;
  93545. var h = this.time % dt;
  93546. var h_div_dt = h / dt;
  93547. var interpvelo = step_tmp1;
  93548. var bodies = this.bodies;
  93549. for (var j = 0; j !== bodies.length; j++) {
  93550. var b = bodies[j];
  93551. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  93552. b.position.vsub(b.previousPosition, interpvelo);
  93553. interpvelo.scale(h_div_dt, interpvelo);
  93554. b.position.vadd(interpvelo, b.interpolatedPosition);
  93555. }
  93556. else {
  93557. b.interpolatedPosition.copy(b.position);
  93558. b.interpolatedQuaternion.copy(b.quaternion);
  93559. }
  93560. }
  93561. }
  93562. };
  93563. };
  93564. return CannonJSPlugin;
  93565. }());
  93566. BABYLON.CannonJSPlugin = CannonJSPlugin;
  93567. })(BABYLON || (BABYLON = {}));
  93568. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  93569. var BABYLON;
  93570. (function (BABYLON) {
  93571. /** @hidden */
  93572. var OimoJSPlugin = /** @class */ (function () {
  93573. function OimoJSPlugin(iterations) {
  93574. this.name = "OimoJSPlugin";
  93575. this._tmpImpostorsArray = [];
  93576. this._tmpPositionVector = BABYLON.Vector3.Zero();
  93577. this.BJSOIMO = OIMO;
  93578. this.world = new this.BJSOIMO.World({
  93579. iterations: iterations
  93580. });
  93581. this.world.clear();
  93582. }
  93583. OimoJSPlugin.prototype.setGravity = function (gravity) {
  93584. this.world.gravity.copy(gravity);
  93585. };
  93586. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  93587. this.world.timeStep = timeStep;
  93588. };
  93589. OimoJSPlugin.prototype.getTimeStep = function () {
  93590. return this.world.timeStep;
  93591. };
  93592. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  93593. var _this = this;
  93594. impostors.forEach(function (impostor) {
  93595. impostor.beforeStep();
  93596. });
  93597. this.world.step();
  93598. impostors.forEach(function (impostor) {
  93599. impostor.afterStep();
  93600. //update the ordered impostors array
  93601. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  93602. });
  93603. //check for collisions
  93604. var contact = this.world.contacts;
  93605. while (contact !== null) {
  93606. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  93607. contact = contact.next;
  93608. continue;
  93609. }
  93610. //is this body colliding with any other? get the impostor
  93611. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  93612. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  93613. if (!mainImpostor || !collidingImpostor) {
  93614. contact = contact.next;
  93615. continue;
  93616. }
  93617. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  93618. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  93619. contact = contact.next;
  93620. }
  93621. };
  93622. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  93623. var mass = impostor.physicsBody.mass;
  93624. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  93625. };
  93626. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  93627. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  93628. this.applyImpulse(impostor, force, contactPoint);
  93629. };
  93630. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  93631. var _this = this;
  93632. //parent-child relationship. Does this impostor has a parent impostor?
  93633. if (impostor.parent) {
  93634. if (impostor.physicsBody) {
  93635. this.removePhysicsBody(impostor);
  93636. //TODO is that needed?
  93637. impostor.forceUpdate();
  93638. }
  93639. return;
  93640. }
  93641. if (impostor.isBodyInitRequired()) {
  93642. var bodyConfig = {
  93643. name: impostor.uniqueId,
  93644. //Oimo must have mass, also for static objects.
  93645. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  93646. size: [],
  93647. type: [],
  93648. pos: [],
  93649. posShape: [],
  93650. rot: [],
  93651. rotShape: [],
  93652. move: impostor.getParam("mass") !== 0,
  93653. density: impostor.getParam("mass"),
  93654. friction: impostor.getParam("friction"),
  93655. restitution: impostor.getParam("restitution"),
  93656. //Supporting older versions of Oimo
  93657. world: this.world
  93658. };
  93659. var impostors = [impostor];
  93660. var addToArray = function (parent) {
  93661. if (!parent.getChildMeshes)
  93662. return;
  93663. parent.getChildMeshes().forEach(function (m) {
  93664. if (m.physicsImpostor) {
  93665. impostors.push(m.physicsImpostor);
  93666. //m.physicsImpostor._init();
  93667. }
  93668. });
  93669. };
  93670. addToArray(impostor.object);
  93671. var checkWithEpsilon_1 = function (value) {
  93672. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  93673. };
  93674. var globalQuaternion_1 = new BABYLON.Quaternion();
  93675. impostors.forEach(function (i) {
  93676. if (!i.object.rotationQuaternion) {
  93677. return;
  93678. }
  93679. //get the correct bounding box
  93680. var oldQuaternion = i.object.rotationQuaternion;
  93681. globalQuaternion_1 = oldQuaternion.clone();
  93682. var rot = oldQuaternion.toEulerAngles();
  93683. var extendSize = i.getObjectExtendSize();
  93684. var radToDeg = 57.295779513082320876;
  93685. if (i === impostor) {
  93686. var center = impostor.getObjectCenter();
  93687. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  93688. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  93689. //Can also use Array.prototype.push.apply
  93690. bodyConfig.pos.push(center.x);
  93691. bodyConfig.pos.push(center.y);
  93692. bodyConfig.pos.push(center.z);
  93693. bodyConfig.posShape.push(0, 0, 0);
  93694. //tmp solution
  93695. bodyConfig.rot.push(0);
  93696. bodyConfig.rot.push(0);
  93697. bodyConfig.rot.push(0);
  93698. bodyConfig.rotShape.push(0, 0, 0);
  93699. }
  93700. else {
  93701. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  93702. bodyConfig.posShape.push(localPosition.x);
  93703. bodyConfig.posShape.push(localPosition.y);
  93704. bodyConfig.posShape.push(localPosition.z);
  93705. bodyConfig.pos.push(0, 0, 0);
  93706. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  93707. bodyConfig.rot.push(0);
  93708. bodyConfig.rot.push(0);
  93709. bodyConfig.rot.push(0);
  93710. bodyConfig.rotShape.push(rot.x * radToDeg);
  93711. bodyConfig.rotShape.push(rot.y * radToDeg);
  93712. bodyConfig.rotShape.push(rot.z * radToDeg);
  93713. }
  93714. // register mesh
  93715. switch (i.type) {
  93716. case BABYLON.PhysicsImpostor.ParticleImpostor:
  93717. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  93718. case BABYLON.PhysicsImpostor.SphereImpostor:
  93719. var radiusX = extendSize.x;
  93720. var radiusY = extendSize.y;
  93721. var radiusZ = extendSize.z;
  93722. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  93723. bodyConfig.type.push('sphere');
  93724. //due to the way oimo works with compounds, add 3 times
  93725. bodyConfig.size.push(size);
  93726. bodyConfig.size.push(size);
  93727. bodyConfig.size.push(size);
  93728. break;
  93729. case BABYLON.PhysicsImpostor.CylinderImpostor:
  93730. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  93731. var sizeY = checkWithEpsilon_1(extendSize.y);
  93732. bodyConfig.type.push('cylinder');
  93733. bodyConfig.size.push(sizeX);
  93734. bodyConfig.size.push(sizeY);
  93735. //due to the way oimo works with compounds, add one more value.
  93736. bodyConfig.size.push(sizeY);
  93737. break;
  93738. case BABYLON.PhysicsImpostor.PlaneImpostor:
  93739. case BABYLON.PhysicsImpostor.BoxImpostor:
  93740. default:
  93741. var sizeX = checkWithEpsilon_1(extendSize.x);
  93742. var sizeY = checkWithEpsilon_1(extendSize.y);
  93743. var sizeZ = checkWithEpsilon_1(extendSize.z);
  93744. bodyConfig.type.push('box');
  93745. //if (i === impostor) {
  93746. bodyConfig.size.push(sizeX);
  93747. bodyConfig.size.push(sizeY);
  93748. bodyConfig.size.push(sizeZ);
  93749. //} else {
  93750. // bodyConfig.size.push(0,0,0);
  93751. //}
  93752. break;
  93753. }
  93754. //actually not needed, but hey...
  93755. i.object.rotationQuaternion = oldQuaternion;
  93756. });
  93757. impostor.physicsBody = this.world.add(bodyConfig);
  93758. // set the quaternion, ignoring the previously defined (euler) rotation
  93759. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  93760. // update with delta 0, so the body will reveive the new rotation.
  93761. impostor.physicsBody.updatePosition(0);
  93762. }
  93763. else {
  93764. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  93765. }
  93766. impostor.setDeltaPosition(this._tmpPositionVector);
  93767. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  93768. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  93769. };
  93770. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  93771. //impostor.physicsBody.dispose();
  93772. //Same as : (older oimo versions)
  93773. this.world.removeRigidBody(impostor.physicsBody);
  93774. };
  93775. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  93776. var mainBody = impostorJoint.mainImpostor.physicsBody;
  93777. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  93778. if (!mainBody || !connectedBody) {
  93779. return;
  93780. }
  93781. var jointData = impostorJoint.joint.jointData;
  93782. var options = jointData.nativeParams || {};
  93783. var type;
  93784. var nativeJointData = {
  93785. body1: mainBody,
  93786. body2: connectedBody,
  93787. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  93788. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  93789. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  93790. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  93791. min: options.min,
  93792. max: options.max,
  93793. collision: options.collision || jointData.collision,
  93794. spring: options.spring,
  93795. //supporting older version of Oimo
  93796. world: this.world
  93797. };
  93798. switch (impostorJoint.joint.type) {
  93799. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  93800. type = "jointBall";
  93801. break;
  93802. case BABYLON.PhysicsJoint.SpringJoint:
  93803. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  93804. var springData = jointData;
  93805. nativeJointData.min = springData.length || nativeJointData.min;
  93806. //Max should also be set, just make sure it is at least min
  93807. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  93808. case BABYLON.PhysicsJoint.DistanceJoint:
  93809. type = "jointDistance";
  93810. nativeJointData.max = jointData.maxDistance;
  93811. break;
  93812. case BABYLON.PhysicsJoint.PrismaticJoint:
  93813. type = "jointPrisme";
  93814. break;
  93815. case BABYLON.PhysicsJoint.SliderJoint:
  93816. type = "jointSlide";
  93817. break;
  93818. case BABYLON.PhysicsJoint.WheelJoint:
  93819. type = "jointWheel";
  93820. break;
  93821. case BABYLON.PhysicsJoint.HingeJoint:
  93822. default:
  93823. type = "jointHinge";
  93824. break;
  93825. }
  93826. nativeJointData.type = type;
  93827. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  93828. };
  93829. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  93830. //Bug in Oimo prevents us from disposing a joint in the playground
  93831. //joint.joint.physicsJoint.dispose();
  93832. //So we will bruteforce it!
  93833. try {
  93834. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  93835. }
  93836. catch (e) {
  93837. BABYLON.Tools.Warn(e);
  93838. }
  93839. };
  93840. OimoJSPlugin.prototype.isSupported = function () {
  93841. return this.BJSOIMO !== undefined;
  93842. };
  93843. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  93844. if (!impostor.physicsBody.sleeping) {
  93845. //TODO check that
  93846. /*if (impostor.physicsBody.shapes.next) {
  93847. var parentShape = this._getLastShape(impostor.physicsBody);
  93848. impostor.object.position.copyFrom(parentShape.position);
  93849. console.log(parentShape.position);
  93850. } else {*/
  93851. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  93852. //}
  93853. if (impostor.object.rotationQuaternion) {
  93854. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  93855. }
  93856. }
  93857. };
  93858. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  93859. var body = impostor.physicsBody;
  93860. body.position.copy(newPosition);
  93861. body.orientation.copy(newRotation);
  93862. body.syncShapes();
  93863. body.awake();
  93864. };
  93865. /*private _getLastShape(body: any): any {
  93866. var lastShape = body.shapes;
  93867. while (lastShape.next) {
  93868. lastShape = lastShape.next;
  93869. }
  93870. return lastShape;
  93871. }*/
  93872. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  93873. impostor.physicsBody.linearVelocity.copy(velocity);
  93874. };
  93875. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  93876. impostor.physicsBody.angularVelocity.copy(velocity);
  93877. };
  93878. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  93879. var v = impostor.physicsBody.linearVelocity;
  93880. if (!v) {
  93881. return null;
  93882. }
  93883. return new BABYLON.Vector3(v.x, v.y, v.z);
  93884. };
  93885. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  93886. var v = impostor.physicsBody.angularVelocity;
  93887. if (!v) {
  93888. return null;
  93889. }
  93890. return new BABYLON.Vector3(v.x, v.y, v.z);
  93891. };
  93892. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  93893. var staticBody = mass === 0;
  93894. //this will actually set the body's density and not its mass.
  93895. //But this is how oimo treats the mass variable.
  93896. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  93897. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  93898. };
  93899. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  93900. return impostor.physicsBody.shapes.density;
  93901. };
  93902. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  93903. return impostor.physicsBody.shapes.friction;
  93904. };
  93905. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  93906. impostor.physicsBody.shapes.friction = friction;
  93907. };
  93908. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  93909. return impostor.physicsBody.shapes.restitution;
  93910. };
  93911. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  93912. impostor.physicsBody.shapes.restitution = restitution;
  93913. };
  93914. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  93915. impostor.physicsBody.sleep();
  93916. };
  93917. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  93918. impostor.physicsBody.awake();
  93919. };
  93920. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  93921. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  93922. if (minDistance !== void 0) {
  93923. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  93924. }
  93925. };
  93926. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  93927. //TODO separate rotational and transational motors.
  93928. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  93929. if (motor) {
  93930. motor.setMotor(speed, maxForce);
  93931. }
  93932. };
  93933. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  93934. //TODO separate rotational and transational motors.
  93935. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  93936. if (motor) {
  93937. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  93938. }
  93939. };
  93940. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  93941. var body = impostor.physicsBody;
  93942. mesh.position.x = body.position.x;
  93943. mesh.position.y = body.position.y;
  93944. mesh.position.z = body.position.z;
  93945. if (mesh.rotationQuaternion) {
  93946. mesh.rotationQuaternion.x = body.orientation.x;
  93947. mesh.rotationQuaternion.y = body.orientation.y;
  93948. mesh.rotationQuaternion.z = body.orientation.z;
  93949. mesh.rotationQuaternion.w = body.orientation.s;
  93950. }
  93951. };
  93952. OimoJSPlugin.prototype.getRadius = function (impostor) {
  93953. return impostor.physicsBody.shapes.radius;
  93954. };
  93955. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  93956. var shape = impostor.physicsBody.shapes;
  93957. result.x = shape.halfWidth * 2;
  93958. result.y = shape.halfHeight * 2;
  93959. result.z = shape.halfDepth * 2;
  93960. };
  93961. OimoJSPlugin.prototype.dispose = function () {
  93962. this.world.clear();
  93963. };
  93964. return OimoJSPlugin;
  93965. }());
  93966. BABYLON.OimoJSPlugin = OimoJSPlugin;
  93967. })(BABYLON || (BABYLON = {}));
  93968. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  93969. var BABYLON;
  93970. (function (BABYLON) {
  93971. /**
  93972. * Gets the current physics engine
  93973. * @returns a IPhysicsEngine or null if none attached
  93974. */
  93975. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  93976. return this._physicsEngine;
  93977. };
  93978. /**
  93979. * Enables physics to the current scene
  93980. * @param gravity defines the scene's gravity for the physics engine
  93981. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  93982. * @return a boolean indicating if the physics engine was initialized
  93983. */
  93984. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  93985. if (gravity === void 0) { gravity = null; }
  93986. if (this._physicsEngine) {
  93987. return true;
  93988. }
  93989. // Register the component to the scene
  93990. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  93991. if (!component) {
  93992. component = new PhysicsEngineSceneComponent(this);
  93993. this._addComponent(component);
  93994. }
  93995. try {
  93996. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  93997. return true;
  93998. }
  93999. catch (e) {
  94000. BABYLON.Tools.Error(e.message);
  94001. return false;
  94002. }
  94003. };
  94004. /**
  94005. * Disables and disposes the physics engine associated with the scene
  94006. */
  94007. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  94008. if (!this._physicsEngine) {
  94009. return;
  94010. }
  94011. this._physicsEngine.dispose();
  94012. this._physicsEngine = null;
  94013. };
  94014. /**
  94015. * Gets a boolean indicating if there is an active physics engine
  94016. * @returns a boolean indicating if there is an active physics engine
  94017. */
  94018. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  94019. return this._physicsEngine !== undefined;
  94020. };
  94021. /**
  94022. * Deletes a physics compound impostor
  94023. * @param compound defines the compound to delete
  94024. */
  94025. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  94026. var mesh = compound.parts[0].mesh;
  94027. if (mesh.physicsImpostor) {
  94028. mesh.physicsImpostor.dispose( /*true*/);
  94029. mesh.physicsImpostor = null;
  94030. }
  94031. };
  94032. /** @hidden */
  94033. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  94034. if (this._physicsEngine) {
  94035. this.onBeforePhysicsObservable.notifyObservers(this);
  94036. this._physicsEngine._step(step / 1000);
  94037. this.onAfterPhysicsObservable.notifyObservers(this);
  94038. }
  94039. };
  94040. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  94041. get: function () {
  94042. return this._physicsImpostor;
  94043. },
  94044. set: function (value) {
  94045. var _this = this;
  94046. if (this._physicsImpostor === value) {
  94047. return;
  94048. }
  94049. if (this._disposePhysicsObserver) {
  94050. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  94051. }
  94052. this._physicsImpostor = value;
  94053. if (value) {
  94054. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  94055. // Physics
  94056. if (_this.physicsImpostor) {
  94057. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  94058. _this.physicsImpostor = null;
  94059. }
  94060. });
  94061. }
  94062. },
  94063. enumerable: true,
  94064. configurable: true
  94065. });
  94066. /**
  94067. * Gets the current physics impostor
  94068. * @see http://doc.babylonjs.com/features/physics_engine
  94069. * @returns a physics impostor or null
  94070. */
  94071. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  94072. return this.physicsImpostor;
  94073. };
  94074. /**
  94075. * Apply a physic impulse to the mesh
  94076. * @param force defines the force to apply
  94077. * @param contactPoint defines where to apply the force
  94078. * @returns the current mesh
  94079. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  94080. */
  94081. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  94082. if (!this.physicsImpostor) {
  94083. return this;
  94084. }
  94085. this.physicsImpostor.applyImpulse(force, contactPoint);
  94086. return this;
  94087. };
  94088. /**
  94089. * Creates a physic joint between two meshes
  94090. * @param otherMesh defines the other mesh to use
  94091. * @param pivot1 defines the pivot to use on this mesh
  94092. * @param pivot2 defines the pivot to use on the other mesh
  94093. * @param options defines additional options (can be plugin dependent)
  94094. * @returns the current mesh
  94095. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  94096. */
  94097. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  94098. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  94099. return this;
  94100. }
  94101. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  94102. mainPivot: pivot1,
  94103. connectedPivot: pivot2,
  94104. nativeParams: options
  94105. });
  94106. return this;
  94107. };
  94108. /**
  94109. * Defines the physics engine scene component responsible to manage a physics engine
  94110. */
  94111. var PhysicsEngineSceneComponent = /** @class */ (function () {
  94112. /**
  94113. * Creates a new instance of the component for the given scene
  94114. * @param scene Defines the scene to register the component in
  94115. */
  94116. function PhysicsEngineSceneComponent(scene) {
  94117. var _this = this;
  94118. /**
  94119. * The component name helpful to identify the component in the list of scene components.
  94120. */
  94121. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  94122. this.scene = scene;
  94123. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  94124. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  94125. // Replace the function used to get the deterministic frame time
  94126. this.scene.getDeterministicFrameTime = function () {
  94127. if (_this.scene._physicsEngine) {
  94128. return _this.scene._physicsEngine.getTimeStep() * 1000;
  94129. }
  94130. return 1000.0 / 60.0;
  94131. };
  94132. }
  94133. /**
  94134. * Registers the component in a given scene
  94135. */
  94136. PhysicsEngineSceneComponent.prototype.register = function () {
  94137. };
  94138. /**
  94139. * Rebuilds the elements related to this component in case of
  94140. * context lost for instance.
  94141. */
  94142. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  94143. // Nothing to do for this component
  94144. };
  94145. /**
  94146. * Disposes the component and the associated ressources
  94147. */
  94148. PhysicsEngineSceneComponent.prototype.dispose = function () {
  94149. this.scene.onBeforePhysicsObservable.clear();
  94150. this.scene.onAfterPhysicsObservable.clear();
  94151. if (this.scene._physicsEngine) {
  94152. this.scene.disablePhysicsEngine();
  94153. }
  94154. };
  94155. return PhysicsEngineSceneComponent;
  94156. }());
  94157. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  94158. })(BABYLON || (BABYLON = {}));
  94159. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  94160. var BABYLON;
  94161. (function (BABYLON) {
  94162. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  94163. // All values and structures referenced from:
  94164. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  94165. var DDS_MAGIC = 0x20534444;
  94166. var
  94167. //DDSD_CAPS = 0x1,
  94168. //DDSD_HEIGHT = 0x2,
  94169. //DDSD_WIDTH = 0x4,
  94170. //DDSD_PITCH = 0x8,
  94171. //DDSD_PIXELFORMAT = 0x1000,
  94172. DDSD_MIPMAPCOUNT = 0x20000;
  94173. //DDSD_LINEARSIZE = 0x80000,
  94174. //DDSD_DEPTH = 0x800000;
  94175. // var DDSCAPS_COMPLEX = 0x8,
  94176. // DDSCAPS_MIPMAP = 0x400000,
  94177. // DDSCAPS_TEXTURE = 0x1000;
  94178. var DDSCAPS2_CUBEMAP = 0x200;
  94179. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  94180. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  94181. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  94182. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  94183. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  94184. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  94185. // DDSCAPS2_VOLUME = 0x200000;
  94186. var
  94187. //DDPF_ALPHAPIXELS = 0x1,
  94188. //DDPF_ALPHA = 0x2,
  94189. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  94190. //DDPF_YUV = 0x200,
  94191. DDPF_LUMINANCE = 0x20000;
  94192. function FourCCToInt32(value) {
  94193. return value.charCodeAt(0) +
  94194. (value.charCodeAt(1) << 8) +
  94195. (value.charCodeAt(2) << 16) +
  94196. (value.charCodeAt(3) << 24);
  94197. }
  94198. function Int32ToFourCC(value) {
  94199. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  94200. }
  94201. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  94202. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  94203. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  94204. var FOURCC_DX10 = FourCCToInt32("DX10");
  94205. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  94206. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  94207. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  94208. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  94209. var headerLengthInt = 31; // The header length in 32 bit ints
  94210. // Offsets into the header array
  94211. var off_magic = 0;
  94212. var off_size = 1;
  94213. var off_flags = 2;
  94214. var off_height = 3;
  94215. var off_width = 4;
  94216. var off_mipmapCount = 7;
  94217. var off_pfFlags = 20;
  94218. var off_pfFourCC = 21;
  94219. var off_RGBbpp = 22;
  94220. var off_RMask = 23;
  94221. var off_GMask = 24;
  94222. var off_BMask = 25;
  94223. var off_AMask = 26;
  94224. // var off_caps1 = 27;
  94225. var off_caps2 = 28;
  94226. // var off_caps3 = 29;
  94227. // var off_caps4 = 30;
  94228. var off_dxgiFormat = 32;
  94229. ;
  94230. /**
  94231. * Class used to provide DDS decompression tools
  94232. */
  94233. var DDSTools = /** @class */ (function () {
  94234. function DDSTools() {
  94235. }
  94236. /**
  94237. * Gets DDS information from an array buffer
  94238. * @param arrayBuffer defines the array buffer to read data from
  94239. * @returns the DDS information
  94240. */
  94241. DDSTools.GetDDSInfo = function (arrayBuffer) {
  94242. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  94243. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  94244. var mipmapCount = 1;
  94245. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  94246. mipmapCount = Math.max(1, header[off_mipmapCount]);
  94247. }
  94248. var fourCC = header[off_pfFourCC];
  94249. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  94250. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94251. switch (fourCC) {
  94252. case FOURCC_D3DFMT_R16G16B16A16F:
  94253. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94254. break;
  94255. case FOURCC_D3DFMT_R32G32B32A32F:
  94256. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94257. break;
  94258. case FOURCC_DX10:
  94259. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  94260. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94261. break;
  94262. }
  94263. }
  94264. return {
  94265. width: header[off_width],
  94266. height: header[off_height],
  94267. mipmapCount: mipmapCount,
  94268. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  94269. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  94270. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  94271. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  94272. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  94273. dxgiFormat: dxgiFormat,
  94274. textureType: textureType
  94275. };
  94276. };
  94277. DDSTools._ToHalfFloat = function (value) {
  94278. if (!DDSTools._FloatView) {
  94279. DDSTools._FloatView = new Float32Array(1);
  94280. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  94281. }
  94282. DDSTools._FloatView[0] = value;
  94283. var x = DDSTools._Int32View[0];
  94284. var bits = (x >> 16) & 0x8000; /* Get the sign */
  94285. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  94286. var e = (x >> 23) & 0xff; /* Using int is faster here */
  94287. /* If zero, or denormal, or exponent underflows too much for a denormal
  94288. * half, return signed zero. */
  94289. if (e < 103) {
  94290. return bits;
  94291. }
  94292. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  94293. if (e > 142) {
  94294. bits |= 0x7c00;
  94295. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  94296. * not Inf, so make sure we set one mantissa bit too. */
  94297. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  94298. return bits;
  94299. }
  94300. /* If exponent underflows but not too much, return a denormal */
  94301. if (e < 113) {
  94302. m |= 0x0800;
  94303. /* Extra rounding may overflow and set mantissa to 0 and exponent
  94304. * to 1, which is OK. */
  94305. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  94306. return bits;
  94307. }
  94308. bits |= ((e - 112) << 10) | (m >> 1);
  94309. bits += m & 1;
  94310. return bits;
  94311. };
  94312. DDSTools._FromHalfFloat = function (value) {
  94313. var s = (value & 0x8000) >> 15;
  94314. var e = (value & 0x7C00) >> 10;
  94315. var f = value & 0x03FF;
  94316. if (e === 0) {
  94317. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  94318. }
  94319. else if (e == 0x1F) {
  94320. return f ? NaN : ((s ? -1 : 1) * Infinity);
  94321. }
  94322. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  94323. };
  94324. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  94325. var destArray = new Float32Array(dataLength);
  94326. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  94327. var index = 0;
  94328. for (var y = 0; y < height; y++) {
  94329. for (var x = 0; x < width; x++) {
  94330. var srcPos = (x + y * width) * 4;
  94331. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  94332. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  94333. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  94334. if (DDSTools.StoreLODInAlphaChannel) {
  94335. destArray[index + 3] = lod;
  94336. }
  94337. else {
  94338. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  94339. }
  94340. index += 4;
  94341. }
  94342. }
  94343. return destArray;
  94344. };
  94345. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  94346. if (DDSTools.StoreLODInAlphaChannel) {
  94347. var destArray = new Uint16Array(dataLength);
  94348. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  94349. var index = 0;
  94350. for (var y = 0; y < height; y++) {
  94351. for (var x = 0; x < width; x++) {
  94352. var srcPos = (x + y * width) * 4;
  94353. destArray[index] = srcData[srcPos];
  94354. destArray[index + 1] = srcData[srcPos + 1];
  94355. destArray[index + 2] = srcData[srcPos + 2];
  94356. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  94357. index += 4;
  94358. }
  94359. }
  94360. return destArray;
  94361. }
  94362. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  94363. };
  94364. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  94365. if (DDSTools.StoreLODInAlphaChannel) {
  94366. var destArray = new Float32Array(dataLength);
  94367. var srcData = new Float32Array(arrayBuffer, dataOffset);
  94368. var index = 0;
  94369. for (var y = 0; y < height; y++) {
  94370. for (var x = 0; x < width; x++) {
  94371. var srcPos = (x + y * width) * 4;
  94372. destArray[index] = srcData[srcPos];
  94373. destArray[index + 1] = srcData[srcPos + 1];
  94374. destArray[index + 2] = srcData[srcPos + 2];
  94375. destArray[index + 3] = lod;
  94376. index += 4;
  94377. }
  94378. }
  94379. return destArray;
  94380. }
  94381. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  94382. };
  94383. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  94384. var destArray = new Uint8Array(dataLength);
  94385. var srcData = new Float32Array(arrayBuffer, dataOffset);
  94386. var index = 0;
  94387. for (var y = 0; y < height; y++) {
  94388. for (var x = 0; x < width; x++) {
  94389. var srcPos = (x + y * width) * 4;
  94390. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  94391. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  94392. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  94393. if (DDSTools.StoreLODInAlphaChannel) {
  94394. destArray[index + 3] = lod;
  94395. }
  94396. else {
  94397. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  94398. }
  94399. index += 4;
  94400. }
  94401. }
  94402. return destArray;
  94403. };
  94404. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  94405. var destArray = new Uint8Array(dataLength);
  94406. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  94407. var index = 0;
  94408. for (var y = 0; y < height; y++) {
  94409. for (var x = 0; x < width; x++) {
  94410. var srcPos = (x + y * width) * 4;
  94411. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  94412. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  94413. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  94414. if (DDSTools.StoreLODInAlphaChannel) {
  94415. destArray[index + 3] = lod;
  94416. }
  94417. else {
  94418. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  94419. }
  94420. index += 4;
  94421. }
  94422. }
  94423. return destArray;
  94424. };
  94425. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  94426. var byteArray = new Uint8Array(dataLength);
  94427. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  94428. var index = 0;
  94429. for (var y = 0; y < height; y++) {
  94430. for (var x = 0; x < width; x++) {
  94431. var srcPos = (x + y * width) * 4;
  94432. byteArray[index] = srcData[srcPos + rOffset];
  94433. byteArray[index + 1] = srcData[srcPos + gOffset];
  94434. byteArray[index + 2] = srcData[srcPos + bOffset];
  94435. byteArray[index + 3] = srcData[srcPos + aOffset];
  94436. index += 4;
  94437. }
  94438. }
  94439. return byteArray;
  94440. };
  94441. DDSTools._ExtractLongWordOrder = function (value) {
  94442. if (value === 0 || value === 255 || value === -16777216) {
  94443. return 0;
  94444. }
  94445. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  94446. };
  94447. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  94448. var byteArray = new Uint8Array(dataLength);
  94449. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  94450. var index = 0;
  94451. for (var y = 0; y < height; y++) {
  94452. for (var x = 0; x < width; x++) {
  94453. var srcPos = (x + y * width) * 3;
  94454. byteArray[index] = srcData[srcPos + rOffset];
  94455. byteArray[index + 1] = srcData[srcPos + gOffset];
  94456. byteArray[index + 2] = srcData[srcPos + bOffset];
  94457. index += 3;
  94458. }
  94459. }
  94460. return byteArray;
  94461. };
  94462. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  94463. var byteArray = new Uint8Array(dataLength);
  94464. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  94465. var index = 0;
  94466. for (var y = 0; y < height; y++) {
  94467. for (var x = 0; x < width; x++) {
  94468. var srcPos = (x + y * width);
  94469. byteArray[index] = srcData[srcPos];
  94470. index++;
  94471. }
  94472. }
  94473. return byteArray;
  94474. };
  94475. /**
  94476. * Uploads DDS Levels to a Babylon Texture
  94477. * @hidden
  94478. */
  94479. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  94480. if (lodIndex === void 0) { lodIndex = -1; }
  94481. var sphericalPolynomialFaces = null;
  94482. if (info.sphericalPolynomial) {
  94483. sphericalPolynomialFaces = new Array();
  94484. }
  94485. var ext = engine.getCaps().s3tc;
  94486. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  94487. var fourCC, width, height, dataLength = 0, dataOffset;
  94488. var byteArray, mipmapCount, mip;
  94489. var internalCompressedFormat = 0;
  94490. var blockBytes = 1;
  94491. if (header[off_magic] !== DDS_MAGIC) {
  94492. BABYLON.Tools.Error("Invalid magic number in DDS header");
  94493. return;
  94494. }
  94495. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  94496. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  94497. return;
  94498. }
  94499. if (info.isCompressed && !ext) {
  94500. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  94501. return;
  94502. }
  94503. var bpp = header[off_RGBbpp];
  94504. dataOffset = header[off_size] + 4;
  94505. var computeFormats = false;
  94506. if (info.isFourCC) {
  94507. fourCC = header[off_pfFourCC];
  94508. switch (fourCC) {
  94509. case FOURCC_DXT1:
  94510. blockBytes = 8;
  94511. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  94512. break;
  94513. case FOURCC_DXT3:
  94514. blockBytes = 16;
  94515. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  94516. break;
  94517. case FOURCC_DXT5:
  94518. blockBytes = 16;
  94519. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  94520. break;
  94521. case FOURCC_D3DFMT_R16G16B16A16F:
  94522. computeFormats = true;
  94523. break;
  94524. case FOURCC_D3DFMT_R32G32B32A32F:
  94525. computeFormats = true;
  94526. break;
  94527. case FOURCC_DX10:
  94528. // There is an additionnal header so dataOffset need to be changed
  94529. dataOffset += 5 * 4; // 5 uints
  94530. var supported = false;
  94531. switch (info.dxgiFormat) {
  94532. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  94533. computeFormats = true;
  94534. supported = true;
  94535. break;
  94536. case DXGI_FORMAT_B8G8R8X8_UNORM:
  94537. info.isRGB = true;
  94538. info.isFourCC = false;
  94539. bpp = 32;
  94540. supported = true;
  94541. break;
  94542. }
  94543. if (supported) {
  94544. break;
  94545. }
  94546. default:
  94547. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  94548. return;
  94549. }
  94550. }
  94551. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  94552. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  94553. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  94554. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  94555. if (computeFormats) {
  94556. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  94557. }
  94558. mipmapCount = 1;
  94559. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  94560. mipmapCount = Math.max(1, header[off_mipmapCount]);
  94561. }
  94562. for (var face = 0; face < faces; face++) {
  94563. width = header[off_width];
  94564. height = header[off_height];
  94565. for (mip = 0; mip < mipmapCount; ++mip) {
  94566. if (lodIndex === -1 || lodIndex === mip) {
  94567. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  94568. var i = (lodIndex === -1) ? mip : 0;
  94569. if (!info.isCompressed && info.isFourCC) {
  94570. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  94571. dataLength = width * height * 4;
  94572. var floatArray = null;
  94573. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  94574. if (bpp === 128) {
  94575. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94576. if (sphericalPolynomialFaces && i == 0) {
  94577. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  94578. }
  94579. }
  94580. else if (bpp === 64) {
  94581. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94582. if (sphericalPolynomialFaces && i == 0) {
  94583. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  94584. }
  94585. }
  94586. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94587. }
  94588. else {
  94589. if (bpp === 128) {
  94590. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94591. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94592. if (sphericalPolynomialFaces && i == 0) {
  94593. sphericalPolynomialFaces.push(floatArray);
  94594. }
  94595. }
  94596. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  94597. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94598. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94599. if (sphericalPolynomialFaces && i == 0) {
  94600. sphericalPolynomialFaces.push(floatArray);
  94601. }
  94602. }
  94603. else { // 64
  94604. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94605. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94606. if (sphericalPolynomialFaces && i == 0) {
  94607. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  94608. }
  94609. }
  94610. }
  94611. if (floatArray) {
  94612. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  94613. }
  94614. }
  94615. else if (info.isRGB) {
  94616. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94617. if (bpp === 24) {
  94618. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  94619. dataLength = width * height * 3;
  94620. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  94621. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  94622. }
  94623. else { // 32
  94624. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  94625. dataLength = width * height * 4;
  94626. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  94627. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  94628. }
  94629. }
  94630. else if (info.isLuminance) {
  94631. var unpackAlignment = engine._getUnpackAlignement();
  94632. var unpaddedRowSize = width;
  94633. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  94634. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  94635. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  94636. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  94637. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94638. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  94639. }
  94640. else {
  94641. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  94642. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  94643. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94644. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  94645. }
  94646. }
  94647. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  94648. width *= 0.5;
  94649. height *= 0.5;
  94650. width = Math.max(1.0, width);
  94651. height = Math.max(1.0, height);
  94652. }
  94653. if (currentFace !== undefined) {
  94654. // Loading a single face
  94655. break;
  94656. }
  94657. }
  94658. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  94659. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  94660. size: header[off_width],
  94661. right: sphericalPolynomialFaces[0],
  94662. left: sphericalPolynomialFaces[1],
  94663. up: sphericalPolynomialFaces[2],
  94664. down: sphericalPolynomialFaces[3],
  94665. front: sphericalPolynomialFaces[4],
  94666. back: sphericalPolynomialFaces[5],
  94667. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  94668. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  94669. gammaSpace: false,
  94670. });
  94671. }
  94672. else {
  94673. info.sphericalPolynomial = undefined;
  94674. }
  94675. };
  94676. /**
  94677. * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
  94678. */
  94679. DDSTools.StoreLODInAlphaChannel = false;
  94680. return DDSTools;
  94681. }());
  94682. BABYLON.DDSTools = DDSTools;
  94683. })(BABYLON || (BABYLON = {}));
  94684. //# sourceMappingURL=babylon.dds.js.map
  94685. var BABYLON;
  94686. (function (BABYLON) {
  94687. /**
  94688. * Implementation of the DDS Texture Loader.
  94689. */
  94690. var DDSTextureLoader = /** @class */ (function () {
  94691. function DDSTextureLoader() {
  94692. /**
  94693. * Defines wether the loader supports cascade loading the different faces.
  94694. */
  94695. this.supportCascades = true;
  94696. }
  94697. /**
  94698. * This returns if the loader support the current file information.
  94699. * @param extension defines the file extension of the file being loaded
  94700. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94701. * @param fallback defines the fallback internal texture if any
  94702. * @param isBase64 defines whether the texture is encoded as a base64
  94703. * @param isBuffer defines whether the texture data are stored as a buffer
  94704. * @returns true if the loader can load the specified file
  94705. */
  94706. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  94707. return extension.indexOf(".dds") === 0;
  94708. };
  94709. /**
  94710. * Transform the url before loading if required.
  94711. * @param rootUrl the url of the texture
  94712. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94713. * @returns the transformed texture
  94714. */
  94715. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  94716. return rootUrl;
  94717. };
  94718. /**
  94719. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  94720. * @param rootUrl the url of the texture
  94721. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94722. * @returns the fallback texture
  94723. */
  94724. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  94725. return null;
  94726. };
  94727. /**
  94728. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  94729. * @param data contains the texture data
  94730. * @param texture defines the BabylonJS internal texture
  94731. * @param createPolynomials will be true if polynomials have been requested
  94732. * @param onLoad defines the callback to trigger once the texture is ready
  94733. * @param onError defines the callback to trigger in case of error
  94734. */
  94735. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  94736. var engine = texture.getEngine();
  94737. var info;
  94738. var loadMipmap = false;
  94739. if (Array.isArray(imgs)) {
  94740. for (var index = 0; index < imgs.length; index++) {
  94741. var data_1 = imgs[index];
  94742. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  94743. texture.width = info.width;
  94744. texture.height = info.height;
  94745. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  94746. engine._unpackFlipY(info.isCompressed);
  94747. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  94748. if (!info.isFourCC && info.mipmapCount === 1) {
  94749. engine.generateMipMapsForCubemap(texture);
  94750. }
  94751. }
  94752. }
  94753. else {
  94754. var data = imgs;
  94755. info = BABYLON.DDSTools.GetDDSInfo(data);
  94756. texture.width = info.width;
  94757. texture.height = info.height;
  94758. if (createPolynomials) {
  94759. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  94760. }
  94761. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  94762. engine._unpackFlipY(info.isCompressed);
  94763. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  94764. if (!info.isFourCC && info.mipmapCount === 1) {
  94765. engine.generateMipMapsForCubemap(texture);
  94766. }
  94767. }
  94768. engine._setCubeMapTextureParams(loadMipmap);
  94769. texture.isReady = true;
  94770. if (onLoad) {
  94771. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  94772. }
  94773. };
  94774. /**
  94775. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  94776. * @param data contains the texture data
  94777. * @param texture defines the BabylonJS internal texture
  94778. * @param callback defines the method to call once ready to upload
  94779. */
  94780. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  94781. var info = BABYLON.DDSTools.GetDDSInfo(data);
  94782. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  94783. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  94784. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  94785. });
  94786. };
  94787. return DDSTextureLoader;
  94788. }());
  94789. // Register the loader.
  94790. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  94791. })(BABYLON || (BABYLON = {}));
  94792. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  94793. var BABYLON;
  94794. (function (BABYLON) {
  94795. /**
  94796. * Based on jsTGALoader - Javascript loader for TGA file
  94797. * By Vincent Thibault
  94798. * @see http://blog.robrowser.com/javascript-tga-loader.html
  94799. */
  94800. var TGATools = /** @class */ (function () {
  94801. function TGATools() {
  94802. }
  94803. /**
  94804. * Gets the header of a TGA file
  94805. * @param data defines the TGA data
  94806. * @returns the header
  94807. */
  94808. TGATools.GetTGAHeader = function (data) {
  94809. var offset = 0;
  94810. var header = {
  94811. id_length: data[offset++],
  94812. colormap_type: data[offset++],
  94813. image_type: data[offset++],
  94814. colormap_index: data[offset++] | data[offset++] << 8,
  94815. colormap_length: data[offset++] | data[offset++] << 8,
  94816. colormap_size: data[offset++],
  94817. origin: [
  94818. data[offset++] | data[offset++] << 8,
  94819. data[offset++] | data[offset++] << 8
  94820. ],
  94821. width: data[offset++] | data[offset++] << 8,
  94822. height: data[offset++] | data[offset++] << 8,
  94823. pixel_size: data[offset++],
  94824. flags: data[offset++]
  94825. };
  94826. return header;
  94827. };
  94828. /**
  94829. * Uploads TGA content to a Babylon Texture
  94830. * @hidden
  94831. */
  94832. TGATools.UploadContent = function (texture, data) {
  94833. // Not enough data to contain header ?
  94834. if (data.length < 19) {
  94835. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  94836. return;
  94837. }
  94838. // Read Header
  94839. var offset = 18;
  94840. var header = TGATools.GetTGAHeader(data);
  94841. // Assume it's a valid Targa file.
  94842. if (header.id_length + offset > data.length) {
  94843. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  94844. return;
  94845. }
  94846. // Skip not needed data
  94847. offset += header.id_length;
  94848. var use_rle = false;
  94849. var use_pal = false;
  94850. var use_grey = false;
  94851. // Get some informations.
  94852. switch (header.image_type) {
  94853. case TGATools._TYPE_RLE_INDEXED:
  94854. use_rle = true;
  94855. case TGATools._TYPE_INDEXED:
  94856. use_pal = true;
  94857. break;
  94858. case TGATools._TYPE_RLE_RGB:
  94859. use_rle = true;
  94860. case TGATools._TYPE_RGB:
  94861. // use_rgb = true;
  94862. break;
  94863. case TGATools._TYPE_RLE_GREY:
  94864. use_rle = true;
  94865. case TGATools._TYPE_GREY:
  94866. use_grey = true;
  94867. break;
  94868. }
  94869. var pixel_data;
  94870. // var numAlphaBits = header.flags & 0xf;
  94871. var pixel_size = header.pixel_size >> 3;
  94872. var pixel_total = header.width * header.height * pixel_size;
  94873. // Read palettes
  94874. var palettes;
  94875. if (use_pal) {
  94876. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  94877. }
  94878. // Read LRE
  94879. if (use_rle) {
  94880. pixel_data = new Uint8Array(pixel_total);
  94881. var c, count, i;
  94882. var localOffset = 0;
  94883. var pixels = new Uint8Array(pixel_size);
  94884. while (offset < pixel_total && localOffset < pixel_total) {
  94885. c = data[offset++];
  94886. count = (c & 0x7f) + 1;
  94887. // RLE pixels
  94888. if (c & 0x80) {
  94889. // Bind pixel tmp array
  94890. for (i = 0; i < pixel_size; ++i) {
  94891. pixels[i] = data[offset++];
  94892. }
  94893. // Copy pixel array
  94894. for (i = 0; i < count; ++i) {
  94895. pixel_data.set(pixels, localOffset + i * pixel_size);
  94896. }
  94897. localOffset += pixel_size * count;
  94898. }
  94899. // Raw pixels
  94900. else {
  94901. count *= pixel_size;
  94902. for (i = 0; i < count; ++i) {
  94903. pixel_data[localOffset + i] = data[offset++];
  94904. }
  94905. localOffset += count;
  94906. }
  94907. }
  94908. }
  94909. // RAW Pixels
  94910. else {
  94911. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  94912. }
  94913. // Load to texture
  94914. var x_start, y_start, x_step, y_step, y_end, x_end;
  94915. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  94916. default:
  94917. case TGATools._ORIGIN_UL:
  94918. x_start = 0;
  94919. x_step = 1;
  94920. x_end = header.width;
  94921. y_start = 0;
  94922. y_step = 1;
  94923. y_end = header.height;
  94924. break;
  94925. case TGATools._ORIGIN_BL:
  94926. x_start = 0;
  94927. x_step = 1;
  94928. x_end = header.width;
  94929. y_start = header.height - 1;
  94930. y_step = -1;
  94931. y_end = -1;
  94932. break;
  94933. case TGATools._ORIGIN_UR:
  94934. x_start = header.width - 1;
  94935. x_step = -1;
  94936. x_end = -1;
  94937. y_start = 0;
  94938. y_step = 1;
  94939. y_end = header.height;
  94940. break;
  94941. case TGATools._ORIGIN_BR:
  94942. x_start = header.width - 1;
  94943. x_step = -1;
  94944. x_end = -1;
  94945. y_start = header.height - 1;
  94946. y_step = -1;
  94947. y_end = -1;
  94948. break;
  94949. }
  94950. // Load the specify method
  94951. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  94952. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  94953. var engine = texture.getEngine();
  94954. engine._uploadDataToTextureDirectly(texture, imageData);
  94955. };
  94956. /** @hidden */
  94957. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94958. var image = pixel_data, colormap = palettes;
  94959. var width = header.width, height = header.height;
  94960. var color, i = 0, x, y;
  94961. var imageData = new Uint8Array(width * height * 4);
  94962. for (y = y_start; y !== y_end; y += y_step) {
  94963. for (x = x_start; x !== x_end; x += x_step, i++) {
  94964. color = image[i];
  94965. imageData[(x + width * y) * 4 + 3] = 255;
  94966. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  94967. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  94968. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  94969. }
  94970. }
  94971. return imageData;
  94972. };
  94973. /** @hidden */
  94974. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94975. var image = pixel_data;
  94976. var width = header.width, height = header.height;
  94977. var color, i = 0, x, y;
  94978. var imageData = new Uint8Array(width * height * 4);
  94979. for (y = y_start; y !== y_end; y += y_step) {
  94980. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  94981. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  94982. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  94983. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  94984. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  94985. imageData[(x + width * y) * 4 + 0] = r;
  94986. imageData[(x + width * y) * 4 + 1] = g;
  94987. imageData[(x + width * y) * 4 + 2] = b;
  94988. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  94989. }
  94990. }
  94991. return imageData;
  94992. };
  94993. /** @hidden */
  94994. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94995. var image = pixel_data;
  94996. var width = header.width, height = header.height;
  94997. var i = 0, x, y;
  94998. var imageData = new Uint8Array(width * height * 4);
  94999. for (y = y_start; y !== y_end; y += y_step) {
  95000. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  95001. imageData[(x + width * y) * 4 + 3] = 255;
  95002. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  95003. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  95004. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  95005. }
  95006. }
  95007. return imageData;
  95008. };
  95009. /** @hidden */
  95010. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  95011. var image = pixel_data;
  95012. var width = header.width, height = header.height;
  95013. var i = 0, x, y;
  95014. var imageData = new Uint8Array(width * height * 4);
  95015. for (y = y_start; y !== y_end; y += y_step) {
  95016. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  95017. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  95018. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  95019. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  95020. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  95021. }
  95022. }
  95023. return imageData;
  95024. };
  95025. /** @hidden */
  95026. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  95027. var image = pixel_data;
  95028. var width = header.width, height = header.height;
  95029. var color, i = 0, x, y;
  95030. var imageData = new Uint8Array(width * height * 4);
  95031. for (y = y_start; y !== y_end; y += y_step) {
  95032. for (x = x_start; x !== x_end; x += x_step, i++) {
  95033. color = image[i];
  95034. imageData[(x + width * y) * 4 + 0] = color;
  95035. imageData[(x + width * y) * 4 + 1] = color;
  95036. imageData[(x + width * y) * 4 + 2] = color;
  95037. imageData[(x + width * y) * 4 + 3] = 255;
  95038. }
  95039. }
  95040. return imageData;
  95041. };
  95042. /** @hidden */
  95043. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  95044. var image = pixel_data;
  95045. var width = header.width, height = header.height;
  95046. var i = 0, x, y;
  95047. var imageData = new Uint8Array(width * height * 4);
  95048. for (y = y_start; y !== y_end; y += y_step) {
  95049. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  95050. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  95051. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  95052. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  95053. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  95054. }
  95055. }
  95056. return imageData;
  95057. };
  95058. //private static _TYPE_NO_DATA = 0;
  95059. TGATools._TYPE_INDEXED = 1;
  95060. TGATools._TYPE_RGB = 2;
  95061. TGATools._TYPE_GREY = 3;
  95062. TGATools._TYPE_RLE_INDEXED = 9;
  95063. TGATools._TYPE_RLE_RGB = 10;
  95064. TGATools._TYPE_RLE_GREY = 11;
  95065. TGATools._ORIGIN_MASK = 0x30;
  95066. TGATools._ORIGIN_SHIFT = 0x04;
  95067. TGATools._ORIGIN_BL = 0x00;
  95068. TGATools._ORIGIN_BR = 0x01;
  95069. TGATools._ORIGIN_UL = 0x02;
  95070. TGATools._ORIGIN_UR = 0x03;
  95071. return TGATools;
  95072. }());
  95073. BABYLON.TGATools = TGATools;
  95074. })(BABYLON || (BABYLON = {}));
  95075. //# sourceMappingURL=babylon.tga.js.map
  95076. var BABYLON;
  95077. (function (BABYLON) {
  95078. /**
  95079. * Implementation of the TGA Texture Loader.
  95080. */
  95081. var TGATextureLoader = /** @class */ (function () {
  95082. function TGATextureLoader() {
  95083. /**
  95084. * Defines wether the loader supports cascade loading the different faces.
  95085. */
  95086. this.supportCascades = false;
  95087. }
  95088. /**
  95089. * This returns if the loader support the current file information.
  95090. * @param extension defines the file extension of the file being loaded
  95091. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95092. * @param fallback defines the fallback internal texture if any
  95093. * @param isBase64 defines whether the texture is encoded as a base64
  95094. * @param isBuffer defines whether the texture data are stored as a buffer
  95095. * @returns true if the loader can load the specified file
  95096. */
  95097. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  95098. return extension.indexOf(".tga") === 0;
  95099. };
  95100. /**
  95101. * Transform the url before loading if required.
  95102. * @param rootUrl the url of the texture
  95103. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95104. * @returns the transformed texture
  95105. */
  95106. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  95107. return rootUrl;
  95108. };
  95109. /**
  95110. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  95111. * @param rootUrl the url of the texture
  95112. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95113. * @returns the fallback texture
  95114. */
  95115. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  95116. return null;
  95117. };
  95118. /**
  95119. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  95120. * @param data contains the texture data
  95121. * @param texture defines the BabylonJS internal texture
  95122. * @param createPolynomials will be true if polynomials have been requested
  95123. * @param onLoad defines the callback to trigger once the texture is ready
  95124. * @param onError defines the callback to trigger in case of error
  95125. */
  95126. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  95127. throw ".env not supported in Cube.";
  95128. };
  95129. /**
  95130. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  95131. * @param data contains the texture data
  95132. * @param texture defines the BabylonJS internal texture
  95133. * @param callback defines the method to call once ready to upload
  95134. */
  95135. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  95136. var uintData = new Uint8Array(data);
  95137. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  95138. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  95139. BABYLON.TGATools.UploadContent(texture, uintData);
  95140. });
  95141. };
  95142. return TGATextureLoader;
  95143. }());
  95144. // Register the loader.
  95145. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  95146. })(BABYLON || (BABYLON = {}));
  95147. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  95148. var BABYLON;
  95149. (function (BABYLON) {
  95150. /**
  95151. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  95152. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  95153. */
  95154. var KhronosTextureContainer = /** @class */ (function () {
  95155. /**
  95156. * Creates a new KhronosTextureContainer
  95157. * @param arrayBuffer contents of the KTX container file
  95158. * @param facesExpected should be either 1 or 6, based whether a cube texture or or
  95159. * @param threeDExpected provision for indicating that data should be a 3D texture, not implemented
  95160. * @param textureArrayExpected provision for indicating that data should be a texture array, not implemented
  95161. */
  95162. function KhronosTextureContainer(
  95163. /** contents of the KTX container file */
  95164. arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  95165. this.arrayBuffer = arrayBuffer;
  95166. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  95167. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  95168. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  95169. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  95170. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  95171. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  95172. BABYLON.Tools.Error("texture missing KTX identifier");
  95173. return;
  95174. }
  95175. // load the reset of the header in native 32 bit int
  95176. var header = new Int32Array(this.arrayBuffer, 12, 13);
  95177. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  95178. var oppositeEndianess = header[0] === 0x01020304;
  95179. // read all the header elements in order they exist in the file, without modification (sans endainness)
  95180. this.glType = oppositeEndianess ? this.switchEndianness(header[1]) : header[1]; // must be 0 for compressed textures
  95181. this.glTypeSize = oppositeEndianess ? this.switchEndianness(header[2]) : header[2]; // must be 1 for compressed textures
  95182. this.glFormat = oppositeEndianess ? this.switchEndianness(header[3]) : header[3]; // must be 0 for compressed textures
  95183. this.glInternalFormat = oppositeEndianess ? this.switchEndianness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  95184. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndianness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  95185. this.pixelWidth = oppositeEndianess ? this.switchEndianness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  95186. this.pixelHeight = oppositeEndianess ? this.switchEndianness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  95187. this.pixelDepth = oppositeEndianess ? this.switchEndianness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  95188. this.numberOfArrayElements = oppositeEndianess ? this.switchEndianness(header[9]) : header[9]; // used for texture arrays
  95189. this.numberOfFaces = oppositeEndianess ? this.switchEndianness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  95190. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndianness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  95191. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndianness(header[12]) : header[12]; // the amount of space after the header for meta-data
  95192. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  95193. if (this.glType !== 0) {
  95194. BABYLON.Tools.Error("only compressed formats currently supported");
  95195. return;
  95196. }
  95197. else {
  95198. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  95199. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  95200. }
  95201. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  95202. BABYLON.Tools.Error("only 2D textures currently supported");
  95203. return;
  95204. }
  95205. if (this.numberOfArrayElements !== 0) {
  95206. BABYLON.Tools.Error("texture arrays not currently supported");
  95207. return;
  95208. }
  95209. if (this.numberOfFaces !== facesExpected) {
  95210. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  95211. return;
  95212. }
  95213. // we now have a completely validated file, so could use existence of loadType as success
  95214. // would need to make this more elaborate & adjust checks above to support more than one load type
  95215. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  95216. }
  95217. //
  95218. /**
  95219. * Revert the endianness of a value.
  95220. * Not as fast hardware based, but will probably never need to use
  95221. * @param val defines the value to convert
  95222. * @returns the new value
  95223. */
  95224. KhronosTextureContainer.prototype.switchEndianness = function (val) {
  95225. return ((val & 0xFF) << 24)
  95226. | ((val & 0xFF00) << 8)
  95227. | ((val >> 8) & 0xFF00)
  95228. | ((val >> 24) & 0xFF);
  95229. };
  95230. /**
  95231. * Uploads KTX content to a Babylon Texture.
  95232. * It is assumed that the texture has already been created & is currently bound
  95233. * @hidden
  95234. */
  95235. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  95236. switch (this.loadType) {
  95237. case KhronosTextureContainer.COMPRESSED_2D:
  95238. this._upload2DCompressedLevels(texture, loadMipmaps);
  95239. break;
  95240. case KhronosTextureContainer.TEX_2D:
  95241. case KhronosTextureContainer.COMPRESSED_3D:
  95242. case KhronosTextureContainer.TEX_3D:
  95243. }
  95244. };
  95245. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  95246. // initialize width & height for level 1
  95247. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  95248. var width = this.pixelWidth;
  95249. var height = this.pixelHeight;
  95250. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  95251. for (var level = 0; level < mipmapCount; level++) {
  95252. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  95253. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  95254. for (var face = 0; face < this.numberOfFaces; face++) {
  95255. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  95256. var engine = texture.getEngine();
  95257. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  95258. dataOffset += imageSize; // add size of the image for the next face/mipmap
  95259. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  95260. }
  95261. width = Math.max(1.0, width * 0.5);
  95262. height = Math.max(1.0, height * 0.5);
  95263. }
  95264. };
  95265. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  95266. // load types
  95267. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  95268. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  95269. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  95270. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  95271. return KhronosTextureContainer;
  95272. }());
  95273. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  95274. })(BABYLON || (BABYLON = {}));
  95275. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  95276. var BABYLON;
  95277. (function (BABYLON) {
  95278. /**
  95279. * Implementation of the KTX Texture Loader.
  95280. */
  95281. var KTXTextureLoader = /** @class */ (function () {
  95282. function KTXTextureLoader() {
  95283. /**
  95284. * Defines wether the loader supports cascade loading the different faces.
  95285. */
  95286. this.supportCascades = false;
  95287. }
  95288. /**
  95289. * This returns if the loader support the current file information.
  95290. * @param extension defines the file extension of the file being loaded
  95291. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95292. * @param fallback defines the fallback internal texture if any
  95293. * @param isBase64 defines whether the texture is encoded as a base64
  95294. * @param isBuffer defines whether the texture data are stored as a buffer
  95295. * @returns true if the loader can load the specified file
  95296. */
  95297. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  95298. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  95299. return true;
  95300. }
  95301. return false;
  95302. };
  95303. /**
  95304. * Transform the url before loading if required.
  95305. * @param rootUrl the url of the texture
  95306. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95307. * @returns the transformed texture
  95308. */
  95309. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  95310. var lastDot = rootUrl.lastIndexOf('.');
  95311. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  95312. };
  95313. /**
  95314. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  95315. * @param rootUrl the url of the texture
  95316. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95317. * @returns the fallback texture
  95318. */
  95319. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  95320. // remove the format appended to the rootUrl in the original createCubeTexture call.
  95321. var exp = new RegExp("" + textureFormatInUse + "$");
  95322. return rootUrl.replace(exp, "");
  95323. };
  95324. /**
  95325. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  95326. * @param data contains the texture data
  95327. * @param texture defines the BabylonJS internal texture
  95328. * @param createPolynomials will be true if polynomials have been requested
  95329. * @param onLoad defines the callback to trigger once the texture is ready
  95330. * @param onError defines the callback to trigger in case of error
  95331. */
  95332. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  95333. if (Array.isArray(data)) {
  95334. return;
  95335. }
  95336. var engine = texture.getEngine();
  95337. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  95338. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  95339. engine._unpackFlipY(true);
  95340. ktx.uploadLevels(texture, texture.generateMipMaps);
  95341. texture.width = ktx.pixelWidth;
  95342. texture.height = ktx.pixelHeight;
  95343. engine._setCubeMapTextureParams(loadMipmap);
  95344. texture.isReady = true;
  95345. };
  95346. /**
  95347. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  95348. * @param data contains the texture data
  95349. * @param texture defines the BabylonJS internal texture
  95350. * @param callback defines the method to call once ready to upload
  95351. */
  95352. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  95353. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  95354. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  95355. ktx.uploadLevels(texture, texture.generateMipMaps);
  95356. });
  95357. };
  95358. return KTXTextureLoader;
  95359. }());
  95360. // Register the loader.
  95361. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  95362. })(BABYLON || (BABYLON = {}));
  95363. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  95364. var BABYLON;
  95365. (function (BABYLON) {
  95366. /**
  95367. * Sets of helpers addressing the serialization and deserialization of environment texture
  95368. * stored in a BabylonJS env file.
  95369. * Those files are usually stored as .env files.
  95370. */
  95371. var EnvironmentTextureTools = /** @class */ (function () {
  95372. function EnvironmentTextureTools() {
  95373. }
  95374. /**
  95375. * Gets the environment info from an env file.
  95376. * @param data The array buffer containing the .env bytes.
  95377. * @returns the environment file info (the json header) if successfully parsed.
  95378. */
  95379. EnvironmentTextureTools.GetEnvInfo = function (data) {
  95380. var dataView = new DataView(data);
  95381. var pos = 0;
  95382. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  95383. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  95384. BABYLON.Tools.Error('Not a babylon environment map');
  95385. return null;
  95386. }
  95387. }
  95388. // Read json manifest - collect characters up to null terminator
  95389. var manifestString = '';
  95390. var charCode = 0x00;
  95391. while ((charCode = dataView.getUint8(pos++))) {
  95392. manifestString += String.fromCharCode(charCode);
  95393. }
  95394. var manifest = JSON.parse(manifestString);
  95395. if (manifest.specular) {
  95396. // Extend the header with the position of the payload.
  95397. manifest.specular.specularDataPosition = pos;
  95398. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  95399. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  95400. }
  95401. return manifest;
  95402. };
  95403. /**
  95404. * Creates an environment texture from a loaded cube texture.
  95405. * @param texture defines the cube texture to convert in env file
  95406. * @return a promise containing the environment data if succesfull.
  95407. */
  95408. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  95409. var _this = this;
  95410. var internalTexture = texture.getInternalTexture();
  95411. if (!internalTexture) {
  95412. return Promise.reject("The cube texture is invalid.");
  95413. }
  95414. if (!texture._prefiltered) {
  95415. return Promise.reject("The cube texture is invalid (not prefiltered).");
  95416. }
  95417. var engine = internalTexture.getEngine();
  95418. if (engine && engine.premultipliedAlpha) {
  95419. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  95420. }
  95421. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  95422. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  95423. }
  95424. var canvas = engine.getRenderingCanvas();
  95425. if (!canvas) {
  95426. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  95427. }
  95428. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  95429. if (!engine.getCaps().textureFloatRender) {
  95430. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95431. if (!engine.getCaps().textureHalfFloatRender) {
  95432. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  95433. }
  95434. }
  95435. var cubeWidth = internalTexture.width;
  95436. var hostingScene = new BABYLON.Scene(engine);
  95437. var specularTextures = {};
  95438. var promises = [];
  95439. // Read and collect all mipmaps data from the cube.
  95440. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  95441. mipmapsCount = Math.round(mipmapsCount);
  95442. var _loop_1 = function (i) {
  95443. var faceWidth = Math.pow(2, mipmapsCount - i);
  95444. var _loop_2 = function (face) {
  95445. var data = texture.readPixels(face, i);
  95446. // Creates a temp texture with the face data.
  95447. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  95448. // And rgbdEncode them.
  95449. var promise = new Promise(function (resolve, reject) {
  95450. 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);
  95451. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  95452. rgbdPostProcess.onApply = function (effect) {
  95453. effect._bindTexture("textureSampler", tempTexture);
  95454. };
  95455. // As the process needs to happen on the main canvas, keep track of the current size
  95456. var currentW = engine.getRenderWidth();
  95457. var currentH = engine.getRenderHeight();
  95458. // Set the desired size for the texture
  95459. engine.setSize(faceWidth, faceWidth);
  95460. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  95461. // Reading datas from WebGL
  95462. BABYLON.Tools.ToBlob(canvas, function (blob) {
  95463. var fileReader = new FileReader();
  95464. fileReader.onload = function (event) {
  95465. var arrayBuffer = event.target.result;
  95466. specularTextures[i * 6 + face] = arrayBuffer;
  95467. resolve();
  95468. };
  95469. fileReader.readAsArrayBuffer(blob);
  95470. });
  95471. // Reapply the previous canvas size
  95472. engine.setSize(currentW, currentH);
  95473. });
  95474. });
  95475. promises.push(promise);
  95476. };
  95477. // All faces of the cube.
  95478. for (var face = 0; face < 6; face++) {
  95479. _loop_2(face);
  95480. }
  95481. };
  95482. for (var i = 0; i <= mipmapsCount; i++) {
  95483. _loop_1(i);
  95484. }
  95485. // Once all the textures haves been collected as RGBD stored in PNGs
  95486. return Promise.all(promises).then(function () {
  95487. // We can delete the hosting scene keeping track of all the creation objects
  95488. hostingScene.dispose();
  95489. // Creates the json header for the env texture
  95490. var info = {
  95491. version: 1,
  95492. width: cubeWidth,
  95493. irradiance: _this._CreateEnvTextureIrradiance(texture),
  95494. specular: {
  95495. mipmaps: [],
  95496. lodGenerationScale: texture.lodGenerationScale
  95497. }
  95498. };
  95499. // Sets the specular image data information
  95500. var position = 0;
  95501. for (var i = 0; i <= mipmapsCount; i++) {
  95502. for (var face = 0; face < 6; face++) {
  95503. var byteLength = specularTextures[i * 6 + face].byteLength;
  95504. info.specular.mipmaps.push({
  95505. length: byteLength,
  95506. position: position
  95507. });
  95508. position += byteLength;
  95509. }
  95510. }
  95511. // Encode the JSON as an array buffer
  95512. var infoString = JSON.stringify(info);
  95513. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  95514. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  95515. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  95516. infoView[i] = infoString.charCodeAt(i);
  95517. }
  95518. // Ends up with a null terminator for easier parsing
  95519. infoView[infoString.length] = 0x00;
  95520. // Computes the final required size and creates the storage
  95521. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  95522. var finalBuffer = new ArrayBuffer(totalSize);
  95523. var finalBufferView = new Uint8Array(finalBuffer);
  95524. var dataView = new DataView(finalBuffer);
  95525. // Copy the magic bytes identifying the file in
  95526. var pos = 0;
  95527. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  95528. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  95529. }
  95530. // Add the json info
  95531. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  95532. pos += infoBuffer.byteLength;
  95533. // Finally inserts the texture data
  95534. for (var i = 0; i <= mipmapsCount; i++) {
  95535. for (var face = 0; face < 6; face++) {
  95536. var dataBuffer = specularTextures[i * 6 + face];
  95537. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  95538. pos += dataBuffer.byteLength;
  95539. }
  95540. }
  95541. // Voila
  95542. return finalBuffer;
  95543. });
  95544. };
  95545. /**
  95546. * Creates a JSON representation of the spherical data.
  95547. * @param texture defines the texture containing the polynomials
  95548. * @return the JSON representation of the spherical info
  95549. */
  95550. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  95551. var polynmials = texture.sphericalPolynomial;
  95552. if (polynmials == null) {
  95553. return null;
  95554. }
  95555. return {
  95556. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  95557. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  95558. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  95559. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  95560. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  95561. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  95562. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  95563. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  95564. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  95565. };
  95566. };
  95567. /**
  95568. * Uploads the texture info contained in the env file to the GPU.
  95569. * @param texture defines the internal texture to upload to
  95570. * @param arrayBuffer defines the buffer cotaining the data to load
  95571. * @param info defines the texture info retrieved through the GetEnvInfo method
  95572. * @returns a promise
  95573. */
  95574. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  95575. if (info.version !== 1) {
  95576. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  95577. }
  95578. var specularInfo = info.specular;
  95579. if (!specularInfo) {
  95580. // Nothing else parsed so far
  95581. return Promise.resolve();
  95582. }
  95583. // Double checks the enclosed info
  95584. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  95585. mipmapsCount = Math.round(mipmapsCount) + 1;
  95586. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  95587. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  95588. }
  95589. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  95590. var imageData = new Array(mipmapsCount);
  95591. for (var i = 0; i < mipmapsCount; i++) {
  95592. imageData[i] = new Array(6);
  95593. for (var face = 0; face < 6; face++) {
  95594. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  95595. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  95596. }
  95597. }
  95598. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  95599. };
  95600. /**
  95601. * Uploads the levels of image data to the GPU.
  95602. * @param texture defines the internal texture to upload to
  95603. * @param imageData defines the array buffer views of image data [mipmap][face]
  95604. * @returns a promise
  95605. */
  95606. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  95607. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  95608. throw new Error("Texture size must be a power of two");
  95609. }
  95610. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  95611. // Gets everything ready.
  95612. var engine = texture.getEngine();
  95613. var expandTexture = false;
  95614. var generateNonLODTextures = false;
  95615. var rgbdPostProcess = null;
  95616. var cubeRtt = null;
  95617. var lodTextures = null;
  95618. var caps = engine.getCaps();
  95619. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  95620. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95621. texture.generateMipMaps = true;
  95622. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  95623. // Add extra process if texture lod is not supported
  95624. if (!caps.textureLOD) {
  95625. expandTexture = false;
  95626. generateNonLODTextures = true;
  95627. lodTextures = {};
  95628. }
  95629. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  95630. else if (engine.webGLVersion < 2) {
  95631. expandTexture = false;
  95632. }
  95633. // If half float available we can uncompress the texture
  95634. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  95635. expandTexture = true;
  95636. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95637. }
  95638. // If full float available we can uncompress the texture
  95639. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  95640. expandTexture = true;
  95641. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  95642. }
  95643. // Expand the texture if possible
  95644. if (expandTexture) {
  95645. // Simply run through the decode PP
  95646. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  95647. texture._isRGBD = false;
  95648. texture.invertY = false;
  95649. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  95650. generateDepthBuffer: false,
  95651. generateMipMaps: true,
  95652. generateStencilBuffer: false,
  95653. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  95654. type: texture.type,
  95655. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  95656. });
  95657. }
  95658. else {
  95659. texture._isRGBD = true;
  95660. texture.invertY = true;
  95661. // In case of missing support, applies the same patch than DDS files.
  95662. if (generateNonLODTextures) {
  95663. var mipSlices = 3;
  95664. var scale = texture._lodGenerationScale;
  95665. var offset = texture._lodGenerationOffset;
  95666. for (var i = 0; i < mipSlices; i++) {
  95667. //compute LOD from even spacing in smoothness (matching shader calculation)
  95668. var smoothness = i / (mipSlices - 1);
  95669. var roughness = 1 - smoothness;
  95670. var minLODIndex = offset; // roughness = 0
  95671. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  95672. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  95673. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  95674. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  95675. glTextureFromLod.isCube = true;
  95676. glTextureFromLod.invertY = true;
  95677. glTextureFromLod.generateMipMaps = false;
  95678. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  95679. // Wrap in a base texture for easy binding.
  95680. var lodTexture = new BABYLON.BaseTexture(null);
  95681. lodTexture.isCube = true;
  95682. lodTexture._texture = glTextureFromLod;
  95683. lodTextures[mipmapIndex] = lodTexture;
  95684. switch (i) {
  95685. case 0:
  95686. texture._lodTextureLow = lodTexture;
  95687. break;
  95688. case 1:
  95689. texture._lodTextureMid = lodTexture;
  95690. break;
  95691. case 2:
  95692. texture._lodTextureHigh = lodTexture;
  95693. break;
  95694. }
  95695. }
  95696. }
  95697. }
  95698. var promises = [];
  95699. var _loop_3 = function (i) {
  95700. var _loop_4 = function (face) {
  95701. // Constructs an image element from image data
  95702. var bytes = imageData[i][face];
  95703. var blob = new Blob([bytes], { type: 'image/png' });
  95704. var url = URL.createObjectURL(blob);
  95705. var image = new Image();
  95706. image.src = url;
  95707. // Enqueue promise to upload to the texture.
  95708. var promise = new Promise(function (resolve, reject) {
  95709. image.onload = function () {
  95710. if (expandTexture) {
  95711. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  95712. reject(message);
  95713. }, image);
  95714. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  95715. // Uncompress the data to a RTT
  95716. rgbdPostProcess.onApply = function (effect) {
  95717. effect._bindTexture("textureSampler", tempTexture_1);
  95718. effect.setFloat2("scale", 1, 1);
  95719. };
  95720. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  95721. // Cleanup
  95722. engine.restoreDefaultFramebuffer();
  95723. tempTexture_1.dispose();
  95724. window.URL.revokeObjectURL(url);
  95725. resolve();
  95726. });
  95727. }
  95728. else {
  95729. engine._uploadImageToTexture(texture, image, face, i);
  95730. // Upload the face to the non lod texture support
  95731. if (generateNonLODTextures) {
  95732. var lodTexture = lodTextures[i];
  95733. if (lodTexture) {
  95734. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  95735. }
  95736. }
  95737. resolve();
  95738. }
  95739. };
  95740. image.onerror = function (error) {
  95741. reject(error);
  95742. };
  95743. });
  95744. promises.push(promise);
  95745. };
  95746. // All faces
  95747. for (var face = 0; face < 6; face++) {
  95748. _loop_4(face);
  95749. }
  95750. };
  95751. // All mipmaps up to provided number of images
  95752. for (var i = 0; i < imageData.length; i++) {
  95753. _loop_3(i);
  95754. }
  95755. // Fill remaining mipmaps with black textures.
  95756. if (imageData.length < mipmapsCount) {
  95757. var data = void 0;
  95758. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  95759. var dataLength = size * size * 4;
  95760. switch (texture.type) {
  95761. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  95762. data = new Uint8Array(dataLength);
  95763. break;
  95764. }
  95765. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  95766. data = new Uint16Array(dataLength);
  95767. break;
  95768. }
  95769. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  95770. data = new Float32Array(dataLength);
  95771. break;
  95772. }
  95773. }
  95774. for (var i = imageData.length; i < mipmapsCount; i++) {
  95775. for (var face = 0; face < 6; face++) {
  95776. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  95777. }
  95778. }
  95779. }
  95780. // Once all done, finishes the cleanup and return
  95781. return Promise.all(promises).then(function () {
  95782. // Release temp RTT.
  95783. if (cubeRtt) {
  95784. engine._releaseFramebufferObjects(cubeRtt);
  95785. cubeRtt._swapAndDie(texture);
  95786. }
  95787. // Release temp Post Process.
  95788. if (rgbdPostProcess) {
  95789. rgbdPostProcess.dispose();
  95790. }
  95791. // Flag internal texture as ready in case they are in use.
  95792. if (generateNonLODTextures) {
  95793. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  95794. texture._lodTextureHigh._texture.isReady = true;
  95795. }
  95796. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  95797. texture._lodTextureMid._texture.isReady = true;
  95798. }
  95799. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  95800. texture._lodTextureLow._texture.isReady = true;
  95801. }
  95802. }
  95803. });
  95804. };
  95805. /**
  95806. * Uploads spherical polynomials information to the texture.
  95807. * @param texture defines the texture we are trying to upload the information to
  95808. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  95809. */
  95810. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  95811. if (info.version !== 1) {
  95812. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  95813. }
  95814. var irradianceInfo = info.irradiance;
  95815. if (!irradianceInfo) {
  95816. return;
  95817. }
  95818. var sp = new BABYLON.SphericalPolynomial();
  95819. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  95820. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  95821. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  95822. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  95823. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  95824. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  95825. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  95826. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  95827. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  95828. texture._sphericalPolynomial = sp;
  95829. };
  95830. /**
  95831. * Magic number identifying the env file.
  95832. */
  95833. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  95834. return EnvironmentTextureTools;
  95835. }());
  95836. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  95837. })(BABYLON || (BABYLON = {}));
  95838. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  95839. var BABYLON;
  95840. (function (BABYLON) {
  95841. /**
  95842. * Implementation of the ENV Texture Loader.
  95843. */
  95844. var ENVTextureLoader = /** @class */ (function () {
  95845. function ENVTextureLoader() {
  95846. /**
  95847. * Defines wether the loader supports cascade loading the different faces.
  95848. */
  95849. this.supportCascades = false;
  95850. }
  95851. /**
  95852. * This returns if the loader support the current file information.
  95853. * @param extension defines the file extension of the file being loaded
  95854. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95855. * @param fallback defines the fallback internal texture if any
  95856. * @param isBase64 defines whether the texture is encoded as a base64
  95857. * @param isBuffer defines whether the texture data are stored as a buffer
  95858. * @returns true if the loader can load the specified file
  95859. */
  95860. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  95861. return extension.indexOf(".env") === 0;
  95862. };
  95863. /**
  95864. * Transform the url before loading if required.
  95865. * @param rootUrl the url of the texture
  95866. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95867. * @returns the transformed texture
  95868. */
  95869. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  95870. return rootUrl;
  95871. };
  95872. /**
  95873. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  95874. * @param rootUrl the url of the texture
  95875. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95876. * @returns the fallback texture
  95877. */
  95878. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  95879. return null;
  95880. };
  95881. /**
  95882. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  95883. * @param data contains the texture data
  95884. * @param texture defines the BabylonJS internal texture
  95885. * @param createPolynomials will be true if polynomials have been requested
  95886. * @param onLoad defines the callback to trigger once the texture is ready
  95887. * @param onError defines the callback to trigger in case of error
  95888. */
  95889. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  95890. if (Array.isArray(data)) {
  95891. return;
  95892. }
  95893. data = data;
  95894. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  95895. if (info) {
  95896. texture.width = info.width;
  95897. texture.height = info.width;
  95898. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  95899. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  95900. texture.isReady = true;
  95901. if (onLoad) {
  95902. onLoad();
  95903. }
  95904. });
  95905. }
  95906. else if (onError) {
  95907. onError("Can not parse the environment file", null);
  95908. }
  95909. };
  95910. /**
  95911. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  95912. * @param data contains the texture data
  95913. * @param texture defines the BabylonJS internal texture
  95914. * @param callback defines the method to call once ready to upload
  95915. */
  95916. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  95917. throw ".env not supported in 2d.";
  95918. };
  95919. return ENVTextureLoader;
  95920. }());
  95921. // Register the loader.
  95922. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  95923. })(BABYLON || (BABYLON = {}));
  95924. //# sourceMappingURL=babylon.envTextureLoader.js.map
  95925. var BABYLON;
  95926. (function (BABYLON) {
  95927. /**
  95928. * Renders a layer on top of an existing scene
  95929. */
  95930. var UtilityLayerRenderer = /** @class */ (function () {
  95931. /**
  95932. * Instantiates a UtilityLayerRenderer
  95933. * @param originalScene the original scene that will be rendered on top of
  95934. */
  95935. function UtilityLayerRenderer(
  95936. /** the original scene that will be rendered on top of */
  95937. originalScene) {
  95938. var _this = this;
  95939. this.originalScene = originalScene;
  95940. this._pointerCaptures = {};
  95941. this._lastPointerEvents = {};
  95942. /**
  95943. * If the utility layer should automatically be rendered on top of existing scene
  95944. */
  95945. this.shouldRender = true;
  95946. /**
  95947. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  95948. */
  95949. this.onlyCheckPointerDownEvents = true;
  95950. /**
  95951. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  95952. */
  95953. this.processAllEvents = false;
  95954. /**
  95955. * Observable raised when the pointer move from the utility layer scene to the main scene
  95956. */
  95957. this.onPointerOutObservable = new BABYLON.Observable();
  95958. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  95959. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  95960. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  95961. this.utilityLayerScene._allowPostProcessClearColor = false;
  95962. originalScene.getEngine().scenes.pop();
  95963. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  95964. this.utilityLayerScene.detachControl();
  95965. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  95966. if (!_this.processAllEvents) {
  95967. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  95968. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  95969. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  95970. return;
  95971. }
  95972. }
  95973. var pointerEvent = (prePointerInfo.event);
  95974. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  95975. _this._pointerCaptures[pointerEvent.pointerId] = false;
  95976. return;
  95977. }
  95978. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  95979. if (!prePointerInfo.ray && utilityScenePick) {
  95980. prePointerInfo.ray = utilityScenePick.ray;
  95981. }
  95982. // always fire the prepointer oversvable
  95983. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  95984. // allow every non pointer down event to flow to the utility layer
  95985. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  95986. if (!prePointerInfo.skipOnPointerObservable) {
  95987. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  95988. }
  95989. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  95990. _this._pointerCaptures[pointerEvent.pointerId] = false;
  95991. }
  95992. return;
  95993. }
  95994. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  95995. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  95996. if (utilityScenePick && utilityScenePick.hit) {
  95997. if (!prePointerInfo.skipOnPointerObservable) {
  95998. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  95999. }
  96000. prePointerInfo.skipOnPointerObservable = true;
  96001. }
  96002. }
  96003. else {
  96004. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  96005. var pointerEvent_1 = (prePointerInfo.event);
  96006. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  96007. if (originalScenePick && utilityScenePick) {
  96008. // No pick in utility scene
  96009. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  96010. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  96011. // We touched an utility mesh present in the main scene
  96012. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  96013. prePointerInfo.skipOnPointerObservable = true;
  96014. }
  96015. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  96016. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  96017. }
  96018. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  96019. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  96020. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  96021. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  96022. }
  96023. }
  96024. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  96025. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  96026. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  96027. // If a previous utility layer set this, do not unset this
  96028. if (!prePointerInfo.skipOnPointerObservable) {
  96029. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  96030. }
  96031. }
  96032. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  96033. // We have a pick in both scenes but main is closer than utility
  96034. // We touched an utility mesh present in the main scene
  96035. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  96036. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  96037. prePointerInfo.skipOnPointerObservable = true;
  96038. }
  96039. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  96040. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  96041. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  96042. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  96043. }
  96044. }
  96045. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  96046. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  96047. }
  96048. }
  96049. }
  96050. });
  96051. // Render directly on top of existing scene without clearing
  96052. this.utilityLayerScene.autoClear = false;
  96053. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  96054. if (_this.shouldRender) {
  96055. _this.render();
  96056. }
  96057. });
  96058. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  96059. _this.dispose();
  96060. });
  96061. this._updateCamera();
  96062. }
  96063. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  96064. /**
  96065. * 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)
  96066. */
  96067. get: function () {
  96068. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  96069. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  96070. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  96071. UtilityLayerRenderer._DefaultUtilityLayer = null;
  96072. });
  96073. }
  96074. return UtilityLayerRenderer._DefaultUtilityLayer;
  96075. },
  96076. enumerable: true,
  96077. configurable: true
  96078. });
  96079. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  96080. /**
  96081. * 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)
  96082. */
  96083. get: function () {
  96084. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  96085. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  96086. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  96087. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  96088. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  96089. });
  96090. }
  96091. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  96092. },
  96093. enumerable: true,
  96094. configurable: true
  96095. });
  96096. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  96097. if (!prePointerInfo.skipOnPointerObservable) {
  96098. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  96099. this._lastPointerEvents[pointerEvent.pointerId] = true;
  96100. }
  96101. };
  96102. /**
  96103. * Renders the utility layers scene on top of the original scene
  96104. */
  96105. UtilityLayerRenderer.prototype.render = function () {
  96106. this._updateCamera();
  96107. if (this.utilityLayerScene.activeCamera) {
  96108. // Set the camera's scene to utility layers scene
  96109. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  96110. var camera = this.utilityLayerScene.activeCamera;
  96111. camera._scene = this.utilityLayerScene;
  96112. if (camera.leftCamera) {
  96113. camera.leftCamera._scene = this.utilityLayerScene;
  96114. }
  96115. if (camera.rightCamera) {
  96116. camera.rightCamera._scene = this.utilityLayerScene;
  96117. }
  96118. this.utilityLayerScene.render(false);
  96119. // Reset camera's scene back to original
  96120. camera._scene = oldScene;
  96121. if (camera.leftCamera) {
  96122. camera.leftCamera._scene = oldScene;
  96123. }
  96124. if (camera.rightCamera) {
  96125. camera.rightCamera._scene = oldScene;
  96126. }
  96127. }
  96128. };
  96129. /**
  96130. * Disposes of the renderer
  96131. */
  96132. UtilityLayerRenderer.prototype.dispose = function () {
  96133. this.onPointerOutObservable.clear();
  96134. if (this._afterRenderObserver) {
  96135. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  96136. }
  96137. if (this._sceneDisposeObserver) {
  96138. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  96139. }
  96140. if (this._originalPointerObserver) {
  96141. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  96142. }
  96143. this.utilityLayerScene.dispose();
  96144. };
  96145. UtilityLayerRenderer.prototype._updateCamera = function () {
  96146. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  96147. };
  96148. UtilityLayerRenderer._DefaultUtilityLayer = null;
  96149. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  96150. return UtilityLayerRenderer;
  96151. }());
  96152. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  96153. })(BABYLON || (BABYLON = {}));
  96154. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  96155. //# sourceMappingURL=babylon.behavior.js.map
  96156. var BABYLON;
  96157. (function (BABYLON) {
  96158. /**
  96159. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  96160. */
  96161. var PointerDragBehavior = /** @class */ (function () {
  96162. /**
  96163. * Creates a pointer drag behavior that can be attached to a mesh
  96164. * @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)
  96165. */
  96166. function PointerDragBehavior(options) {
  96167. /**
  96168. * 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)
  96169. */
  96170. this.maxDragAngle = 0;
  96171. /**
  96172. * @hidden
  96173. */
  96174. this._useAlternatePickedPointAboveMaxDragAngle = false;
  96175. /**
  96176. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  96177. */
  96178. this.currentDraggingPointerID = -1;
  96179. /**
  96180. * If the behavior is currently in a dragging state
  96181. */
  96182. this.dragging = false;
  96183. /**
  96184. * 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)
  96185. */
  96186. this.dragDeltaRatio = 0.2;
  96187. /**
  96188. * If the drag plane orientation should be updated during the dragging (Default: true)
  96189. */
  96190. this.updateDragPlane = true;
  96191. // Debug mode will display drag planes to help visualize behavior
  96192. this._debugMode = false;
  96193. this._moving = false;
  96194. /**
  96195. * Fires each time the attached mesh is dragged with the pointer
  96196. * * delta between last drag position and current drag position in world space
  96197. * * dragDistance along the drag axis
  96198. * * dragPlaneNormal normal of the current drag plane used during the drag
  96199. * * dragPlanePoint in world space where the drag intersects the drag plane
  96200. */
  96201. this.onDragObservable = new BABYLON.Observable();
  96202. /**
  96203. * Fires each time a drag begins (eg. mouse down on mesh)
  96204. */
  96205. this.onDragStartObservable = new BABYLON.Observable();
  96206. /**
  96207. * Fires each time a drag ends (eg. mouse release after drag)
  96208. */
  96209. this.onDragEndObservable = new BABYLON.Observable();
  96210. /**
  96211. * If the attached mesh should be moved when dragged
  96212. */
  96213. this.moveAttached = true;
  96214. /**
  96215. * If the drag behavior will react to drag events (Default: true)
  96216. */
  96217. this.enabled = true;
  96218. /**
  96219. * If camera controls should be detached during the drag
  96220. */
  96221. this.detachCameraControls = true;
  96222. /**
  96223. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  96224. */
  96225. this.useObjectOrienationForDragging = true;
  96226. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  96227. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  96228. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  96229. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  96230. this._attachedElement = null;
  96231. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  96232. this._lastPointerRay = {};
  96233. this._dragDelta = new BABYLON.Vector3();
  96234. // Variables to avoid instantiation in the below method
  96235. this._pointA = new BABYLON.Vector3(0, 0, 0);
  96236. this._pointB = new BABYLON.Vector3(0, 0, 0);
  96237. this._pointC = new BABYLON.Vector3(0, 0, 0);
  96238. this._lineA = new BABYLON.Vector3(0, 0, 0);
  96239. this._lineB = new BABYLON.Vector3(0, 0, 0);
  96240. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  96241. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  96242. this._options = options ? options : {};
  96243. var optionCount = 0;
  96244. if (this._options.dragAxis) {
  96245. optionCount++;
  96246. }
  96247. if (this._options.dragPlaneNormal) {
  96248. optionCount++;
  96249. }
  96250. if (optionCount > 1) {
  96251. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  96252. }
  96253. }
  96254. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  96255. /**
  96256. * The name of the behavior
  96257. */
  96258. get: function () {
  96259. return "PointerDrag";
  96260. },
  96261. enumerable: true,
  96262. configurable: true
  96263. });
  96264. /**
  96265. * Initializes the behavior
  96266. */
  96267. PointerDragBehavior.prototype.init = function () { };
  96268. /**
  96269. * Attaches the drag behavior the passed in mesh
  96270. * @param ownerNode The mesh that will be dragged around once attached
  96271. */
  96272. PointerDragBehavior.prototype.attach = function (ownerNode) {
  96273. var _this = this;
  96274. this._scene = ownerNode.getScene();
  96275. this._attachedNode = ownerNode;
  96276. // Initialize drag plane to not interfere with existing scene
  96277. if (!PointerDragBehavior._planeScene) {
  96278. if (this._debugMode) {
  96279. PointerDragBehavior._planeScene = this._scene;
  96280. }
  96281. else {
  96282. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  96283. PointerDragBehavior._planeScene.detachControl();
  96284. this._scene.getEngine().scenes.pop();
  96285. this._scene.onDisposeObservable.addOnce(function () {
  96286. PointerDragBehavior._planeScene.dispose();
  96287. PointerDragBehavior._planeScene = null;
  96288. });
  96289. }
  96290. }
  96291. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  96292. // State of the drag
  96293. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  96294. var pickPredicate = function (m) {
  96295. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  96296. };
  96297. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  96298. if (!_this.enabled) {
  96299. return;
  96300. }
  96301. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  96302. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  96303. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  96304. }
  96305. }
  96306. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  96307. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  96308. _this.releaseDrag();
  96309. }
  96310. }
  96311. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  96312. var pointerId = pointerInfo.event.pointerId;
  96313. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  96314. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  96315. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  96316. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  96317. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  96318. }
  96319. _this.currentDraggingPointerID = pointerId;
  96320. }
  96321. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  96322. if (!_this._lastPointerRay[pointerId]) {
  96323. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  96324. }
  96325. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  96326. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  96327. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  96328. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  96329. _this._moveDrag(pointerInfo.pickInfo.ray);
  96330. }
  96331. }
  96332. }
  96333. });
  96334. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  96335. if (_this._moving && _this.moveAttached) {
  96336. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  96337. // Slowly move mesh to avoid jitter
  96338. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  96339. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  96340. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  96341. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  96342. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  96343. }
  96344. });
  96345. };
  96346. /**
  96347. * Force relase the drag action by code.
  96348. */
  96349. PointerDragBehavior.prototype.releaseDrag = function () {
  96350. this.dragging = false;
  96351. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  96352. this.currentDraggingPointerID = -1;
  96353. this._moving = false;
  96354. // Reattach camera controls
  96355. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  96356. this._scene.activeCamera.attachControl(this._attachedElement, true);
  96357. }
  96358. };
  96359. /**
  96360. * Simulates the start of a pointer drag event on the behavior
  96361. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  96362. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  96363. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  96364. */
  96365. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  96366. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  96367. this._startDrag(pointerId, fromRay, startPickedPoint);
  96368. var lastRay = this._lastPointerRay[pointerId];
  96369. if (pointerId === PointerDragBehavior._AnyMouseID) {
  96370. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  96371. }
  96372. if (lastRay) {
  96373. // if there was a last pointer ray drag the object there
  96374. this._moveDrag(lastRay);
  96375. }
  96376. };
  96377. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  96378. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  96379. return;
  96380. }
  96381. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  96382. // Create start ray from the camera to the object
  96383. if (fromRay) {
  96384. this._startDragRay.direction.copyFrom(fromRay.direction);
  96385. this._startDragRay.origin.copyFrom(fromRay.origin);
  96386. }
  96387. else {
  96388. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  96389. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  96390. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  96391. }
  96392. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  96393. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  96394. if (pickedPoint) {
  96395. this.dragging = true;
  96396. this.currentDraggingPointerID = pointerId;
  96397. this.lastDragPosition.copyFrom(pickedPoint);
  96398. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  96399. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  96400. // Detatch camera controls
  96401. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  96402. if (this._scene.activeCamera.inputs.attachedElement) {
  96403. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  96404. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  96405. }
  96406. else {
  96407. this._attachedElement = null;
  96408. }
  96409. }
  96410. }
  96411. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  96412. };
  96413. PointerDragBehavior.prototype._moveDrag = function (ray) {
  96414. this._moving = true;
  96415. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  96416. if (pickedPoint) {
  96417. if (this.updateDragPlane) {
  96418. this._updateDragPlanePosition(ray, pickedPoint);
  96419. }
  96420. var dragLength = 0;
  96421. // depending on the drag mode option drag accordingly
  96422. if (this._options.dragAxis) {
  96423. // Convert local drag axis to world
  96424. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  96425. // Project delta drag from the drag plane onto the drag axis
  96426. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  96427. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  96428. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  96429. }
  96430. else {
  96431. dragLength = this._dragDelta.length();
  96432. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  96433. }
  96434. this._targetPosition.addInPlace(this._dragDelta);
  96435. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  96436. this.lastDragPosition.copyFrom(pickedPoint);
  96437. }
  96438. };
  96439. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  96440. var _this = this;
  96441. if (!ray) {
  96442. return null;
  96443. }
  96444. // Calculate angle between plane normal and ray
  96445. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  96446. // Correct if ray is casted from oposite side
  96447. if (angle > Math.PI / 2) {
  96448. angle = Math.PI - angle;
  96449. }
  96450. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  96451. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  96452. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  96453. // Invert ray direction along the towards object axis
  96454. this._tmpVector.copyFrom(ray.direction);
  96455. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  96456. this._alternatePickedPoint.normalize();
  96457. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  96458. this._tmpVector.addInPlace(this._alternatePickedPoint);
  96459. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  96460. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  96461. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  96462. this._alternatePickedPoint.addInPlace(this._tmpVector);
  96463. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  96464. return this._alternatePickedPoint;
  96465. }
  96466. else {
  96467. return null;
  96468. }
  96469. }
  96470. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  96471. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  96472. return pickResult.pickedPoint;
  96473. }
  96474. else {
  96475. return null;
  96476. }
  96477. };
  96478. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  96479. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  96480. this._pointA.copyFrom(dragPlanePosition);
  96481. if (this._options.dragAxis) {
  96482. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  96483. // Calculate plane normal in direction of camera but perpendicular to drag axis
  96484. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  96485. ray.origin.subtractToRef(this._pointA, this._pointC);
  96486. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  96487. // Get perpendicular line from direction to camera and drag axis
  96488. this._pointB.subtractToRef(this._pointA, this._lineA);
  96489. this._pointC.subtractToRef(this._pointA, this._lineB);
  96490. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  96491. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  96492. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  96493. this._lookAt.normalize();
  96494. this._dragPlane.position.copyFrom(this._pointA);
  96495. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  96496. this._dragPlane.lookAt(this._lookAt);
  96497. }
  96498. else if (this._options.dragPlaneNormal) {
  96499. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  96500. this._dragPlane.position.copyFrom(this._pointA);
  96501. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  96502. this._dragPlane.lookAt(this._lookAt);
  96503. }
  96504. else {
  96505. this._dragPlane.position.copyFrom(this._pointA);
  96506. this._dragPlane.lookAt(ray.origin);
  96507. }
  96508. this._dragPlane.computeWorldMatrix(true);
  96509. };
  96510. /**
  96511. * Detaches the behavior from the mesh
  96512. */
  96513. PointerDragBehavior.prototype.detach = function () {
  96514. if (this._pointerObserver) {
  96515. this._scene.onPointerObservable.remove(this._pointerObserver);
  96516. }
  96517. if (this._beforeRenderObserver) {
  96518. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  96519. }
  96520. };
  96521. PointerDragBehavior._AnyMouseID = -2;
  96522. return PointerDragBehavior;
  96523. }());
  96524. BABYLON.PointerDragBehavior = PointerDragBehavior;
  96525. })(BABYLON || (BABYLON = {}));
  96526. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  96527. var BABYLON;
  96528. (function (BABYLON) {
  96529. /**
  96530. * A behavior that when attached to a mesh will allow the mesh to be scaled
  96531. */
  96532. var MultiPointerScaleBehavior = /** @class */ (function () {
  96533. /**
  96534. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  96535. */
  96536. function MultiPointerScaleBehavior() {
  96537. this._startDistance = 0;
  96538. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  96539. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  96540. this._sceneRenderObserver = null;
  96541. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  96542. this._dragBehaviorA.moveAttached = false;
  96543. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  96544. this._dragBehaviorB.moveAttached = false;
  96545. }
  96546. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  96547. /**
  96548. * The name of the behavior
  96549. */
  96550. get: function () {
  96551. return "MultiPointerScale";
  96552. },
  96553. enumerable: true,
  96554. configurable: true
  96555. });
  96556. /**
  96557. * Initializes the behavior
  96558. */
  96559. MultiPointerScaleBehavior.prototype.init = function () { };
  96560. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  96561. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  96562. };
  96563. /**
  96564. * Attaches the scale behavior the passed in mesh
  96565. * @param ownerNode The mesh that will be scaled around once attached
  96566. */
  96567. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  96568. var _this = this;
  96569. this._ownerNode = ownerNode;
  96570. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  96571. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  96572. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96573. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  96574. _this._dragBehaviorA.releaseDrag();
  96575. }
  96576. else {
  96577. _this._initialScale.copyFrom(ownerNode.scaling);
  96578. _this._startDistance = _this._getCurrentDistance();
  96579. }
  96580. }
  96581. });
  96582. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  96583. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96584. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  96585. _this._dragBehaviorB.releaseDrag();
  96586. }
  96587. else {
  96588. _this._initialScale.copyFrom(ownerNode.scaling);
  96589. _this._startDistance = _this._getCurrentDistance();
  96590. }
  96591. }
  96592. });
  96593. // Once both drag behaviors are active scale based on the distance between the two pointers
  96594. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  96595. behavior.onDragObservable.add(function () {
  96596. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96597. var ratio = _this._getCurrentDistance() / _this._startDistance;
  96598. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  96599. }
  96600. });
  96601. });
  96602. ownerNode.addBehavior(this._dragBehaviorA);
  96603. ownerNode.addBehavior(this._dragBehaviorB);
  96604. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  96605. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  96606. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96607. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  96608. if (change.length() > 0.01) {
  96609. ownerNode.scaling.addInPlace(change);
  96610. }
  96611. }
  96612. });
  96613. };
  96614. /**
  96615. * Detaches the behavior from the mesh
  96616. */
  96617. MultiPointerScaleBehavior.prototype.detach = function () {
  96618. var _this = this;
  96619. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  96620. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  96621. behavior.onDragStartObservable.clear();
  96622. behavior.onDragObservable.clear();
  96623. _this._ownerNode.removeBehavior(behavior);
  96624. });
  96625. };
  96626. return MultiPointerScaleBehavior;
  96627. }());
  96628. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  96629. })(BABYLON || (BABYLON = {}));
  96630. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  96631. var BABYLON;
  96632. (function (BABYLON) {
  96633. /**
  96634. * 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
  96635. */
  96636. var SixDofDragBehavior = /** @class */ (function () {
  96637. /**
  96638. * 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
  96639. */
  96640. function SixDofDragBehavior() {
  96641. this._sceneRenderObserver = null;
  96642. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  96643. this._moving = false;
  96644. this._startingOrientation = new BABYLON.Quaternion();
  96645. /**
  96646. * 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)
  96647. */
  96648. this.zDragFactor = 3;
  96649. /**
  96650. * If the behavior is currently in a dragging state
  96651. */
  96652. this.dragging = false;
  96653. /**
  96654. * 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)
  96655. */
  96656. this.dragDeltaRatio = 0.2;
  96657. /**
  96658. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  96659. */
  96660. this.currentDraggingPointerID = -1;
  96661. /**
  96662. * If camera controls should be detached during the drag
  96663. */
  96664. this.detachCameraControls = true;
  96665. /**
  96666. * Fires each time a drag starts
  96667. */
  96668. this.onDragStartObservable = new BABYLON.Observable();
  96669. /**
  96670. * Fires each time a drag ends (eg. mouse release after drag)
  96671. */
  96672. this.onDragEndObservable = new BABYLON.Observable();
  96673. }
  96674. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  96675. /**
  96676. * The name of the behavior
  96677. */
  96678. get: function () {
  96679. return "SixDofDrag";
  96680. },
  96681. enumerable: true,
  96682. configurable: true
  96683. });
  96684. /**
  96685. * Initializes the behavior
  96686. */
  96687. SixDofDragBehavior.prototype.init = function () { };
  96688. /**
  96689. * Attaches the scale behavior the passed in mesh
  96690. * @param ownerNode The mesh that will be scaled around once attached
  96691. */
  96692. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  96693. var _this = this;
  96694. this._ownerNode = ownerNode;
  96695. this._scene = this._ownerNode.getScene();
  96696. if (!SixDofDragBehavior._virtualScene) {
  96697. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  96698. this._scene.getEngine().scenes.pop();
  96699. }
  96700. var pickedMesh = null;
  96701. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  96702. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  96703. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  96704. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  96705. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  96706. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  96707. var pickPredicate = function (m) {
  96708. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  96709. };
  96710. var attachedElement = null;
  96711. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  96712. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  96713. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  96714. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  96715. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  96716. }
  96717. pickedMesh = _this._ownerNode;
  96718. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  96719. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  96720. // Set position and orientation of the controller
  96721. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  96722. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  96723. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  96724. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  96725. pickedMesh.computeWorldMatrix();
  96726. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  96727. if (!pickedMesh.rotationQuaternion) {
  96728. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  96729. }
  96730. var oldParent = pickedMesh.parent;
  96731. pickedMesh.setParent(null);
  96732. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  96733. pickedMesh.setParent(oldParent);
  96734. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  96735. // Update state
  96736. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  96737. _this.dragging = true;
  96738. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  96739. // Detatch camera controls
  96740. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  96741. if (_this._scene.activeCamera.inputs.attachedElement) {
  96742. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  96743. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  96744. }
  96745. else {
  96746. attachedElement = null;
  96747. }
  96748. }
  96749. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  96750. _this.onDragStartObservable.notifyObservers({});
  96751. }
  96752. }
  96753. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  96754. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  96755. _this.dragging = false;
  96756. _this._moving = false;
  96757. _this.currentDraggingPointerID = -1;
  96758. pickedMesh = null;
  96759. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  96760. // Reattach camera controls
  96761. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  96762. _this._scene.activeCamera.attachControl(attachedElement, true);
  96763. }
  96764. _this.onDragEndObservable.notifyObservers({});
  96765. }
  96766. }
  96767. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  96768. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  96769. var zDragFactor = _this.zDragFactor;
  96770. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  96771. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  96772. zDragFactor = 0;
  96773. }
  96774. // Calculate controller drag distance in controller space
  96775. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  96776. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  96777. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  96778. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  96779. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  96780. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  96781. if (_this._virtualDragMesh.position.z < 0) {
  96782. _this._virtualDragMesh.position.z = 0;
  96783. }
  96784. // Update the controller position
  96785. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  96786. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  96787. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  96788. // Move the virtualObjectsPosition into the picked mesh's space if needed
  96789. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  96790. if (pickedMesh.parent) {
  96791. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  96792. }
  96793. if (!_this._moving) {
  96794. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  96795. }
  96796. _this._moving = true;
  96797. }
  96798. }
  96799. });
  96800. var tmpQuaternion = new BABYLON.Quaternion();
  96801. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  96802. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  96803. if (_this.dragging && _this._moving && pickedMesh) {
  96804. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  96805. // Slowly move mesh to avoid jitter
  96806. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  96807. // Get change in rotation
  96808. tmpQuaternion.copyFrom(_this._startingOrientation);
  96809. tmpQuaternion.x = -tmpQuaternion.x;
  96810. tmpQuaternion.y = -tmpQuaternion.y;
  96811. tmpQuaternion.z = -tmpQuaternion.z;
  96812. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  96813. // Convert change in rotation to only y axis rotation
  96814. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  96815. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  96816. // Slowly move mesh to avoid jitter
  96817. var oldParent = pickedMesh.parent;
  96818. pickedMesh.setParent(null);
  96819. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  96820. pickedMesh.setParent(oldParent);
  96821. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  96822. }
  96823. });
  96824. };
  96825. /**
  96826. * Detaches the behavior from the mesh
  96827. */
  96828. SixDofDragBehavior.prototype.detach = function () {
  96829. if (this._scene) {
  96830. this._scene.onPointerObservable.remove(this._pointerObserver);
  96831. }
  96832. if (this._ownerNode) {
  96833. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  96834. }
  96835. if (this._virtualOriginMesh) {
  96836. this._virtualOriginMesh.dispose();
  96837. }
  96838. if (this._virtualDragMesh) {
  96839. this._virtualDragMesh.dispose();
  96840. }
  96841. this.onDragEndObservable.clear();
  96842. this.onDragStartObservable.clear();
  96843. };
  96844. return SixDofDragBehavior;
  96845. }());
  96846. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  96847. })(BABYLON || (BABYLON = {}));
  96848. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  96849. var BABYLON;
  96850. (function (BABYLON) {
  96851. /**
  96852. * @hidden
  96853. */
  96854. var FaceDirectionInfo = /** @class */ (function () {
  96855. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  96856. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  96857. if (diff === void 0) { diff = 0; }
  96858. if (ignore === void 0) { ignore = false; }
  96859. this.direction = direction;
  96860. this.rotatedDirection = rotatedDirection;
  96861. this.diff = diff;
  96862. this.ignore = ignore;
  96863. }
  96864. return FaceDirectionInfo;
  96865. }());
  96866. /**
  96867. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  96868. */
  96869. var AttachToBoxBehavior = /** @class */ (function () {
  96870. /**
  96871. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  96872. * @param ui The transform node that should be attched to the mesh
  96873. */
  96874. function AttachToBoxBehavior(ui) {
  96875. this.ui = ui;
  96876. /**
  96877. * The name of the behavior
  96878. */
  96879. this.name = "AttachToBoxBehavior";
  96880. /**
  96881. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  96882. */
  96883. this.distanceAwayFromFace = 0.15;
  96884. /**
  96885. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  96886. */
  96887. this.distanceAwayFromBottomOfFace = 0.15;
  96888. 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))];
  96889. this._tmpMatrix = new BABYLON.Matrix();
  96890. this._tmpVector = new BABYLON.Vector3();
  96891. this._zeroVector = BABYLON.Vector3.Zero();
  96892. this._lookAtTmpMatrix = new BABYLON.Matrix();
  96893. /* Does nothing */
  96894. }
  96895. /**
  96896. * Initializes the behavior
  96897. */
  96898. AttachToBoxBehavior.prototype.init = function () {
  96899. /* Does nothing */
  96900. };
  96901. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  96902. var _this = this;
  96903. // Go over each face and calculate the angle between the face's normal and targetDirection
  96904. this._faceVectors.forEach(function (v) {
  96905. if (!_this._target.rotationQuaternion) {
  96906. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  96907. }
  96908. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  96909. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  96910. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  96911. });
  96912. // Return the face information of the one with the normal closeset to target direction
  96913. return this._faceVectors.reduce(function (min, p) {
  96914. if (min.ignore) {
  96915. return p;
  96916. }
  96917. else if (p.ignore) {
  96918. return min;
  96919. }
  96920. else {
  96921. return min.diff < p.diff ? min : p;
  96922. }
  96923. }, this._faceVectors[0]);
  96924. };
  96925. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  96926. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  96927. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  96928. this._lookAtTmpMatrix.invert();
  96929. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  96930. };
  96931. /**
  96932. * Attaches the AttachToBoxBehavior to the passed in mesh
  96933. * @param target The mesh that the specified node will be attached to
  96934. */
  96935. AttachToBoxBehavior.prototype.attach = function (target) {
  96936. var _this = this;
  96937. this._target = target;
  96938. this._scene = this._target.getScene();
  96939. // Every frame, update the app bars position
  96940. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  96941. if (!_this._scene.activeCamera) {
  96942. return;
  96943. }
  96944. // Find the face closest to the cameras position
  96945. var cameraPos = _this._scene.activeCamera.position;
  96946. if (_this._scene.activeCamera.devicePosition) {
  96947. cameraPos = _this._scene.activeCamera.devicePosition;
  96948. }
  96949. var facing = _this._closestFace(cameraPos.subtract(target.position));
  96950. if (_this._scene.activeCamera.leftCamera) {
  96951. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  96952. }
  96953. else {
  96954. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  96955. }
  96956. // Get camera up direction
  96957. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  96958. // Ignore faces to not select a parrelel face for the up vector of the UI
  96959. _this._faceVectors.forEach(function (v) {
  96960. if (facing.direction.x && v.direction.x) {
  96961. v.ignore = true;
  96962. }
  96963. if (facing.direction.y && v.direction.y) {
  96964. v.ignore = true;
  96965. }
  96966. if (facing.direction.z && v.direction.z) {
  96967. v.ignore = true;
  96968. }
  96969. });
  96970. var facingUp = _this._closestFace(_this._tmpVector);
  96971. // Unignore faces
  96972. _this._faceVectors.forEach(function (v) {
  96973. v.ignore = false;
  96974. });
  96975. // Position the app bar on that face
  96976. _this.ui.position.copyFrom(target.position);
  96977. if (facing.direction.x) {
  96978. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  96979. _this.ui.position.addInPlace(_this._tmpVector);
  96980. }
  96981. if (facing.direction.y) {
  96982. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  96983. _this.ui.position.addInPlace(_this._tmpVector);
  96984. }
  96985. if (facing.direction.z) {
  96986. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  96987. _this.ui.position.addInPlace(_this._tmpVector);
  96988. }
  96989. // Rotate to be oriented properly to the camera
  96990. if (!_this.ui.rotationQuaternion) {
  96991. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  96992. }
  96993. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  96994. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  96995. // Place ui the correct distance from the bottom of the mesh
  96996. if (facingUp.direction.x) {
  96997. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  96998. }
  96999. if (facingUp.direction.y) {
  97000. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  97001. }
  97002. if (facingUp.direction.z) {
  97003. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  97004. }
  97005. _this.ui.position.addInPlace(_this._tmpVector);
  97006. });
  97007. };
  97008. /**
  97009. * Detaches the behavior from the mesh
  97010. */
  97011. AttachToBoxBehavior.prototype.detach = function () {
  97012. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  97013. };
  97014. return AttachToBoxBehavior;
  97015. }());
  97016. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  97017. })(BABYLON || (BABYLON = {}));
  97018. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  97019. var BABYLON;
  97020. (function (BABYLON) {
  97021. /**
  97022. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  97023. */
  97024. var FadeInOutBehavior = /** @class */ (function () {
  97025. /**
  97026. * Instatiates the FadeInOutBehavior
  97027. */
  97028. function FadeInOutBehavior() {
  97029. var _this = this;
  97030. /**
  97031. * Time in milliseconds to delay before fading in (Default: 0)
  97032. */
  97033. this.delay = 0;
  97034. /**
  97035. * Time in milliseconds for the mesh to fade in (Default: 300)
  97036. */
  97037. this.fadeInTime = 300;
  97038. this._millisecondsPerFrame = 1000 / 60;
  97039. this._hovered = false;
  97040. this._hoverValue = 0;
  97041. this._ownerNode = null;
  97042. this._update = function () {
  97043. if (_this._ownerNode) {
  97044. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  97045. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  97046. if (_this._ownerNode.visibility > 1) {
  97047. _this._setAllVisibility(_this._ownerNode, 1);
  97048. _this._hoverValue = _this.fadeInTime + _this.delay;
  97049. return;
  97050. }
  97051. else if (_this._ownerNode.visibility < 0) {
  97052. _this._setAllVisibility(_this._ownerNode, 0);
  97053. if (_this._hoverValue < 0) {
  97054. _this._hoverValue = 0;
  97055. return;
  97056. }
  97057. }
  97058. setTimeout(_this._update, _this._millisecondsPerFrame);
  97059. }
  97060. };
  97061. }
  97062. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  97063. /**
  97064. * The name of the behavior
  97065. */
  97066. get: function () {
  97067. return "FadeInOut";
  97068. },
  97069. enumerable: true,
  97070. configurable: true
  97071. });
  97072. /**
  97073. * Initializes the behavior
  97074. */
  97075. FadeInOutBehavior.prototype.init = function () {
  97076. };
  97077. /**
  97078. * Attaches the fade behavior on the passed in mesh
  97079. * @param ownerNode The mesh that will be faded in/out once attached
  97080. */
  97081. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  97082. this._ownerNode = ownerNode;
  97083. this._setAllVisibility(this._ownerNode, 0);
  97084. };
  97085. /**
  97086. * Detaches the behavior from the mesh
  97087. */
  97088. FadeInOutBehavior.prototype.detach = function () {
  97089. this._ownerNode = null;
  97090. };
  97091. /**
  97092. * Triggers the mesh to begin fading in or out
  97093. * @param value if the object should fade in or out (true to fade in)
  97094. */
  97095. FadeInOutBehavior.prototype.fadeIn = function (value) {
  97096. this._hovered = value;
  97097. this._update();
  97098. };
  97099. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  97100. var _this = this;
  97101. mesh.visibility = value;
  97102. mesh.getChildMeshes().forEach(function (c) {
  97103. _this._setAllVisibility(c, value);
  97104. });
  97105. };
  97106. return FadeInOutBehavior;
  97107. }());
  97108. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  97109. })(BABYLON || (BABYLON = {}));
  97110. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  97111. var BABYLON;
  97112. (function (BABYLON) {
  97113. /**
  97114. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  97115. */
  97116. var Gizmo = /** @class */ (function () {
  97117. /**
  97118. * Creates a gizmo
  97119. * @param gizmoLayer The utility layer the gizmo will be added to
  97120. */
  97121. function Gizmo(
  97122. /** The utility layer the gizmo will be added to */
  97123. gizmoLayer) {
  97124. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97125. var _this = this;
  97126. this.gizmoLayer = gizmoLayer;
  97127. /**
  97128. * Ratio for the scale of the gizmo (Default: 1)
  97129. */
  97130. this.scaleRatio = 1;
  97131. this._tmpMatrix = new BABYLON.Matrix();
  97132. /**
  97133. * If a custom mesh has been set (Default: false)
  97134. */
  97135. this._customMeshSet = false;
  97136. /**
  97137. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  97138. */
  97139. this.updateGizmoRotationToMatchAttachedMesh = true;
  97140. /**
  97141. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  97142. */
  97143. this.updateGizmoPositionToMatchAttachedMesh = true;
  97144. /**
  97145. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  97146. */
  97147. this._updateScale = true;
  97148. this._interactionsEnabled = true;
  97149. this._tempVector = new BABYLON.Vector3();
  97150. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  97151. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  97152. _this._update();
  97153. });
  97154. this.attachedMesh = null;
  97155. }
  97156. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  97157. /**
  97158. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  97159. * * When set, interactions will be enabled
  97160. */
  97161. get: function () {
  97162. return this._attachedMesh;
  97163. },
  97164. set: function (value) {
  97165. this._attachedMesh = value;
  97166. this._rootMesh.setEnabled(value ? true : false);
  97167. this._attachedMeshChanged(value);
  97168. },
  97169. enumerable: true,
  97170. configurable: true
  97171. });
  97172. /**
  97173. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  97174. * @param mesh The mesh to replace the default mesh of the gizmo
  97175. */
  97176. Gizmo.prototype.setCustomMesh = function (mesh) {
  97177. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  97178. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  97179. }
  97180. this._rootMesh.getChildMeshes().forEach(function (c) {
  97181. c.dispose();
  97182. });
  97183. mesh.parent = this._rootMesh;
  97184. this._customMeshSet = true;
  97185. };
  97186. Gizmo.prototype._attachedMeshChanged = function (value) {
  97187. };
  97188. /**
  97189. * @hidden
  97190. * Updates the gizmo to match the attached mesh's position/rotation
  97191. */
  97192. Gizmo.prototype._update = function () {
  97193. if (this.attachedMesh) {
  97194. if (this.updateGizmoRotationToMatchAttachedMesh) {
  97195. if (!this._rootMesh.rotationQuaternion) {
  97196. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  97197. }
  97198. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  97199. this._tempVector.copyFrom(this.attachedMesh.scaling);
  97200. if (this.attachedMesh.scaling.x < 0) {
  97201. this.attachedMesh.scaling.x *= -1;
  97202. }
  97203. if (this.attachedMesh.scaling.y < 0) {
  97204. this.attachedMesh.scaling.y *= -1;
  97205. }
  97206. if (this.attachedMesh.scaling.z < 0) {
  97207. this.attachedMesh.scaling.z *= -1;
  97208. }
  97209. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  97210. this.attachedMesh.scaling.copyFrom(this._tempVector);
  97211. this.attachedMesh.computeWorldMatrix();
  97212. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  97213. }
  97214. else if (this._rootMesh.rotationQuaternion) {
  97215. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  97216. }
  97217. if (this.updateGizmoPositionToMatchAttachedMesh) {
  97218. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  97219. }
  97220. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  97221. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  97222. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  97223. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  97224. }
  97225. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  97226. var dist = this._tempVector.length() * this.scaleRatio;
  97227. this._rootMesh.scaling.set(dist, dist, dist);
  97228. }
  97229. }
  97230. };
  97231. /**
  97232. * Disposes of the gizmo
  97233. */
  97234. Gizmo.prototype.dispose = function () {
  97235. this._rootMesh.dispose();
  97236. if (this._beforeRenderObserver) {
  97237. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  97238. }
  97239. };
  97240. return Gizmo;
  97241. }());
  97242. BABYLON.Gizmo = Gizmo;
  97243. })(BABYLON || (BABYLON = {}));
  97244. //# sourceMappingURL=babylon.gizmo.js.map
  97245. var BABYLON;
  97246. (function (BABYLON) {
  97247. /**
  97248. * Single axis drag gizmo
  97249. */
  97250. var AxisDragGizmo = /** @class */ (function (_super) {
  97251. __extends(AxisDragGizmo, _super);
  97252. /**
  97253. * Creates an AxisDragGizmo
  97254. * @param gizmoLayer The utility layer the gizmo will be added to
  97255. * @param dragAxis The axis which the gizmo will be able to drag on
  97256. * @param color The color of the gizmo
  97257. */
  97258. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  97259. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  97260. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97261. var _this = _super.call(this, gizmoLayer) || this;
  97262. _this._pointerObserver = null;
  97263. /**
  97264. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  97265. */
  97266. _this.snapDistance = 0;
  97267. /**
  97268. * Event that fires each time the gizmo snaps to a new location.
  97269. * * snapDistance is the the change in distance
  97270. */
  97271. _this.onSnapObservable = new BABYLON.Observable();
  97272. // Create Material
  97273. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97274. coloredMaterial.disableLighting = true;
  97275. coloredMaterial.emissiveColor = color;
  97276. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97277. hoverMaterial.disableLighting = true;
  97278. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  97279. // Build mesh on root node
  97280. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  97281. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  97282. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  97283. arrowTail.color = coloredMaterial.emissiveColor;
  97284. arrow.addChild(arrowMesh);
  97285. arrow.addChild(arrowTail);
  97286. // Position arrow pointing in its drag axis
  97287. arrowMesh.scaling.scaleInPlace(0.05);
  97288. arrowMesh.material = coloredMaterial;
  97289. arrowMesh.rotation.x = Math.PI / 2;
  97290. arrowMesh.position.z += 0.3;
  97291. arrowTail.scaling.scaleInPlace(0.26);
  97292. arrowTail.rotation.x = Math.PI / 2;
  97293. arrowTail.material = coloredMaterial;
  97294. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  97295. arrow.scaling.scaleInPlace(1 / 3);
  97296. _this._rootMesh.addChild(arrow);
  97297. var currentSnapDragDistance = 0;
  97298. var tmpVector = new BABYLON.Vector3();
  97299. var tmpSnapEvent = { snapDistance: 0 };
  97300. // Add drag behavior to handle events when the gizmo is dragged
  97301. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  97302. _this.dragBehavior.moveAttached = false;
  97303. _this._rootMesh.addBehavior(_this.dragBehavior);
  97304. var localDelta = new BABYLON.Vector3();
  97305. var tmpMatrix = new BABYLON.Matrix();
  97306. _this.dragBehavior.onDragObservable.add(function (event) {
  97307. if (_this.attachedMesh) {
  97308. // Convert delta to local translation if it has a parent
  97309. if (_this.attachedMesh.parent) {
  97310. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  97311. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  97312. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  97313. }
  97314. else {
  97315. localDelta.copyFrom(event.delta);
  97316. }
  97317. // Snapping logic
  97318. if (_this.snapDistance == 0) {
  97319. _this.attachedMesh.position.addInPlace(localDelta);
  97320. }
  97321. else {
  97322. currentSnapDragDistance += event.dragDistance;
  97323. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  97324. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  97325. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  97326. localDelta.normalizeToRef(tmpVector);
  97327. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  97328. _this.attachedMesh.position.addInPlace(tmpVector);
  97329. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  97330. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  97331. }
  97332. }
  97333. }
  97334. });
  97335. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  97336. if (_this._customMeshSet) {
  97337. return;
  97338. }
  97339. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  97340. var material = isHovered ? hoverMaterial : coloredMaterial;
  97341. _this._rootMesh.getChildMeshes().forEach(function (m) {
  97342. m.material = material;
  97343. if (m.color) {
  97344. m.color = material.emissiveColor;
  97345. }
  97346. });
  97347. });
  97348. return _this;
  97349. }
  97350. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  97351. if (this.dragBehavior) {
  97352. this.dragBehavior.enabled = value ? true : false;
  97353. }
  97354. };
  97355. /**
  97356. * Disposes of the gizmo
  97357. */
  97358. AxisDragGizmo.prototype.dispose = function () {
  97359. this.onSnapObservable.clear();
  97360. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  97361. this.dragBehavior.detach();
  97362. _super.prototype.dispose.call(this);
  97363. };
  97364. return AxisDragGizmo;
  97365. }(BABYLON.Gizmo));
  97366. BABYLON.AxisDragGizmo = AxisDragGizmo;
  97367. })(BABYLON || (BABYLON = {}));
  97368. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  97369. var BABYLON;
  97370. (function (BABYLON) {
  97371. /**
  97372. * Single axis scale gizmo
  97373. */
  97374. var AxisScaleGizmo = /** @class */ (function (_super) {
  97375. __extends(AxisScaleGizmo, _super);
  97376. /**
  97377. * Creates an AxisScaleGizmo
  97378. * @param gizmoLayer The utility layer the gizmo will be added to
  97379. * @param dragAxis The axis which the gizmo will be able to scale on
  97380. * @param color The color of the gizmo
  97381. */
  97382. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  97383. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  97384. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97385. var _this = _super.call(this, gizmoLayer) || this;
  97386. _this._pointerObserver = null;
  97387. /**
  97388. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  97389. */
  97390. _this.snapDistance = 0;
  97391. /**
  97392. * Event that fires each time the gizmo snaps to a new location.
  97393. * * snapDistance is the the change in distance
  97394. */
  97395. _this.onSnapObservable = new BABYLON.Observable();
  97396. /**
  97397. * If the scaling operation should be done on all axis (default: false)
  97398. */
  97399. _this.uniformScaling = false;
  97400. // Create Material
  97401. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97402. _this._coloredMaterial.disableLighting = true;
  97403. _this._coloredMaterial.emissiveColor = color;
  97404. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97405. hoverMaterial.disableLighting = true;
  97406. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  97407. // Build mesh on root node
  97408. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  97409. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  97410. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  97411. arrowTail.color = _this._coloredMaterial.emissiveColor;
  97412. arrow.addChild(arrowMesh);
  97413. arrow.addChild(arrowTail);
  97414. // Position arrow pointing in its drag axis
  97415. arrowMesh.scaling.scaleInPlace(0.1);
  97416. arrowMesh.material = _this._coloredMaterial;
  97417. arrowMesh.rotation.x = Math.PI / 2;
  97418. arrowMesh.position.z += 0.3;
  97419. arrowTail.scaling.scaleInPlace(0.26);
  97420. arrowTail.rotation.x = Math.PI / 2;
  97421. arrowTail.material = _this._coloredMaterial;
  97422. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  97423. _this._rootMesh.addChild(arrow);
  97424. arrow.scaling.scaleInPlace(1 / 3);
  97425. // Add drag behavior to handle events when the gizmo is dragged
  97426. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  97427. _this.dragBehavior.moveAttached = false;
  97428. _this._rootMesh.addBehavior(_this.dragBehavior);
  97429. var currentSnapDragDistance = 0;
  97430. var tmpVector = new BABYLON.Vector3();
  97431. var tmpSnapEvent = { snapDistance: 0 };
  97432. _this.dragBehavior.onDragObservable.add(function (event) {
  97433. if (_this.attachedMesh) {
  97434. // Snapping logic
  97435. var snapped = false;
  97436. var dragSteps = 0;
  97437. if (_this.uniformScaling) {
  97438. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  97439. if (tmpVector.y < 0) {
  97440. tmpVector.scaleInPlace(-1);
  97441. }
  97442. }
  97443. else {
  97444. tmpVector.copyFrom(dragAxis);
  97445. }
  97446. if (_this.snapDistance == 0) {
  97447. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  97448. }
  97449. else {
  97450. currentSnapDragDistance += event.dragDistance;
  97451. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  97452. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  97453. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  97454. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  97455. snapped = true;
  97456. }
  97457. else {
  97458. tmpVector.scaleInPlace(0);
  97459. }
  97460. }
  97461. _this.attachedMesh.scaling.addInPlace(tmpVector);
  97462. if (snapped) {
  97463. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  97464. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  97465. }
  97466. }
  97467. });
  97468. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  97469. if (_this._customMeshSet) {
  97470. return;
  97471. }
  97472. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  97473. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  97474. _this._rootMesh.getChildMeshes().forEach(function (m) {
  97475. m.material = material;
  97476. if (m.color) {
  97477. m.color = material.emissiveColor;
  97478. }
  97479. });
  97480. });
  97481. return _this;
  97482. }
  97483. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  97484. if (this.dragBehavior) {
  97485. this.dragBehavior.enabled = value ? true : false;
  97486. }
  97487. };
  97488. /**
  97489. * Disposes of the gizmo
  97490. */
  97491. AxisScaleGizmo.prototype.dispose = function () {
  97492. this.onSnapObservable.clear();
  97493. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  97494. this.dragBehavior.detach();
  97495. _super.prototype.dispose.call(this);
  97496. };
  97497. /**
  97498. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  97499. * @param mesh The mesh to replace the default mesh of the gizmo
  97500. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  97501. */
  97502. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  97503. var _this = this;
  97504. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  97505. _super.prototype.setCustomMesh.call(this, mesh);
  97506. if (useGizmoMaterial) {
  97507. this._rootMesh.getChildMeshes().forEach(function (m) {
  97508. m.material = _this._coloredMaterial;
  97509. if (m.color) {
  97510. m.color = _this._coloredMaterial.emissiveColor;
  97511. }
  97512. });
  97513. this._customMeshSet = false;
  97514. }
  97515. };
  97516. return AxisScaleGizmo;
  97517. }(BABYLON.Gizmo));
  97518. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  97519. })(BABYLON || (BABYLON = {}));
  97520. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  97521. var BABYLON;
  97522. (function (BABYLON) {
  97523. /**
  97524. * Single plane rotation gizmo
  97525. */
  97526. var PlaneRotationGizmo = /** @class */ (function (_super) {
  97527. __extends(PlaneRotationGizmo, _super);
  97528. /**
  97529. * Creates a PlaneRotationGizmo
  97530. * @param gizmoLayer The utility layer the gizmo will be added to
  97531. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  97532. * @param color The color of the gizmo
  97533. */
  97534. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  97535. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  97536. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97537. var _this = _super.call(this, gizmoLayer) || this;
  97538. _this._pointerObserver = null;
  97539. /**
  97540. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  97541. */
  97542. _this.snapDistance = 0;
  97543. /**
  97544. * Event that fires each time the gizmo snaps to a new location.
  97545. * * snapDistance is the the change in distance
  97546. */
  97547. _this.onSnapObservable = new BABYLON.Observable();
  97548. // Create Material
  97549. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97550. coloredMaterial.disableLighting = true;
  97551. coloredMaterial.emissiveColor = color;
  97552. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97553. hoverMaterial.disableLighting = true;
  97554. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  97555. // Build mesh on root node
  97556. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  97557. // Create circle out of lines
  97558. var tessellation = 20;
  97559. var radius = 0.8;
  97560. var points = new Array();
  97561. for (var i = 0; i < tessellation; i++) {
  97562. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  97563. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  97564. }
  97565. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  97566. rotationMesh.color = coloredMaterial.emissiveColor;
  97567. // Position arrow pointing in its drag axis
  97568. rotationMesh.scaling.scaleInPlace(0.26);
  97569. rotationMesh.material = coloredMaterial;
  97570. rotationMesh.rotation.x = Math.PI / 2;
  97571. parentMesh.addChild(rotationMesh);
  97572. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  97573. _this._rootMesh.addChild(parentMesh);
  97574. parentMesh.scaling.scaleInPlace(1 / 3);
  97575. // Add drag behavior to handle events when the gizmo is dragged
  97576. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  97577. _this.dragBehavior.moveAttached = false;
  97578. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  97579. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  97580. _this._rootMesh.addBehavior(_this.dragBehavior);
  97581. var lastDragPosition = new BABYLON.Vector3();
  97582. _this.dragBehavior.onDragStartObservable.add(function (e) {
  97583. if (_this.attachedMesh) {
  97584. lastDragPosition.copyFrom(e.dragPlanePoint);
  97585. }
  97586. });
  97587. var rotationMatrix = new BABYLON.Matrix();
  97588. var planeNormalTowardsCamera = new BABYLON.Vector3();
  97589. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  97590. var tmpSnapEvent = { snapDistance: 0 };
  97591. var currentSnapDragDistance = 0;
  97592. var tmpMatrix = new BABYLON.Matrix();
  97593. var tmpVector = new BABYLON.Vector3();
  97594. var amountToRotate = new BABYLON.Quaternion();
  97595. _this.dragBehavior.onDragObservable.add(function (event) {
  97596. if (_this.attachedMesh) {
  97597. if (!_this.attachedMesh.rotationQuaternion) {
  97598. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  97599. }
  97600. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  97601. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  97602. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  97603. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  97604. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  97605. var angle = Math.atan2(cross.length(), dot);
  97606. planeNormalTowardsCamera.copyFrom(planeNormal);
  97607. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  97608. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  97609. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  97610. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  97611. }
  97612. // Flip up vector depending on which side the camera is on
  97613. if (gizmoLayer.utilityLayerScene.activeCamera) {
  97614. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  97615. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  97616. planeNormalTowardsCamera.scaleInPlace(-1);
  97617. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  97618. }
  97619. }
  97620. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  97621. if (halfCircleSide)
  97622. angle = -angle;
  97623. // Snapping logic
  97624. var snapped = false;
  97625. if (_this.snapDistance != 0) {
  97626. currentSnapDragDistance += angle;
  97627. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  97628. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  97629. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  97630. angle = _this.snapDistance * dragSteps;
  97631. snapped = true;
  97632. }
  97633. else {
  97634. angle = 0;
  97635. }
  97636. }
  97637. // If the mesh has a parent, convert needed world rotation to local rotation
  97638. tmpMatrix.reset();
  97639. if (_this.attachedMesh.parent) {
  97640. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  97641. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  97642. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  97643. }
  97644. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  97645. var quaternionCoefficient = Math.sin(angle / 2);
  97646. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  97647. // 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
  97648. if (tmpMatrix.determinant() > 0) {
  97649. amountToRotate.toEulerAnglesToRef(tmpVector);
  97650. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  97651. }
  97652. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  97653. // Rotate selected mesh quaternion over fixed axis
  97654. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  97655. }
  97656. else {
  97657. // Rotate selected mesh quaternion over rotated axis
  97658. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  97659. }
  97660. lastDragPosition.copyFrom(event.dragPlanePoint);
  97661. if (snapped) {
  97662. tmpSnapEvent.snapDistance = angle;
  97663. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  97664. }
  97665. }
  97666. });
  97667. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  97668. if (_this._customMeshSet) {
  97669. return;
  97670. }
  97671. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  97672. var material = isHovered ? hoverMaterial : coloredMaterial;
  97673. _this._rootMesh.getChildMeshes().forEach(function (m) {
  97674. m.material = material;
  97675. if (m.color) {
  97676. m.color = material.emissiveColor;
  97677. }
  97678. });
  97679. });
  97680. return _this;
  97681. }
  97682. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  97683. if (this.dragBehavior) {
  97684. this.dragBehavior.enabled = value ? true : false;
  97685. }
  97686. };
  97687. /**
  97688. * Disposes of the gizmo
  97689. */
  97690. PlaneRotationGizmo.prototype.dispose = function () {
  97691. this.onSnapObservable.clear();
  97692. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  97693. this.dragBehavior.detach();
  97694. _super.prototype.dispose.call(this);
  97695. };
  97696. return PlaneRotationGizmo;
  97697. }(BABYLON.Gizmo));
  97698. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  97699. })(BABYLON || (BABYLON = {}));
  97700. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  97701. var BABYLON;
  97702. (function (BABYLON) {
  97703. /**
  97704. * Gizmo that enables dragging a mesh along 3 axis
  97705. */
  97706. var PositionGizmo = /** @class */ (function (_super) {
  97707. __extends(PositionGizmo, _super);
  97708. /**
  97709. * Creates a PositionGizmo
  97710. * @param gizmoLayer The utility layer the gizmo will be added to
  97711. */
  97712. function PositionGizmo(gizmoLayer) {
  97713. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97714. var _this = _super.call(this, gizmoLayer) || this;
  97715. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  97716. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  97717. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  97718. _this.attachedMesh = null;
  97719. return _this;
  97720. }
  97721. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  97722. set: function (mesh) {
  97723. if (this.xGizmo) {
  97724. this.xGizmo.attachedMesh = mesh;
  97725. this.yGizmo.attachedMesh = mesh;
  97726. this.zGizmo.attachedMesh = mesh;
  97727. }
  97728. },
  97729. enumerable: true,
  97730. configurable: true
  97731. });
  97732. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  97733. get: function () {
  97734. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  97735. },
  97736. set: function (value) {
  97737. if (this.xGizmo) {
  97738. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97739. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97740. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97741. }
  97742. },
  97743. enumerable: true,
  97744. configurable: true
  97745. });
  97746. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  97747. get: function () {
  97748. return this.xGizmo.snapDistance;
  97749. },
  97750. /**
  97751. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  97752. */
  97753. set: function (value) {
  97754. if (this.xGizmo) {
  97755. this.xGizmo.snapDistance = value;
  97756. this.yGizmo.snapDistance = value;
  97757. this.zGizmo.snapDistance = value;
  97758. }
  97759. },
  97760. enumerable: true,
  97761. configurable: true
  97762. });
  97763. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  97764. get: function () {
  97765. return this.xGizmo.scaleRatio;
  97766. },
  97767. /**
  97768. * Ratio for the scale of the gizmo (Default: 1)
  97769. */
  97770. set: function (value) {
  97771. if (this.xGizmo) {
  97772. this.xGizmo.scaleRatio = value;
  97773. this.yGizmo.scaleRatio = value;
  97774. this.zGizmo.scaleRatio = value;
  97775. }
  97776. },
  97777. enumerable: true,
  97778. configurable: true
  97779. });
  97780. /**
  97781. * Disposes of the gizmo
  97782. */
  97783. PositionGizmo.prototype.dispose = function () {
  97784. this.xGizmo.dispose();
  97785. this.yGizmo.dispose();
  97786. this.zGizmo.dispose();
  97787. };
  97788. /**
  97789. * CustomMeshes are not supported by this gizmo
  97790. * @param mesh The mesh to replace the default mesh of the gizmo
  97791. */
  97792. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  97793. 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)");
  97794. };
  97795. return PositionGizmo;
  97796. }(BABYLON.Gizmo));
  97797. BABYLON.PositionGizmo = PositionGizmo;
  97798. })(BABYLON || (BABYLON = {}));
  97799. //# sourceMappingURL=babylon.positionGizmo.js.map
  97800. var BABYLON;
  97801. (function (BABYLON) {
  97802. /**
  97803. * Gizmo that enables rotating a mesh along 3 axis
  97804. */
  97805. var RotationGizmo = /** @class */ (function (_super) {
  97806. __extends(RotationGizmo, _super);
  97807. /**
  97808. * Creates a RotationGizmo
  97809. * @param gizmoLayer The utility layer the gizmo will be added to
  97810. */
  97811. function RotationGizmo(gizmoLayer) {
  97812. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97813. var _this = _super.call(this, gizmoLayer) || this;
  97814. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  97815. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  97816. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  97817. _this.attachedMesh = null;
  97818. return _this;
  97819. }
  97820. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  97821. set: function (mesh) {
  97822. if (this.xGizmo) {
  97823. this.xGizmo.attachedMesh = mesh;
  97824. this.yGizmo.attachedMesh = mesh;
  97825. this.zGizmo.attachedMesh = mesh;
  97826. }
  97827. },
  97828. enumerable: true,
  97829. configurable: true
  97830. });
  97831. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  97832. get: function () {
  97833. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  97834. },
  97835. set: function (value) {
  97836. if (this.xGizmo) {
  97837. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97838. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97839. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97840. }
  97841. },
  97842. enumerable: true,
  97843. configurable: true
  97844. });
  97845. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  97846. get: function () {
  97847. return this.xGizmo.snapDistance;
  97848. },
  97849. /**
  97850. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  97851. */
  97852. set: function (value) {
  97853. if (this.xGizmo) {
  97854. this.xGizmo.snapDistance = value;
  97855. this.yGizmo.snapDistance = value;
  97856. this.zGizmo.snapDistance = value;
  97857. }
  97858. },
  97859. enumerable: true,
  97860. configurable: true
  97861. });
  97862. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  97863. get: function () {
  97864. return this.xGizmo.scaleRatio;
  97865. },
  97866. /**
  97867. * Ratio for the scale of the gizmo (Default: 1)
  97868. */
  97869. set: function (value) {
  97870. if (this.xGizmo) {
  97871. this.xGizmo.scaleRatio = value;
  97872. this.yGizmo.scaleRatio = value;
  97873. this.zGizmo.scaleRatio = value;
  97874. }
  97875. },
  97876. enumerable: true,
  97877. configurable: true
  97878. });
  97879. /**
  97880. * Disposes of the gizmo
  97881. */
  97882. RotationGizmo.prototype.dispose = function () {
  97883. this.xGizmo.dispose();
  97884. this.yGizmo.dispose();
  97885. this.zGizmo.dispose();
  97886. };
  97887. /**
  97888. * CustomMeshes are not supported by this gizmo
  97889. * @param mesh The mesh to replace the default mesh of the gizmo
  97890. */
  97891. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  97892. 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)");
  97893. };
  97894. return RotationGizmo;
  97895. }(BABYLON.Gizmo));
  97896. BABYLON.RotationGizmo = RotationGizmo;
  97897. })(BABYLON || (BABYLON = {}));
  97898. //# sourceMappingURL=babylon.rotationGizmo.js.map
  97899. var BABYLON;
  97900. (function (BABYLON) {
  97901. /**
  97902. * Gizmo that enables scaling a mesh along 3 axis
  97903. */
  97904. var ScaleGizmo = /** @class */ (function (_super) {
  97905. __extends(ScaleGizmo, _super);
  97906. /**
  97907. * Creates a ScaleGizmo
  97908. * @param gizmoLayer The utility layer the gizmo will be added to
  97909. */
  97910. function ScaleGizmo(gizmoLayer) {
  97911. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97912. var _this = _super.call(this, gizmoLayer) || this;
  97913. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  97914. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  97915. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  97916. // Create uniform scale gizmo
  97917. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  97918. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  97919. _this.uniformScaleGizmo.uniformScaling = true;
  97920. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  97921. octahedron.scaling.scaleInPlace(0.007);
  97922. _this.uniformScaleGizmo.setCustomMesh(octahedron, true);
  97923. _this.attachedMesh = null;
  97924. return _this;
  97925. }
  97926. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  97927. set: function (mesh) {
  97928. if (this.xGizmo) {
  97929. this.xGizmo.attachedMesh = mesh;
  97930. this.yGizmo.attachedMesh = mesh;
  97931. this.zGizmo.attachedMesh = mesh;
  97932. this.uniformScaleGizmo.attachedMesh = mesh;
  97933. }
  97934. },
  97935. enumerable: true,
  97936. configurable: true
  97937. });
  97938. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  97939. get: function () {
  97940. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  97941. },
  97942. set: function (value) {
  97943. if (this.xGizmo) {
  97944. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97945. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97946. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97947. }
  97948. },
  97949. enumerable: true,
  97950. configurable: true
  97951. });
  97952. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  97953. get: function () {
  97954. return this.xGizmo.snapDistance;
  97955. },
  97956. /**
  97957. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  97958. */
  97959. set: function (value) {
  97960. if (this.xGizmo) {
  97961. this.xGizmo.snapDistance = value;
  97962. this.yGizmo.snapDistance = value;
  97963. this.zGizmo.snapDistance = value;
  97964. this.uniformScaleGizmo.snapDistance = value;
  97965. }
  97966. },
  97967. enumerable: true,
  97968. configurable: true
  97969. });
  97970. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  97971. get: function () {
  97972. return this.xGizmo.scaleRatio;
  97973. },
  97974. /**
  97975. * Ratio for the scale of the gizmo (Default: 1)
  97976. */
  97977. set: function (value) {
  97978. if (this.xGizmo) {
  97979. this.xGizmo.scaleRatio = value;
  97980. this.yGizmo.scaleRatio = value;
  97981. this.zGizmo.scaleRatio = value;
  97982. this.uniformScaleGizmo.scaleRatio = value;
  97983. }
  97984. },
  97985. enumerable: true,
  97986. configurable: true
  97987. });
  97988. /**
  97989. * Disposes of the gizmo
  97990. */
  97991. ScaleGizmo.prototype.dispose = function () {
  97992. this.xGizmo.dispose();
  97993. this.yGizmo.dispose();
  97994. this.zGizmo.dispose();
  97995. this.uniformScaleGizmo.dispose();
  97996. };
  97997. return ScaleGizmo;
  97998. }(BABYLON.Gizmo));
  97999. BABYLON.ScaleGizmo = ScaleGizmo;
  98000. })(BABYLON || (BABYLON = {}));
  98001. //# sourceMappingURL=babylon.scaleGizmo.js.map
  98002. var BABYLON;
  98003. (function (BABYLON) {
  98004. /**
  98005. * Bounding box gizmo
  98006. */
  98007. var BoundingBoxGizmo = /** @class */ (function (_super) {
  98008. __extends(BoundingBoxGizmo, _super);
  98009. /**
  98010. * Creates an BoundingBoxGizmo
  98011. * @param gizmoLayer The utility layer the gizmo will be added to
  98012. * @param color The color of the gizmo
  98013. */
  98014. function BoundingBoxGizmo(color, gizmoLayer) {
  98015. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  98016. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  98017. var _this = _super.call(this, gizmoLayer) || this;
  98018. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  98019. _this._renderObserver = null;
  98020. _this._pointerObserver = null;
  98021. _this._scaleDragSpeed = 0.2;
  98022. _this._tmpQuaternion = new BABYLON.Quaternion();
  98023. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  98024. _this._tmpRotationMatrix = new BABYLON.Matrix();
  98025. /**
  98026. * 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)
  98027. */
  98028. _this.ignoreChildren = false;
  98029. /**
  98030. * 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)
  98031. */
  98032. _this.includeChildPredicate = null;
  98033. /**
  98034. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  98035. */
  98036. _this.rotationSphereSize = 0.1;
  98037. /**
  98038. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  98039. */
  98040. _this.scaleBoxSize = 0.1;
  98041. /**
  98042. * 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)
  98043. */
  98044. _this.fixedDragMeshScreenSize = false;
  98045. /**
  98046. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  98047. */
  98048. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  98049. /**
  98050. * Fired when a rotation sphere or scale box is dragged
  98051. */
  98052. _this.onDragStartObservable = new BABYLON.Observable();
  98053. /**
  98054. * Fired when a scale box is dragged
  98055. */
  98056. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  98057. /**
  98058. * Fired when a scale box drag is ended
  98059. */
  98060. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  98061. /**
  98062. * Fired when a rotation sphere is dragged
  98063. */
  98064. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  98065. /**
  98066. * Fired when a rotation sphere drag is ended
  98067. */
  98068. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  98069. /**
  98070. * 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)
  98071. */
  98072. _this.scalePivot = null;
  98073. _this._existingMeshScale = new BABYLON.Vector3();
  98074. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  98075. _this._updateScale = false;
  98076. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  98077. // Create Materials
  98078. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98079. coloredMaterial.disableLighting = true;
  98080. coloredMaterial.emissiveColor = color;
  98081. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98082. hoverColoredMaterial.disableLighting = true;
  98083. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  98084. // Build bounding box out of lines
  98085. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  98086. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  98087. var lines = [];
  98088. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  98089. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  98090. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  98091. 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));
  98092. 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));
  98093. 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));
  98094. 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));
  98095. 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));
  98096. 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));
  98097. 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));
  98098. 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));
  98099. 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));
  98100. lines.forEach(function (l) {
  98101. l.color = color;
  98102. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  98103. l.isPickable = false;
  98104. _this._lineBoundingBox.addChild(l);
  98105. });
  98106. _this._rootMesh.addChild(_this._lineBoundingBox);
  98107. // Create rotation spheres
  98108. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  98109. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  98110. var _loop_1 = function (i_1) {
  98111. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  98112. sphere.rotationQuaternion = new BABYLON.Quaternion();
  98113. sphere.material = coloredMaterial;
  98114. // Drag behavior
  98115. _dragBehavior = new BABYLON.PointerDragBehavior({});
  98116. _dragBehavior.moveAttached = false;
  98117. _dragBehavior.updateDragPlane = false;
  98118. sphere.addBehavior(_dragBehavior);
  98119. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  98120. var totalTurnAmountOfDrag = 0;
  98121. _dragBehavior.onDragStartObservable.add(function (event) {
  98122. startingTurnDirection.copyFrom(sphere.forward);
  98123. totalTurnAmountOfDrag = 0;
  98124. });
  98125. _dragBehavior.onDragObservable.add(function (event) {
  98126. _this.onRotationSphereDragObservable.notifyObservers({});
  98127. if (_this.attachedMesh) {
  98128. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  98129. var worldDragDirection = startingTurnDirection;
  98130. // Project the world right on to the drag plane
  98131. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  98132. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  98133. // project drag delta on to the resulting drag axis and rotate based on that
  98134. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  98135. // Make rotation relative to size of mesh.
  98136. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  98137. // Rotate based on axis
  98138. if (!_this.attachedMesh.rotationQuaternion) {
  98139. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  98140. }
  98141. if (!_this._anchorMesh.rotationQuaternion) {
  98142. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  98143. }
  98144. // Do not allow the object to turn more than a full circle
  98145. totalTurnAmountOfDrag += projectDist;
  98146. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  98147. if (i_1 >= 8) {
  98148. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  98149. }
  98150. else if (i_1 >= 4) {
  98151. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  98152. }
  98153. else {
  98154. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  98155. }
  98156. // Rotate around center of bounding box
  98157. _this._anchorMesh.addChild(_this.attachedMesh);
  98158. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  98159. _this._anchorMesh.removeChild(_this.attachedMesh);
  98160. }
  98161. _this.updateBoundingBox();
  98162. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  98163. }
  98164. });
  98165. // Selection/deselection
  98166. _dragBehavior.onDragStartObservable.add(function () {
  98167. _this.onDragStartObservable.notifyObservers({});
  98168. _this._selectNode(sphere);
  98169. });
  98170. _dragBehavior.onDragEndObservable.add(function () {
  98171. _this.onRotationSphereDragEndObservable.notifyObservers({});
  98172. _this._selectNode(null);
  98173. });
  98174. this_1._rotateSpheresParent.addChild(sphere);
  98175. };
  98176. var this_1 = this, _dragBehavior;
  98177. for (var i_1 = 0; i_1 < 12; i_1++) {
  98178. _loop_1(i_1);
  98179. }
  98180. _this._rootMesh.addChild(_this._rotateSpheresParent);
  98181. // Create scale cubes
  98182. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  98183. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  98184. for (var i = 0; i < 2; i++) {
  98185. for (var j = 0; j < 2; j++) {
  98186. var _loop_2 = function () {
  98187. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  98188. box.material = coloredMaterial;
  98189. // Dragging logic
  98190. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  98191. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  98192. _dragBehavior.moveAttached = false;
  98193. box.addBehavior(_dragBehavior);
  98194. _dragBehavior.onDragObservable.add(function (event) {
  98195. _this.onScaleBoxDragObservable.notifyObservers({});
  98196. if (_this.attachedMesh) {
  98197. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  98198. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  98199. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  98200. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  98201. _this.updateBoundingBox();
  98202. if (_this.scalePivot) {
  98203. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  98204. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  98205. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  98206. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  98207. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  98208. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  98209. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  98210. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  98211. }
  98212. else {
  98213. // Scale from the position of the opposite corner
  98214. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  98215. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  98216. }
  98217. _this._anchorMesh.addChild(_this.attachedMesh);
  98218. _this._anchorMesh.scaling.addInPlace(deltaScale);
  98219. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  98220. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  98221. }
  98222. _this._anchorMesh.removeChild(_this.attachedMesh);
  98223. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  98224. }
  98225. });
  98226. // Selection/deselection
  98227. _dragBehavior.onDragStartObservable.add(function () {
  98228. _this.onDragStartObservable.notifyObservers({});
  98229. _this._selectNode(box);
  98230. });
  98231. _dragBehavior.onDragEndObservable.add(function () {
  98232. _this.onScaleBoxDragEndObservable.notifyObservers({});
  98233. _this._selectNode(null);
  98234. });
  98235. this_2._scaleBoxesParent.addChild(box);
  98236. };
  98237. var this_2 = this, _dragBehavior;
  98238. for (var k = 0; k < 2; k++) {
  98239. _loop_2();
  98240. }
  98241. }
  98242. }
  98243. _this._rootMesh.addChild(_this._scaleBoxesParent);
  98244. // Hover color change
  98245. var pointerIds = new Array();
  98246. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  98247. if (!pointerIds[pointerInfo.event.pointerId]) {
  98248. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  98249. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  98250. pointerIds[pointerInfo.event.pointerId] = mesh;
  98251. mesh.material = hoverColoredMaterial;
  98252. }
  98253. });
  98254. }
  98255. else {
  98256. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  98257. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  98258. delete pointerIds[pointerInfo.event.pointerId];
  98259. }
  98260. }
  98261. });
  98262. // Update bounding box positions
  98263. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  98264. // Only update the bouding box if scaling has changed
  98265. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  98266. _this.updateBoundingBox();
  98267. }
  98268. });
  98269. _this.updateBoundingBox();
  98270. return _this;
  98271. }
  98272. /** @hidden */
  98273. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  98274. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  98275. // Save old pivot and set pivot to 0,0,0
  98276. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  98277. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  98278. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  98279. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  98280. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  98281. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  98282. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  98283. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  98284. }
  98285. }
  98286. BoundingBoxGizmo._PivotCached++;
  98287. };
  98288. /** @hidden */
  98289. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  98290. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  98291. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  98292. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  98293. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  98294. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  98295. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  98296. }
  98297. this._PivotCached--;
  98298. };
  98299. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  98300. if (value) {
  98301. // Reset anchor mesh to match attached mesh's scale
  98302. // This is needed to avoid invalid box/sphere position on first drag
  98303. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  98304. this._anchorMesh.addChild(value);
  98305. this._anchorMesh.removeChild(value);
  98306. BoundingBoxGizmo._RestorePivotPoint(value);
  98307. this.updateBoundingBox();
  98308. }
  98309. };
  98310. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  98311. this._rotateSpheresParent.getChildMeshes()
  98312. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  98313. m.isVisible = (!selectedMesh || m == selectedMesh);
  98314. });
  98315. };
  98316. /**
  98317. * Updates the bounding box information for the Gizmo
  98318. */
  98319. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  98320. if (this.attachedMesh) {
  98321. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  98322. this._update();
  98323. // Rotate based on axis
  98324. if (!this.attachedMesh.rotationQuaternion) {
  98325. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  98326. }
  98327. if (!this._anchorMesh.rotationQuaternion) {
  98328. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  98329. }
  98330. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  98331. // Store original position and reset mesh to origin before computing the bounding box
  98332. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  98333. this._tmpVector.copyFrom(this.attachedMesh.position);
  98334. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  98335. this.attachedMesh.position.set(0, 0, 0);
  98336. // Update bounding dimensions/positions
  98337. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  98338. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  98339. // Update gizmo to match bounding box scaling and rotation
  98340. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  98341. 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);
  98342. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  98343. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  98344. this._lineBoundingBox.computeWorldMatrix();
  98345. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  98346. // restore position/rotation values
  98347. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  98348. this.attachedMesh.position.copyFrom(this._tmpVector);
  98349. }
  98350. // Update rotation sphere locations
  98351. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  98352. for (var i = 0; i < 3; i++) {
  98353. for (var j = 0; j < 2; j++) {
  98354. for (var k = 0; k < 2; k++) {
  98355. var index = ((i * 4) + (j * 2)) + k;
  98356. if (i == 0) {
  98357. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  98358. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  98359. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  98360. }
  98361. if (i == 1) {
  98362. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  98363. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  98364. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  98365. }
  98366. if (i == 2) {
  98367. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  98368. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  98369. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  98370. }
  98371. if (this.fixedDragMeshScreenSize) {
  98372. this._rootMesh.computeWorldMatrix();
  98373. this._rotateSpheresParent.computeWorldMatrix();
  98374. rotateSpheres[index].computeWorldMatrix();
  98375. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  98376. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  98377. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  98378. }
  98379. else {
  98380. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  98381. }
  98382. }
  98383. }
  98384. }
  98385. // Update scale box locations
  98386. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  98387. for (var i = 0; i < 2; i++) {
  98388. for (var j = 0; j < 2; j++) {
  98389. for (var k = 0; k < 2; k++) {
  98390. var index = ((i * 4) + (j * 2)) + k;
  98391. if (scaleBoxes[index]) {
  98392. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  98393. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  98394. if (this.fixedDragMeshScreenSize) {
  98395. this._rootMesh.computeWorldMatrix();
  98396. this._scaleBoxesParent.computeWorldMatrix();
  98397. scaleBoxes[index].computeWorldMatrix();
  98398. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  98399. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  98400. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  98401. }
  98402. else {
  98403. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  98404. }
  98405. }
  98406. }
  98407. }
  98408. }
  98409. if (this.attachedMesh) {
  98410. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  98411. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  98412. }
  98413. };
  98414. /**
  98415. * Enables rotation on the specified axis and disables rotation on the others
  98416. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  98417. */
  98418. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  98419. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  98420. if (i < 4) {
  98421. m.setEnabled(axis.indexOf("x") != -1);
  98422. }
  98423. else if (i < 8) {
  98424. m.setEnabled(axis.indexOf("y") != -1);
  98425. }
  98426. else {
  98427. m.setEnabled(axis.indexOf("z") != -1);
  98428. }
  98429. });
  98430. };
  98431. /**
  98432. * Disposes of the gizmo
  98433. */
  98434. BoundingBoxGizmo.prototype.dispose = function () {
  98435. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  98436. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  98437. this._lineBoundingBox.dispose();
  98438. this._rotateSpheresParent.dispose();
  98439. this._scaleBoxesParent.dispose();
  98440. _super.prototype.dispose.call(this);
  98441. };
  98442. /**
  98443. * 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)
  98444. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  98445. * @returns the bounding box mesh with the passed in mesh as a child
  98446. */
  98447. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  98448. var makeNotPickable = function (root) {
  98449. root.isPickable = false;
  98450. root.getChildMeshes().forEach(function (c) {
  98451. makeNotPickable(c);
  98452. });
  98453. };
  98454. makeNotPickable(mesh);
  98455. // Reset position to get boudning box from origin with no rotation
  98456. if (!mesh.rotationQuaternion) {
  98457. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  98458. }
  98459. var oldPos = mesh.position.clone();
  98460. var oldRot = mesh.rotationQuaternion.clone();
  98461. mesh.rotationQuaternion.set(0, 0, 0, 1);
  98462. mesh.position.set(0, 0, 0);
  98463. // Update bounding dimensions/positions
  98464. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  98465. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  98466. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  98467. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  98468. // Restore original positions
  98469. mesh.addChild(box);
  98470. mesh.rotationQuaternion.copyFrom(oldRot);
  98471. mesh.position.copyFrom(oldPos);
  98472. // Reverse parenting
  98473. mesh.removeChild(box);
  98474. box.addChild(mesh);
  98475. box.visibility = 0;
  98476. return box;
  98477. };
  98478. /**
  98479. * CustomMeshes are not supported by this gizmo
  98480. * @param mesh The mesh to replace the default mesh of the gizmo
  98481. */
  98482. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  98483. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  98484. };
  98485. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  98486. // store/remove pivot point should only be applied during their outermost calls
  98487. BoundingBoxGizmo._PivotCached = 0;
  98488. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  98489. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  98490. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  98491. return BoundingBoxGizmo;
  98492. }(BABYLON.Gizmo));
  98493. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  98494. })(BABYLON || (BABYLON = {}));
  98495. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  98496. var BABYLON;
  98497. (function (BABYLON) {
  98498. /**
  98499. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  98500. */
  98501. var GizmoManager = /** @class */ (function () {
  98502. /**
  98503. * Instatiates a gizmo manager
  98504. * @param scene the scene to overlay the gizmos on top of
  98505. */
  98506. function GizmoManager(scene) {
  98507. var _this = this;
  98508. this.scene = scene;
  98509. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  98510. this._pointerObserver = null;
  98511. this._attachedMesh = null;
  98512. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  98513. /**
  98514. * When bounding box gizmo is enabled, this can be used to track drag/end events
  98515. */
  98516. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  98517. /**
  98518. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  98519. */
  98520. this.attachableMeshes = null;
  98521. /**
  98522. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  98523. */
  98524. this.usePointerToAttachGizmos = true;
  98525. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  98526. // Instatiate/dispose gizmos based on pointer actions
  98527. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  98528. if (!_this.usePointerToAttachGizmos) {
  98529. return;
  98530. }
  98531. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  98532. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  98533. var node = pointerInfo.pickInfo.pickedMesh;
  98534. if (_this.attachableMeshes == null) {
  98535. // Attach to the most parent node
  98536. while (node && node.parent != null) {
  98537. node = node.parent;
  98538. }
  98539. }
  98540. else {
  98541. // Attach to the parent node that is an attachableMesh
  98542. var found = false;
  98543. _this.attachableMeshes.forEach(function (mesh) {
  98544. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  98545. node = mesh;
  98546. found = true;
  98547. }
  98548. });
  98549. if (!found) {
  98550. node = null;
  98551. }
  98552. }
  98553. if (node instanceof BABYLON.AbstractMesh) {
  98554. _this.attachToMesh(node);
  98555. }
  98556. else {
  98557. _this.attachToMesh(null);
  98558. }
  98559. }
  98560. else {
  98561. _this.attachToMesh(null);
  98562. }
  98563. }
  98564. });
  98565. }
  98566. /**
  98567. * Attaches a set of gizmos to the specified mesh
  98568. * @param mesh The mesh the gizmo's should be attached to
  98569. */
  98570. GizmoManager.prototype.attachToMesh = function (mesh) {
  98571. if (this._attachedMesh) {
  98572. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  98573. }
  98574. this._attachedMesh = mesh;
  98575. for (var key in this.gizmos) {
  98576. var gizmo = (this.gizmos[key]);
  98577. if (gizmo && this._gizmosEnabled[key]) {
  98578. gizmo.attachedMesh = mesh;
  98579. }
  98580. }
  98581. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  98582. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  98583. }
  98584. };
  98585. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  98586. get: function () {
  98587. return this._gizmosEnabled.positionGizmo;
  98588. },
  98589. /**
  98590. * If the position gizmo is enabled
  98591. */
  98592. set: function (value) {
  98593. if (value) {
  98594. if (!this.gizmos.positionGizmo) {
  98595. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  98596. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  98597. }
  98598. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  98599. }
  98600. else if (this.gizmos.positionGizmo) {
  98601. this.gizmos.positionGizmo.attachedMesh = null;
  98602. }
  98603. this._gizmosEnabled.positionGizmo = value;
  98604. },
  98605. enumerable: true,
  98606. configurable: true
  98607. });
  98608. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  98609. get: function () {
  98610. return this._gizmosEnabled.rotationGizmo;
  98611. },
  98612. /**
  98613. * If the rotation gizmo is enabled
  98614. */
  98615. set: function (value) {
  98616. if (value) {
  98617. if (!this.gizmos.rotationGizmo) {
  98618. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  98619. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  98620. }
  98621. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  98622. }
  98623. else if (this.gizmos.rotationGizmo) {
  98624. this.gizmos.rotationGizmo.attachedMesh = null;
  98625. }
  98626. this._gizmosEnabled.rotationGizmo = value;
  98627. },
  98628. enumerable: true,
  98629. configurable: true
  98630. });
  98631. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  98632. get: function () {
  98633. return this._gizmosEnabled.scaleGizmo;
  98634. },
  98635. /**
  98636. * If the scale gizmo is enabled
  98637. */
  98638. set: function (value) {
  98639. if (value) {
  98640. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  98641. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  98642. }
  98643. else if (this.gizmos.scaleGizmo) {
  98644. this.gizmos.scaleGizmo.attachedMesh = null;
  98645. }
  98646. this._gizmosEnabled.scaleGizmo = value;
  98647. },
  98648. enumerable: true,
  98649. configurable: true
  98650. });
  98651. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  98652. get: function () {
  98653. return this._gizmosEnabled.boundingBoxGizmo;
  98654. },
  98655. /**
  98656. * If the boundingBox gizmo is enabled
  98657. */
  98658. set: function (value) {
  98659. if (value) {
  98660. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  98661. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  98662. if (this._attachedMesh) {
  98663. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  98664. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  98665. }
  98666. }
  98667. else if (this.gizmos.boundingBoxGizmo) {
  98668. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  98669. }
  98670. this._gizmosEnabled.boundingBoxGizmo = value;
  98671. },
  98672. enumerable: true,
  98673. configurable: true
  98674. });
  98675. /**
  98676. * Disposes of the gizmo manager
  98677. */
  98678. GizmoManager.prototype.dispose = function () {
  98679. this.scene.onPointerObservable.remove(this._pointerObserver);
  98680. for (var key in this.gizmos) {
  98681. var gizmo = (this.gizmos[key]);
  98682. if (gizmo) {
  98683. gizmo.dispose();
  98684. }
  98685. }
  98686. this.boundingBoxDragBehavior.detach();
  98687. };
  98688. return GizmoManager;
  98689. }());
  98690. BABYLON.GizmoManager = GizmoManager;
  98691. })(BABYLON || (BABYLON = {}));
  98692. //# sourceMappingURL=babylon.gizmoManager.js.map
  98693. var BABYLON;
  98694. (function (BABYLON) {
  98695. /**
  98696. * Defines a target to use with MorphTargetManager
  98697. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  98698. */
  98699. var MorphTarget = /** @class */ (function () {
  98700. /**
  98701. * Creates a new MorphTarget
  98702. * @param name defines the name of the target
  98703. * @param influence defines the influence to use
  98704. */
  98705. function MorphTarget(
  98706. /** defines the name of the target */
  98707. name, influence, scene) {
  98708. if (influence === void 0) { influence = 0; }
  98709. if (scene === void 0) { scene = null; }
  98710. this.name = name;
  98711. /**
  98712. * Gets or sets the list of animations
  98713. */
  98714. this.animations = new Array();
  98715. this._positions = null;
  98716. this._normals = null;
  98717. this._tangents = null;
  98718. /**
  98719. * Observable raised when the influence changes
  98720. */
  98721. this.onInfluenceChanged = new BABYLON.Observable();
  98722. this._animationPropertiesOverride = null;
  98723. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  98724. this.influence = influence;
  98725. }
  98726. Object.defineProperty(MorphTarget.prototype, "influence", {
  98727. /**
  98728. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  98729. */
  98730. get: function () {
  98731. return this._influence;
  98732. },
  98733. set: function (influence) {
  98734. if (this._influence === influence) {
  98735. return;
  98736. }
  98737. var previous = this._influence;
  98738. this._influence = influence;
  98739. if (this.onInfluenceChanged.hasObservers) {
  98740. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  98741. }
  98742. },
  98743. enumerable: true,
  98744. configurable: true
  98745. });
  98746. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  98747. /**
  98748. * Gets or sets the animation properties override
  98749. */
  98750. get: function () {
  98751. if (!this._animationPropertiesOverride && this._scene) {
  98752. return this._scene.animationPropertiesOverride;
  98753. }
  98754. return this._animationPropertiesOverride;
  98755. },
  98756. set: function (value) {
  98757. this._animationPropertiesOverride = value;
  98758. },
  98759. enumerable: true,
  98760. configurable: true
  98761. });
  98762. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  98763. /**
  98764. * Gets a boolean defining if the target contains position data
  98765. */
  98766. get: function () {
  98767. return !!this._positions;
  98768. },
  98769. enumerable: true,
  98770. configurable: true
  98771. });
  98772. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  98773. /**
  98774. * Gets a boolean defining if the target contains normal data
  98775. */
  98776. get: function () {
  98777. return !!this._normals;
  98778. },
  98779. enumerable: true,
  98780. configurable: true
  98781. });
  98782. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  98783. /**
  98784. * Gets a boolean defining if the target contains tangent data
  98785. */
  98786. get: function () {
  98787. return !!this._tangents;
  98788. },
  98789. enumerable: true,
  98790. configurable: true
  98791. });
  98792. /**
  98793. * Affects position data to this target
  98794. * @param data defines the position data to use
  98795. */
  98796. MorphTarget.prototype.setPositions = function (data) {
  98797. this._positions = data;
  98798. };
  98799. /**
  98800. * Gets the position data stored in this target
  98801. * @returns a FloatArray containing the position data (or null if not present)
  98802. */
  98803. MorphTarget.prototype.getPositions = function () {
  98804. return this._positions;
  98805. };
  98806. /**
  98807. * Affects normal data to this target
  98808. * @param data defines the normal data to use
  98809. */
  98810. MorphTarget.prototype.setNormals = function (data) {
  98811. this._normals = data;
  98812. };
  98813. /**
  98814. * Gets the normal data stored in this target
  98815. * @returns a FloatArray containing the normal data (or null if not present)
  98816. */
  98817. MorphTarget.prototype.getNormals = function () {
  98818. return this._normals;
  98819. };
  98820. /**
  98821. * Affects tangent data to this target
  98822. * @param data defines the tangent data to use
  98823. */
  98824. MorphTarget.prototype.setTangents = function (data) {
  98825. this._tangents = data;
  98826. };
  98827. /**
  98828. * Gets the tangent data stored in this target
  98829. * @returns a FloatArray containing the tangent data (or null if not present)
  98830. */
  98831. MorphTarget.prototype.getTangents = function () {
  98832. return this._tangents;
  98833. };
  98834. /**
  98835. * Serializes the current target into a Serialization object
  98836. * @returns the serialized object
  98837. */
  98838. MorphTarget.prototype.serialize = function () {
  98839. var serializationObject = {};
  98840. serializationObject.name = this.name;
  98841. serializationObject.influence = this.influence;
  98842. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  98843. if (this.hasNormals) {
  98844. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  98845. }
  98846. if (this.hasTangents) {
  98847. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  98848. }
  98849. // Animations
  98850. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  98851. return serializationObject;
  98852. };
  98853. // Statics
  98854. /**
  98855. * Creates a new target from serialized data
  98856. * @param serializationObject defines the serialized data to use
  98857. * @returns a new MorphTarget
  98858. */
  98859. MorphTarget.Parse = function (serializationObject) {
  98860. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  98861. result.setPositions(serializationObject.positions);
  98862. if (serializationObject.normals) {
  98863. result.setNormals(serializationObject.normals);
  98864. }
  98865. if (serializationObject.tangents) {
  98866. result.setTangents(serializationObject.tangents);
  98867. }
  98868. // Animations
  98869. if (serializationObject.animations) {
  98870. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  98871. var parsedAnimation = serializationObject.animations[animationIndex];
  98872. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  98873. }
  98874. }
  98875. return result;
  98876. };
  98877. /**
  98878. * Creates a MorphTarget from mesh data
  98879. * @param mesh defines the source mesh
  98880. * @param name defines the name to use for the new target
  98881. * @param influence defines the influence to attach to the target
  98882. * @returns a new MorphTarget
  98883. */
  98884. MorphTarget.FromMesh = function (mesh, name, influence) {
  98885. if (!name) {
  98886. name = mesh.name;
  98887. }
  98888. var result = new MorphTarget(name, influence, mesh.getScene());
  98889. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  98890. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  98891. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  98892. }
  98893. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  98894. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  98895. }
  98896. return result;
  98897. };
  98898. return MorphTarget;
  98899. }());
  98900. BABYLON.MorphTarget = MorphTarget;
  98901. })(BABYLON || (BABYLON = {}));
  98902. //# sourceMappingURL=babylon.morphTarget.js.map
  98903. var BABYLON;
  98904. (function (BABYLON) {
  98905. /**
  98906. * This class is used to deform meshes using morphing between different targets
  98907. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  98908. */
  98909. var MorphTargetManager = /** @class */ (function () {
  98910. /**
  98911. * Creates a new MorphTargetManager
  98912. * @param scene defines the current scene
  98913. */
  98914. function MorphTargetManager(scene) {
  98915. if (scene === void 0) { scene = null; }
  98916. this._targets = new Array();
  98917. this._targetObservable = new Array();
  98918. this._activeTargets = new BABYLON.SmartArray(16);
  98919. this._supportsNormals = false;
  98920. this._supportsTangents = false;
  98921. this._vertexCount = 0;
  98922. this._uniqueId = 0;
  98923. this._tempInfluences = new Array();
  98924. if (!scene) {
  98925. scene = BABYLON.Engine.LastCreatedScene;
  98926. }
  98927. this._scene = scene;
  98928. if (this._scene) {
  98929. this._scene.morphTargetManagers.push(this);
  98930. this._uniqueId = this._scene.getUniqueId();
  98931. }
  98932. }
  98933. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  98934. /**
  98935. * Gets the unique ID of this manager
  98936. */
  98937. get: function () {
  98938. return this._uniqueId;
  98939. },
  98940. enumerable: true,
  98941. configurable: true
  98942. });
  98943. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  98944. /**
  98945. * Gets the number of vertices handled by this manager
  98946. */
  98947. get: function () {
  98948. return this._vertexCount;
  98949. },
  98950. enumerable: true,
  98951. configurable: true
  98952. });
  98953. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  98954. /**
  98955. * Gets a boolean indicating if this manager supports morphing of normals
  98956. */
  98957. get: function () {
  98958. return this._supportsNormals;
  98959. },
  98960. enumerable: true,
  98961. configurable: true
  98962. });
  98963. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  98964. /**
  98965. * Gets a boolean indicating if this manager supports morphing of tangents
  98966. */
  98967. get: function () {
  98968. return this._supportsTangents;
  98969. },
  98970. enumerable: true,
  98971. configurable: true
  98972. });
  98973. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  98974. /**
  98975. * Gets the number of targets stored in this manager
  98976. */
  98977. get: function () {
  98978. return this._targets.length;
  98979. },
  98980. enumerable: true,
  98981. configurable: true
  98982. });
  98983. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  98984. /**
  98985. * Gets the number of influencers (ie. the number of targets with influences > 0)
  98986. */
  98987. get: function () {
  98988. return this._activeTargets.length;
  98989. },
  98990. enumerable: true,
  98991. configurable: true
  98992. });
  98993. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  98994. /**
  98995. * Gets the list of influences (one per target)
  98996. */
  98997. get: function () {
  98998. return this._influences;
  98999. },
  99000. enumerable: true,
  99001. configurable: true
  99002. });
  99003. /**
  99004. * Gets the active target at specified index. An active target is a target with an influence > 0
  99005. * @param index defines the index to check
  99006. * @returns the requested target
  99007. */
  99008. MorphTargetManager.prototype.getActiveTarget = function (index) {
  99009. return this._activeTargets.data[index];
  99010. };
  99011. /**
  99012. * Gets the target at specified index
  99013. * @param index defines the index to check
  99014. * @returns the requested target
  99015. */
  99016. MorphTargetManager.prototype.getTarget = function (index) {
  99017. return this._targets[index];
  99018. };
  99019. /**
  99020. * Add a new target to this manager
  99021. * @param target defines the target to add
  99022. */
  99023. MorphTargetManager.prototype.addTarget = function (target) {
  99024. var _this = this;
  99025. this._targets.push(target);
  99026. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  99027. _this._syncActiveTargets(needUpdate);
  99028. }));
  99029. this._syncActiveTargets(true);
  99030. };
  99031. /**
  99032. * Removes a target from the manager
  99033. * @param target defines the target to remove
  99034. */
  99035. MorphTargetManager.prototype.removeTarget = function (target) {
  99036. var index = this._targets.indexOf(target);
  99037. if (index >= 0) {
  99038. this._targets.splice(index, 1);
  99039. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  99040. this._syncActiveTargets(true);
  99041. }
  99042. };
  99043. /**
  99044. * Serializes the current manager into a Serialization object
  99045. * @returns the serialized object
  99046. */
  99047. MorphTargetManager.prototype.serialize = function () {
  99048. var serializationObject = {};
  99049. serializationObject.id = this.uniqueId;
  99050. serializationObject.targets = [];
  99051. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  99052. var target = _a[_i];
  99053. serializationObject.targets.push(target.serialize());
  99054. }
  99055. return serializationObject;
  99056. };
  99057. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  99058. var influenceCount = 0;
  99059. this._activeTargets.reset();
  99060. this._supportsNormals = true;
  99061. this._supportsTangents = true;
  99062. this._vertexCount = 0;
  99063. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  99064. var target = _a[_i];
  99065. this._activeTargets.push(target);
  99066. this._tempInfluences[influenceCount++] = target.influence;
  99067. var positions = target.getPositions();
  99068. if (positions) {
  99069. this._supportsNormals = this._supportsNormals && target.hasNormals;
  99070. this._supportsTangents = this._supportsTangents && target.hasTangents;
  99071. var vertexCount = positions.length / 3;
  99072. if (this._vertexCount === 0) {
  99073. this._vertexCount = vertexCount;
  99074. }
  99075. else if (this._vertexCount !== vertexCount) {
  99076. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  99077. return;
  99078. }
  99079. }
  99080. }
  99081. if (!this._influences || this._influences.length !== influenceCount) {
  99082. this._influences = new Float32Array(influenceCount);
  99083. }
  99084. for (var index = 0; index < influenceCount; index++) {
  99085. this._influences[index] = this._tempInfluences[index];
  99086. }
  99087. if (needUpdate) {
  99088. this.synchronize();
  99089. }
  99090. };
  99091. /**
  99092. * Syncrhonize the targets with all the meshes using this morph target manager
  99093. */
  99094. MorphTargetManager.prototype.synchronize = function () {
  99095. if (!this._scene) {
  99096. return;
  99097. }
  99098. // Flag meshes as dirty to resync with the active targets
  99099. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  99100. var mesh = _a[_i];
  99101. if (mesh.morphTargetManager === this) {
  99102. mesh._syncGeometryWithMorphTargetManager();
  99103. }
  99104. }
  99105. };
  99106. // Statics
  99107. /**
  99108. * Creates a new MorphTargetManager from serialized data
  99109. * @param serializationObject defines the serialized data
  99110. * @param scene defines the hosting scene
  99111. * @returns the new MorphTargetManager
  99112. */
  99113. MorphTargetManager.Parse = function (serializationObject, scene) {
  99114. var result = new MorphTargetManager(scene);
  99115. result._uniqueId = serializationObject.id;
  99116. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  99117. var targetData = _a[_i];
  99118. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  99119. }
  99120. return result;
  99121. };
  99122. return MorphTargetManager;
  99123. }());
  99124. BABYLON.MorphTargetManager = MorphTargetManager;
  99125. })(BABYLON || (BABYLON = {}));
  99126. //# sourceMappingURL=babylon.morphTargetManager.js.map
  99127. var BABYLON;
  99128. (function (BABYLON) {
  99129. var Octree = /** @class */ (function () {
  99130. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  99131. if (maxDepth === void 0) { maxDepth = 2; }
  99132. this.maxDepth = maxDepth;
  99133. this.dynamicContent = new Array();
  99134. this._maxBlockCapacity = maxBlockCapacity || 64;
  99135. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  99136. this._creationFunc = creationFunc;
  99137. }
  99138. // Methods
  99139. Octree.prototype.update = function (worldMin, worldMax, entries) {
  99140. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  99141. };
  99142. Octree.prototype.addMesh = function (entry) {
  99143. for (var index = 0; index < this.blocks.length; index++) {
  99144. var block = this.blocks[index];
  99145. block.addEntry(entry);
  99146. }
  99147. };
  99148. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  99149. this._selectionContent.reset();
  99150. for (var index = 0; index < this.blocks.length; index++) {
  99151. var block = this.blocks[index];
  99152. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  99153. }
  99154. if (allowDuplicate) {
  99155. this._selectionContent.concat(this.dynamicContent);
  99156. }
  99157. else {
  99158. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  99159. }
  99160. return this._selectionContent;
  99161. };
  99162. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  99163. this._selectionContent.reset();
  99164. for (var index = 0; index < this.blocks.length; index++) {
  99165. var block = this.blocks[index];
  99166. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  99167. }
  99168. if (allowDuplicate) {
  99169. this._selectionContent.concat(this.dynamicContent);
  99170. }
  99171. else {
  99172. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  99173. }
  99174. return this._selectionContent;
  99175. };
  99176. Octree.prototype.intersectsRay = function (ray) {
  99177. this._selectionContent.reset();
  99178. for (var index = 0; index < this.blocks.length; index++) {
  99179. var block = this.blocks[index];
  99180. block.intersectsRay(ray, this._selectionContent);
  99181. }
  99182. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  99183. return this._selectionContent;
  99184. };
  99185. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  99186. target.blocks = new Array();
  99187. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  99188. // Segmenting space
  99189. for (var x = 0; x < 2; x++) {
  99190. for (var y = 0; y < 2; y++) {
  99191. for (var z = 0; z < 2; z++) {
  99192. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  99193. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  99194. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  99195. block.addEntries(entries);
  99196. target.blocks.push(block);
  99197. }
  99198. }
  99199. }
  99200. };
  99201. Octree.CreationFuncForMeshes = function (entry, block) {
  99202. var boundingInfo = entry.getBoundingInfo();
  99203. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  99204. block.entries.push(entry);
  99205. }
  99206. };
  99207. Octree.CreationFuncForSubMeshes = function (entry, block) {
  99208. var boundingInfo = entry.getBoundingInfo();
  99209. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  99210. block.entries.push(entry);
  99211. }
  99212. };
  99213. return Octree;
  99214. }());
  99215. BABYLON.Octree = Octree;
  99216. })(BABYLON || (BABYLON = {}));
  99217. //# sourceMappingURL=babylon.octree.js.map
  99218. var BABYLON;
  99219. (function (BABYLON) {
  99220. /**
  99221. * Class used to store a cell in an octree
  99222. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  99223. */
  99224. var OctreeBlock = /** @class */ (function () {
  99225. /**
  99226. * Creates a new block
  99227. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  99228. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  99229. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  99230. * @param depth defines the current depth of this block in the octree
  99231. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  99232. * @param creationFunc defines a callback to call when an element is added to the block
  99233. */
  99234. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  99235. /**
  99236. * Gets the content of the current block
  99237. */
  99238. this.entries = new Array();
  99239. this._boundingVectors = new Array();
  99240. this._capacity = capacity;
  99241. this._depth = depth;
  99242. this._maxDepth = maxDepth;
  99243. this._creationFunc = creationFunc;
  99244. this._minPoint = minPoint;
  99245. this._maxPoint = maxPoint;
  99246. this._boundingVectors.push(minPoint.clone());
  99247. this._boundingVectors.push(maxPoint.clone());
  99248. this._boundingVectors.push(minPoint.clone());
  99249. this._boundingVectors[2].x = maxPoint.x;
  99250. this._boundingVectors.push(minPoint.clone());
  99251. this._boundingVectors[3].y = maxPoint.y;
  99252. this._boundingVectors.push(minPoint.clone());
  99253. this._boundingVectors[4].z = maxPoint.z;
  99254. this._boundingVectors.push(maxPoint.clone());
  99255. this._boundingVectors[5].z = minPoint.z;
  99256. this._boundingVectors.push(maxPoint.clone());
  99257. this._boundingVectors[6].x = minPoint.x;
  99258. this._boundingVectors.push(maxPoint.clone());
  99259. this._boundingVectors[7].y = minPoint.y;
  99260. }
  99261. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  99262. // Property
  99263. /**
  99264. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  99265. */
  99266. get: function () {
  99267. return this._capacity;
  99268. },
  99269. enumerable: true,
  99270. configurable: true
  99271. });
  99272. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  99273. /**
  99274. * Gets the minimum vector (in world space) of the block's bounding box
  99275. */
  99276. get: function () {
  99277. return this._minPoint;
  99278. },
  99279. enumerable: true,
  99280. configurable: true
  99281. });
  99282. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  99283. /**
  99284. * Gets the maximum vector (in world space) of the block's bounding box
  99285. */
  99286. get: function () {
  99287. return this._maxPoint;
  99288. },
  99289. enumerable: true,
  99290. configurable: true
  99291. });
  99292. // Methods
  99293. /**
  99294. * Add a new element to this block
  99295. * @param entry defines the element to add
  99296. */
  99297. OctreeBlock.prototype.addEntry = function (entry) {
  99298. if (this.blocks) {
  99299. for (var index = 0; index < this.blocks.length; index++) {
  99300. var block = this.blocks[index];
  99301. block.addEntry(entry);
  99302. }
  99303. return;
  99304. }
  99305. this._creationFunc(entry, this);
  99306. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  99307. this.createInnerBlocks();
  99308. }
  99309. };
  99310. /**
  99311. * Add an array of elements to this block
  99312. * @param entries defines the array of elements to add
  99313. */
  99314. OctreeBlock.prototype.addEntries = function (entries) {
  99315. for (var index = 0; index < entries.length; index++) {
  99316. var mesh = entries[index];
  99317. this.addEntry(mesh);
  99318. }
  99319. };
  99320. /**
  99321. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  99322. * @param frustumPlanes defines the frustum planes to test
  99323. * @param selection defines the array to store current content if selection is positive
  99324. * @param allowDuplicate defines if the selection array can contains duplicated entries
  99325. */
  99326. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  99327. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  99328. if (this.blocks) {
  99329. for (var index = 0; index < this.blocks.length; index++) {
  99330. var block = this.blocks[index];
  99331. block.select(frustumPlanes, selection, allowDuplicate);
  99332. }
  99333. return;
  99334. }
  99335. if (allowDuplicate) {
  99336. selection.concat(this.entries);
  99337. }
  99338. else {
  99339. selection.concatWithNoDuplicate(this.entries);
  99340. }
  99341. }
  99342. };
  99343. /**
  99344. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  99345. * @param sphereCenter defines the bounding sphere center
  99346. * @param sphereRadius defines the bounding sphere radius
  99347. * @param selection defines the array to store current content if selection is positive
  99348. * @param allowDuplicate defines if the selection array can contains duplicated entries
  99349. */
  99350. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  99351. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  99352. if (this.blocks) {
  99353. for (var index = 0; index < this.blocks.length; index++) {
  99354. var block = this.blocks[index];
  99355. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  99356. }
  99357. return;
  99358. }
  99359. if (allowDuplicate) {
  99360. selection.concat(this.entries);
  99361. }
  99362. else {
  99363. selection.concatWithNoDuplicate(this.entries);
  99364. }
  99365. }
  99366. };
  99367. /**
  99368. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  99369. * @param ray defines the ray to test with
  99370. * @param selection defines the array to store current content if selection is positive
  99371. */
  99372. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  99373. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  99374. if (this.blocks) {
  99375. for (var index = 0; index < this.blocks.length; index++) {
  99376. var block = this.blocks[index];
  99377. block.intersectsRay(ray, selection);
  99378. }
  99379. return;
  99380. }
  99381. selection.concatWithNoDuplicate(this.entries);
  99382. }
  99383. };
  99384. /**
  99385. * Subdivide the content into child blocks (this block will then be empty)
  99386. */
  99387. OctreeBlock.prototype.createInnerBlocks = function () {
  99388. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  99389. };
  99390. return OctreeBlock;
  99391. }());
  99392. BABYLON.OctreeBlock = OctreeBlock;
  99393. })(BABYLON || (BABYLON = {}));
  99394. //# sourceMappingURL=babylon.octreeBlock.js.map
  99395. var BABYLON;
  99396. (function (BABYLON) {
  99397. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  99398. if (maxCapacity === void 0) { maxCapacity = 64; }
  99399. if (maxDepth === void 0) { maxDepth = 2; }
  99400. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  99401. if (!component) {
  99402. component = new OctreeSceneComponent(this);
  99403. this._addComponent(component);
  99404. }
  99405. if (!this._selectionOctree) {
  99406. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  99407. }
  99408. var worldExtends = this.getWorldExtends();
  99409. // Update octree
  99410. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  99411. return this._selectionOctree;
  99412. };
  99413. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  99414. get: function () {
  99415. return this._selectionOctree;
  99416. },
  99417. enumerable: true,
  99418. configurable: true
  99419. });
  99420. /**
  99421. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  99422. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  99423. * @param maxCapacity defines the maximum size of each block (64 by default)
  99424. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  99425. * @returns the new octree
  99426. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  99427. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  99428. */
  99429. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  99430. if (maxCapacity === void 0) { maxCapacity = 64; }
  99431. if (maxDepth === void 0) { maxDepth = 2; }
  99432. var scene = this.getScene();
  99433. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  99434. if (!component) {
  99435. component = new OctreeSceneComponent(scene);
  99436. scene._addComponent(component);
  99437. }
  99438. if (!this._submeshesOctree) {
  99439. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  99440. }
  99441. this.computeWorldMatrix(true);
  99442. var boundingInfo = this.getBoundingInfo();
  99443. // Update octree
  99444. var bbox = boundingInfo.boundingBox;
  99445. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  99446. return this._submeshesOctree;
  99447. };
  99448. /**
  99449. * Defines the octree scene component responsible to manage any octrees
  99450. * in a given scene.
  99451. */
  99452. var OctreeSceneComponent = /** @class */ (function () {
  99453. /**
  99454. * Creates a new instance of the component for the given scene
  99455. * @param scene Defines the scene to register the component in
  99456. */
  99457. function OctreeSceneComponent(scene) {
  99458. /**
  99459. * The component name helpfull to identify the component in the list of scene components.
  99460. */
  99461. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  99462. /**
  99463. * Indicates if the meshes have been checked to make sure they are isEnabled()
  99464. */
  99465. this.checksIsEnabled = true;
  99466. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  99467. this.scene = scene;
  99468. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  99469. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  99470. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  99471. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  99472. }
  99473. /**
  99474. * Registers the component in a given scene
  99475. */
  99476. OctreeSceneComponent.prototype.register = function () {
  99477. var _this = this;
  99478. this.scene.onMeshRemovedObservable.add(function (mesh) {
  99479. var sceneOctree = _this.scene.selectionOctree;
  99480. if (sceneOctree !== undefined && sceneOctree !== null) {
  99481. var index = sceneOctree.dynamicContent.indexOf(mesh);
  99482. if (index !== -1) {
  99483. sceneOctree.dynamicContent.splice(index, 1);
  99484. }
  99485. }
  99486. });
  99487. this.scene.onMeshImportedObservable.add(function (mesh) {
  99488. var sceneOctree = _this.scene.selectionOctree;
  99489. if (sceneOctree !== undefined && sceneOctree !== null) {
  99490. sceneOctree.addMesh(mesh);
  99491. }
  99492. });
  99493. };
  99494. /**
  99495. * Return the list of active meshes
  99496. * @returns the list of active meshes
  99497. */
  99498. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  99499. if (this.scene._selectionOctree) {
  99500. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  99501. return selection;
  99502. }
  99503. return this.scene._getDefaultMeshCandidates();
  99504. };
  99505. /**
  99506. * Return the list of active sub meshes
  99507. * @param mesh The mesh to get the candidates sub meshes from
  99508. * @returns the list of active sub meshes
  99509. */
  99510. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  99511. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  99512. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  99513. return intersections;
  99514. }
  99515. return this.scene._getDefaultSubMeshCandidates(mesh);
  99516. };
  99517. /**
  99518. * Return the list of sub meshes intersecting with a given local ray
  99519. * @param mesh defines the mesh to find the submesh for
  99520. * @param localRay defines the ray in local space
  99521. * @returns the list of intersecting sub meshes
  99522. */
  99523. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  99524. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  99525. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  99526. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  99527. return intersections;
  99528. }
  99529. return this.scene._getDefaultSubMeshCandidates(mesh);
  99530. };
  99531. /**
  99532. * Return the list of sub meshes colliding with a collider
  99533. * @param mesh defines the mesh to find the submesh for
  99534. * @param collider defines the collider to evaluate the collision against
  99535. * @returns the list of colliding sub meshes
  99536. */
  99537. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  99538. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  99539. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  99540. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  99541. return intersections;
  99542. }
  99543. return this.scene._getDefaultSubMeshCandidates(mesh);
  99544. };
  99545. /**
  99546. * Rebuilds the elements related to this component in case of
  99547. * context lost for instance.
  99548. */
  99549. OctreeSceneComponent.prototype.rebuild = function () {
  99550. // Nothing to do here.
  99551. };
  99552. /**
  99553. * Disposes the component and the associated ressources.
  99554. */
  99555. OctreeSceneComponent.prototype.dispose = function () {
  99556. // Nothing to do here.
  99557. };
  99558. return OctreeSceneComponent;
  99559. }());
  99560. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  99561. })(BABYLON || (BABYLON = {}));
  99562. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  99563. var BABYLON;
  99564. (function (BABYLON) {
  99565. /**
  99566. * Postprocess used to generate anaglyphic rendering
  99567. */
  99568. var AnaglyphPostProcess = /** @class */ (function (_super) {
  99569. __extends(AnaglyphPostProcess, _super);
  99570. /**
  99571. * Creates a new AnaglyphPostProcess
  99572. * @param name defines postprocess name
  99573. * @param options defines creation options or target ratio scale
  99574. * @param rigCameras defines cameras using this postprocess
  99575. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  99576. * @param engine defines hosting engine
  99577. * @param reusable defines if the postprocess will be reused multiple times per frame
  99578. */
  99579. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  99580. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  99581. _this._passedProcess = rigCameras[0]._rigPostProcess;
  99582. _this.onApplyObservable.add(function (effect) {
  99583. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  99584. });
  99585. return _this;
  99586. }
  99587. return AnaglyphPostProcess;
  99588. }(BABYLON.PostProcess));
  99589. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  99590. })(BABYLON || (BABYLON = {}));
  99591. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  99592. var BABYLON;
  99593. (function (BABYLON) {
  99594. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  99595. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99596. });
  99597. /**
  99598. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  99599. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99600. */
  99601. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  99602. __extends(AnaglyphArcRotateCamera, _super);
  99603. /**
  99604. * Creates a new AnaglyphArcRotateCamera
  99605. * @param name defines camera name
  99606. * @param alpha defines alpha angle (in radians)
  99607. * @param beta defines beta angle (in radians)
  99608. * @param radius defines radius
  99609. * @param target defines camera target
  99610. * @param interaxialDistance defines distance between each color axis
  99611. * @param scene defines the hosting scene
  99612. */
  99613. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  99614. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  99615. _this.interaxialDistance = interaxialDistance;
  99616. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99617. return _this;
  99618. }
  99619. /**
  99620. * Gets camera class name
  99621. * @returns AnaglyphArcRotateCamera
  99622. */
  99623. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  99624. return "AnaglyphArcRotateCamera";
  99625. };
  99626. return AnaglyphArcRotateCamera;
  99627. }(BABYLON.ArcRotateCamera));
  99628. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  99629. })(BABYLON || (BABYLON = {}));
  99630. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  99631. var BABYLON;
  99632. (function (BABYLON) {
  99633. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  99634. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99635. });
  99636. /**
  99637. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  99638. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99639. */
  99640. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  99641. __extends(AnaglyphFreeCamera, _super);
  99642. /**
  99643. * Creates a new AnaglyphFreeCamera
  99644. * @param name defines camera name
  99645. * @param position defines initial position
  99646. * @param interaxialDistance defines distance between each color axis
  99647. * @param scene defines the hosting scene
  99648. */
  99649. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  99650. var _this = _super.call(this, name, position, scene) || this;
  99651. _this.interaxialDistance = interaxialDistance;
  99652. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99653. return _this;
  99654. }
  99655. /**
  99656. * Gets camera class name
  99657. * @returns AnaglyphFreeCamera
  99658. */
  99659. AnaglyphFreeCamera.prototype.getClassName = function () {
  99660. return "AnaglyphFreeCamera";
  99661. };
  99662. return AnaglyphFreeCamera;
  99663. }(BABYLON.FreeCamera));
  99664. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  99665. })(BABYLON || (BABYLON = {}));
  99666. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  99667. var BABYLON;
  99668. (function (BABYLON) {
  99669. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  99670. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99671. });
  99672. /**
  99673. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  99674. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99675. */
  99676. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  99677. __extends(AnaglyphGamepadCamera, _super);
  99678. /**
  99679. * Creates a new AnaglyphGamepadCamera
  99680. * @param name defines camera name
  99681. * @param position defines initial position
  99682. * @param interaxialDistance defines distance between each color axis
  99683. * @param scene defines the hosting scene
  99684. */
  99685. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  99686. var _this = _super.call(this, name, position, scene) || this;
  99687. _this.interaxialDistance = interaxialDistance;
  99688. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99689. return _this;
  99690. }
  99691. /**
  99692. * Gets camera class name
  99693. * @returns AnaglyphGamepadCamera
  99694. */
  99695. AnaglyphGamepadCamera.prototype.getClassName = function () {
  99696. return "AnaglyphGamepadCamera";
  99697. };
  99698. return AnaglyphGamepadCamera;
  99699. }(BABYLON.GamepadCamera));
  99700. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  99701. })(BABYLON || (BABYLON = {}));
  99702. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  99703. var BABYLON;
  99704. (function (BABYLON) {
  99705. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  99706. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99707. });
  99708. /**
  99709. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  99710. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99711. */
  99712. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  99713. __extends(AnaglyphUniversalCamera, _super);
  99714. /**
  99715. * Creates a new AnaglyphUniversalCamera
  99716. * @param name defines camera name
  99717. * @param position defines initial position
  99718. * @param interaxialDistance defines distance between each color axis
  99719. * @param scene defines the hosting scene
  99720. */
  99721. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  99722. var _this = _super.call(this, name, position, scene) || this;
  99723. _this.interaxialDistance = interaxialDistance;
  99724. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99725. return _this;
  99726. }
  99727. /**
  99728. * Gets camera class name
  99729. * @returns AnaglyphUniversalCamera
  99730. */
  99731. AnaglyphUniversalCamera.prototype.getClassName = function () {
  99732. return "AnaglyphUniversalCamera";
  99733. };
  99734. return AnaglyphUniversalCamera;
  99735. }(BABYLON.UniversalCamera));
  99736. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  99737. })(BABYLON || (BABYLON = {}));
  99738. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  99739. var BABYLON;
  99740. (function (BABYLON) {
  99741. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  99742. __extends(StereoscopicInterlacePostProcess, _super);
  99743. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  99744. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  99745. _this._passedProcess = rigCameras[0]._rigPostProcess;
  99746. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  99747. _this.onSizeChangedObservable.add(function () {
  99748. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  99749. });
  99750. _this.onApplyObservable.add(function (effect) {
  99751. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  99752. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  99753. });
  99754. return _this;
  99755. }
  99756. return StereoscopicInterlacePostProcess;
  99757. }(BABYLON.PostProcess));
  99758. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  99759. })(BABYLON || (BABYLON = {}));
  99760. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  99761. var BABYLON;
  99762. (function (BABYLON) {
  99763. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  99764. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99765. });
  99766. /**
  99767. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  99768. * @see http://doc.babylonjs.com/features/cameras
  99769. */
  99770. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  99771. __extends(StereoscopicArcRotateCamera, _super);
  99772. /**
  99773. * Creates a new StereoscopicArcRotateCamera
  99774. * @param name defines camera name
  99775. * @param alpha defines alpha angle (in radians)
  99776. * @param beta defines beta angle (in radians)
  99777. * @param radius defines radius
  99778. * @param target defines camera target
  99779. * @param interaxialDistance defines distance between each color axis
  99780. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99781. * @param scene defines the hosting scene
  99782. */
  99783. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  99784. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  99785. _this.interaxialDistance = interaxialDistance;
  99786. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99787. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99788. return _this;
  99789. }
  99790. /**
  99791. * Gets camera class name
  99792. * @returns StereoscopicArcRotateCamera
  99793. */
  99794. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  99795. return "StereoscopicArcRotateCamera";
  99796. };
  99797. return StereoscopicArcRotateCamera;
  99798. }(BABYLON.ArcRotateCamera));
  99799. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  99800. })(BABYLON || (BABYLON = {}));
  99801. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  99802. var BABYLON;
  99803. (function (BABYLON) {
  99804. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  99805. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99806. });
  99807. /**
  99808. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  99809. * @see http://doc.babylonjs.com/features/cameras
  99810. */
  99811. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  99812. __extends(StereoscopicFreeCamera, _super);
  99813. /**
  99814. * Creates a new StereoscopicFreeCamera
  99815. * @param name defines camera name
  99816. * @param position defines initial position
  99817. * @param interaxialDistance defines distance between each color axis
  99818. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99819. * @param scene defines the hosting scene
  99820. */
  99821. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  99822. var _this = _super.call(this, name, position, scene) || this;
  99823. _this.interaxialDistance = interaxialDistance;
  99824. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99825. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99826. return _this;
  99827. }
  99828. /**
  99829. * Gets camera class name
  99830. * @returns StereoscopicFreeCamera
  99831. */
  99832. StereoscopicFreeCamera.prototype.getClassName = function () {
  99833. return "StereoscopicFreeCamera";
  99834. };
  99835. return StereoscopicFreeCamera;
  99836. }(BABYLON.FreeCamera));
  99837. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  99838. })(BABYLON || (BABYLON = {}));
  99839. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  99840. var BABYLON;
  99841. (function (BABYLON) {
  99842. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  99843. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99844. });
  99845. /**
  99846. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  99847. * @see http://doc.babylonjs.com/features/cameras
  99848. */
  99849. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  99850. __extends(StereoscopicGamepadCamera, _super);
  99851. /**
  99852. * Creates a new StereoscopicGamepadCamera
  99853. * @param name defines camera name
  99854. * @param position defines initial position
  99855. * @param interaxialDistance defines distance between each color axis
  99856. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99857. * @param scene defines the hosting scene
  99858. */
  99859. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  99860. var _this = _super.call(this, name, position, scene) || this;
  99861. _this.interaxialDistance = interaxialDistance;
  99862. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99863. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99864. return _this;
  99865. }
  99866. /**
  99867. * Gets camera class name
  99868. * @returns StereoscopicGamepadCamera
  99869. */
  99870. StereoscopicGamepadCamera.prototype.getClassName = function () {
  99871. return "StereoscopicGamepadCamera";
  99872. };
  99873. return StereoscopicGamepadCamera;
  99874. }(BABYLON.GamepadCamera));
  99875. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  99876. })(BABYLON || (BABYLON = {}));
  99877. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  99878. var BABYLON;
  99879. (function (BABYLON) {
  99880. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  99881. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99882. });
  99883. /**
  99884. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  99885. * @see http://doc.babylonjs.com/features/cameras
  99886. */
  99887. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  99888. __extends(StereoscopicUniversalCamera, _super);
  99889. /**
  99890. * Creates a new StereoscopicUniversalCamera
  99891. * @param name defines camera name
  99892. * @param position defines initial position
  99893. * @param interaxialDistance defines distance between each color axis
  99894. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99895. * @param scene defines the hosting scene
  99896. */
  99897. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  99898. var _this = _super.call(this, name, position, scene) || this;
  99899. _this.interaxialDistance = interaxialDistance;
  99900. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99901. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99902. return _this;
  99903. }
  99904. /**
  99905. * Gets camera class name
  99906. * @returns StereoscopicUniversalCamera
  99907. */
  99908. StereoscopicUniversalCamera.prototype.getClassName = function () {
  99909. return "StereoscopicUniversalCamera";
  99910. };
  99911. return StereoscopicUniversalCamera;
  99912. }(BABYLON.UniversalCamera));
  99913. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  99914. })(BABYLON || (BABYLON = {}));
  99915. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  99916. var BABYLON;
  99917. (function (BABYLON) {
  99918. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  99919. __extends(VRDistortionCorrectionPostProcess, _super);
  99920. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  99921. var _this = _super.call(this, name, "vrDistortionCorrection", [
  99922. 'LensCenter',
  99923. 'Scale',
  99924. 'ScaleIn',
  99925. 'HmdWarpParam'
  99926. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  99927. _this._isRightEye = isRightEye;
  99928. _this._distortionFactors = vrMetrics.distortionK;
  99929. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  99930. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  99931. _this.adaptScaleToCurrentViewport = true;
  99932. _this.onSizeChangedObservable.add(function () {
  99933. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  99934. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  99935. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  99936. });
  99937. _this.onApplyObservable.add(function (effect) {
  99938. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  99939. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  99940. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  99941. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  99942. });
  99943. return _this;
  99944. }
  99945. return VRDistortionCorrectionPostProcess;
  99946. }(BABYLON.PostProcess));
  99947. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  99948. })(BABYLON || (BABYLON = {}));
  99949. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  99950. var BABYLON;
  99951. (function (BABYLON) {
  99952. /**
  99953. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  99954. * Screen rotation is taken into account.
  99955. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  99956. */
  99957. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  99958. /**
  99959. * Instantiates a new input
  99960. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  99961. */
  99962. function FreeCameraDeviceOrientationInput() {
  99963. var _this = this;
  99964. this._screenOrientationAngle = 0;
  99965. this._screenQuaternion = new BABYLON.Quaternion();
  99966. this._alpha = 0;
  99967. this._beta = 0;
  99968. this._gamma = 0;
  99969. this._orientationChanged = function () {
  99970. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  99971. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  99972. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  99973. };
  99974. this._deviceOrientation = function (evt) {
  99975. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  99976. _this._beta = evt.beta !== null ? evt.beta : 0;
  99977. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  99978. };
  99979. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  99980. this._orientationChanged();
  99981. }
  99982. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  99983. /**
  99984. * Define the camera controlled by the input.
  99985. */
  99986. get: function () {
  99987. return this._camera;
  99988. },
  99989. set: function (camera) {
  99990. this._camera = camera;
  99991. if (this._camera != null && !this._camera.rotationQuaternion) {
  99992. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  99993. }
  99994. },
  99995. enumerable: true,
  99996. configurable: true
  99997. });
  99998. /**
  99999. * Attach the input controls to a specific dom element to get the input from.
  100000. * @param element Defines the element the controls should be listened from
  100001. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  100002. */
  100003. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  100004. window.addEventListener("orientationchange", this._orientationChanged);
  100005. window.addEventListener("deviceorientation", this._deviceOrientation);
  100006. //In certain cases, the attach control is called AFTER orientation was changed,
  100007. //So this is needed.
  100008. this._orientationChanged();
  100009. };
  100010. /**
  100011. * Detach the current controls from the specified dom element.
  100012. * @param element Defines the element to stop listening the inputs from
  100013. */
  100014. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  100015. window.removeEventListener("orientationchange", this._orientationChanged);
  100016. window.removeEventListener("deviceorientation", this._deviceOrientation);
  100017. };
  100018. /**
  100019. * Update the current camera state depending on the inputs that have been used this frame.
  100020. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  100021. */
  100022. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  100023. //if no device orientation provided, don't update the rotation.
  100024. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  100025. if (!this._alpha)
  100026. return;
  100027. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  100028. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  100029. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  100030. //Mirror on XY Plane
  100031. this._camera.rotationQuaternion.z *= -1;
  100032. this._camera.rotationQuaternion.w *= -1;
  100033. };
  100034. /**
  100035. * Gets the class name of the current intput.
  100036. * @returns the class name
  100037. */
  100038. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  100039. return "FreeCameraDeviceOrientationInput";
  100040. };
  100041. /**
  100042. * Get the friendly name associated with the input class.
  100043. * @returns the input friendly name
  100044. */
  100045. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  100046. return "deviceOrientation";
  100047. };
  100048. return FreeCameraDeviceOrientationInput;
  100049. }());
  100050. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  100051. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  100052. })(BABYLON || (BABYLON = {}));
  100053. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  100054. var BABYLON;
  100055. (function (BABYLON) {
  100056. /**
  100057. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  100058. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  100059. */
  100060. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  100061. /**
  100062. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  100063. */
  100064. function ArcRotateCameraVRDeviceOrientationInput() {
  100065. /**
  100066. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  100067. */
  100068. this.alphaCorrection = 1;
  100069. /**
  100070. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  100071. */
  100072. this.betaCorrection = 1;
  100073. /**
  100074. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  100075. */
  100076. this.gammaCorrection = 1;
  100077. this._alpha = 0;
  100078. this._gamma = 0;
  100079. this._dirty = false;
  100080. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  100081. }
  100082. /**
  100083. * Attach the input controls to a specific dom element to get the input from.
  100084. * @param element Defines the element the controls should be listened from
  100085. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  100086. */
  100087. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  100088. this.camera.attachControl(element, noPreventDefault);
  100089. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  100090. };
  100091. /** @hidden */
  100092. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  100093. if (evt.alpha !== null) {
  100094. this._alpha = +evt.alpha | 0;
  100095. }
  100096. if (evt.gamma !== null) {
  100097. this._gamma = +evt.gamma | 0;
  100098. }
  100099. this._dirty = true;
  100100. };
  100101. /**
  100102. * Update the current camera state depending on the inputs that have been used this frame.
  100103. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  100104. */
  100105. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  100106. if (this._dirty) {
  100107. this._dirty = false;
  100108. if (this._gamma < 0) {
  100109. this._gamma = 180 + this._gamma;
  100110. }
  100111. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  100112. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  100113. }
  100114. };
  100115. /**
  100116. * Detach the current controls from the specified dom element.
  100117. * @param element Defines the element to stop listening the inputs from
  100118. */
  100119. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  100120. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  100121. };
  100122. /**
  100123. * Gets the class name of the current intput.
  100124. * @returns the class name
  100125. */
  100126. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  100127. return "ArcRotateCameraVRDeviceOrientationInput";
  100128. };
  100129. /**
  100130. * Get the friendly name associated with the input class.
  100131. * @returns the input friendly name
  100132. */
  100133. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  100134. return "VRDeviceOrientation";
  100135. };
  100136. return ArcRotateCameraVRDeviceOrientationInput;
  100137. }());
  100138. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  100139. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  100140. })(BABYLON || (BABYLON = {}));
  100141. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  100142. var BABYLON;
  100143. (function (BABYLON) {
  100144. /**
  100145. * This represents all the required metrics to create a VR camera.
  100146. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  100147. */
  100148. var VRCameraMetrics = /** @class */ (function () {
  100149. function VRCameraMetrics() {
  100150. /**
  100151. * Define if the current vr camera should compensate the distortion of the lense or not.
  100152. */
  100153. this.compensateDistortion = true;
  100154. }
  100155. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  100156. /**
  100157. * Gets the rendering aspect ratio based on the provided resolutions.
  100158. */
  100159. get: function () {
  100160. return this.hResolution / (2 * this.vResolution);
  100161. },
  100162. enumerable: true,
  100163. configurable: true
  100164. });
  100165. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  100166. /**
  100167. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  100168. */
  100169. get: function () {
  100170. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  100171. },
  100172. enumerable: true,
  100173. configurable: true
  100174. });
  100175. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  100176. /**
  100177. * @hidden
  100178. */
  100179. get: function () {
  100180. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  100181. var h = (4 * meters) / this.hScreenSize;
  100182. return BABYLON.Matrix.Translation(h, 0, 0);
  100183. },
  100184. enumerable: true,
  100185. configurable: true
  100186. });
  100187. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  100188. /**
  100189. * @hidden
  100190. */
  100191. get: function () {
  100192. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  100193. var h = (4 * meters) / this.hScreenSize;
  100194. return BABYLON.Matrix.Translation(-h, 0, 0);
  100195. },
  100196. enumerable: true,
  100197. configurable: true
  100198. });
  100199. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  100200. /**
  100201. * @hidden
  100202. */
  100203. get: function () {
  100204. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  100205. },
  100206. enumerable: true,
  100207. configurable: true
  100208. });
  100209. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  100210. /**
  100211. * @hidden
  100212. */
  100213. get: function () {
  100214. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  100215. },
  100216. enumerable: true,
  100217. configurable: true
  100218. });
  100219. /**
  100220. * Get the default VRMetrics based on the most generic setup.
  100221. * @returns the default vr metrics
  100222. */
  100223. VRCameraMetrics.GetDefault = function () {
  100224. var result = new VRCameraMetrics();
  100225. result.hResolution = 1280;
  100226. result.vResolution = 800;
  100227. result.hScreenSize = 0.149759993;
  100228. result.vScreenSize = 0.0935999975;
  100229. result.vScreenCenter = 0.0467999987;
  100230. result.eyeToScreenDistance = 0.0410000011;
  100231. result.lensSeparationDistance = 0.0635000020;
  100232. result.interpupillaryDistance = 0.0640000030;
  100233. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  100234. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  100235. result.postProcessScaleFactor = 1.714605507808412;
  100236. result.lensCenterOffset = 0.151976421;
  100237. return result;
  100238. };
  100239. return VRCameraMetrics;
  100240. }());
  100241. BABYLON.VRCameraMetrics = VRCameraMetrics;
  100242. })(BABYLON || (BABYLON = {}));
  100243. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  100244. var BABYLON;
  100245. (function (BABYLON) {
  100246. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  100247. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  100248. });
  100249. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  100250. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  100251. });
  100252. /**
  100253. * This represents a WebVR camera.
  100254. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  100255. * @example http://doc.babylonjs.com/how_to/webvr_camera
  100256. */
  100257. var WebVRFreeCamera = /** @class */ (function (_super) {
  100258. __extends(WebVRFreeCamera, _super);
  100259. /**
  100260. * Instantiates a WebVRFreeCamera.
  100261. * @param name The name of the WebVRFreeCamera
  100262. * @param position The starting anchor position for the camera
  100263. * @param scene The scene the camera belongs to
  100264. * @param webVROptions a set of customizable options for the webVRCamera
  100265. */
  100266. function WebVRFreeCamera(name, position, scene, webVROptions) {
  100267. if (webVROptions === void 0) { webVROptions = {}; }
  100268. var _this = _super.call(this, name, position, scene) || this;
  100269. _this.webVROptions = webVROptions;
  100270. /**
  100271. * @hidden
  100272. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  100273. */
  100274. _this._vrDevice = null;
  100275. /**
  100276. * The rawPose of the vrDevice.
  100277. */
  100278. _this.rawPose = null;
  100279. _this._specsVersion = "1.1";
  100280. _this._attached = false;
  100281. _this._descendants = [];
  100282. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  100283. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  100284. /** @hidden */
  100285. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  100286. _this._standingMatrix = null;
  100287. /**
  100288. * Represents device position in babylon space.
  100289. */
  100290. _this.devicePosition = BABYLON.Vector3.Zero();
  100291. /**
  100292. * Represents device rotation in babylon space.
  100293. */
  100294. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  100295. /**
  100296. * The scale of the device to be used when translating from device space to babylon space.
  100297. */
  100298. _this.deviceScaleFactor = 1;
  100299. _this._deviceToWorld = BABYLON.Matrix.Identity();
  100300. _this._worldToDevice = BABYLON.Matrix.Identity();
  100301. /**
  100302. * References to the webVR controllers for the vrDevice.
  100303. */
  100304. _this.controllers = [];
  100305. /**
  100306. * Emits an event when a controller is attached.
  100307. */
  100308. _this.onControllersAttachedObservable = new BABYLON.Observable();
  100309. /**
  100310. * Emits an event when a controller's mesh has been loaded;
  100311. */
  100312. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  100313. /**
  100314. * Emits an event when the HMD's pose has been updated.
  100315. */
  100316. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  100317. _this._poseSet = false;
  100318. /**
  100319. * If the rig cameras be used as parent instead of this camera.
  100320. */
  100321. _this.rigParenting = true;
  100322. _this._defaultHeight = undefined;
  100323. _this._htmlElementAttached = null;
  100324. _this._detachIfAttached = function () {
  100325. var vrDisplay = _this.getEngine().getVRDevice();
  100326. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  100327. _this.detachControl(_this._htmlElementAttached);
  100328. }
  100329. };
  100330. _this._workingVector = BABYLON.Vector3.Zero();
  100331. _this._oneVector = BABYLON.Vector3.One();
  100332. _this._workingMatrix = BABYLON.Matrix.Identity();
  100333. _this._tmpMatrix = new BABYLON.Matrix();
  100334. _this._cache.position = BABYLON.Vector3.Zero();
  100335. if (webVROptions.defaultHeight) {
  100336. _this._defaultHeight = webVROptions.defaultHeight;
  100337. _this.position.y = _this._defaultHeight;
  100338. }
  100339. _this.minZ = 0.1;
  100340. //legacy support - the compensation boolean was removed.
  100341. if (arguments.length === 5) {
  100342. _this.webVROptions = arguments[4];
  100343. }
  100344. // default webVR options
  100345. if (_this.webVROptions.trackPosition == undefined) {
  100346. _this.webVROptions.trackPosition = true;
  100347. }
  100348. if (_this.webVROptions.controllerMeshes == undefined) {
  100349. _this.webVROptions.controllerMeshes = true;
  100350. }
  100351. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  100352. _this.webVROptions.defaultLightingOnControllers = true;
  100353. }
  100354. _this.rotationQuaternion = new BABYLON.Quaternion();
  100355. if (_this.webVROptions && _this.webVROptions.positionScale) {
  100356. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  100357. }
  100358. //enable VR
  100359. var engine = _this.getEngine();
  100360. _this._onVREnabled = function (success) { if (success) {
  100361. _this.initControllers();
  100362. } };
  100363. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  100364. engine.initWebVR().add(function (event) {
  100365. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  100366. return;
  100367. }
  100368. _this._vrDevice = event.vrDisplay;
  100369. //reset the rig parameters.
  100370. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  100371. if (_this._attached) {
  100372. _this.getEngine().enableVR();
  100373. }
  100374. });
  100375. if (typeof (VRFrameData) !== "undefined")
  100376. _this._frameData = new VRFrameData();
  100377. /**
  100378. * The idea behind the following lines:
  100379. * objects that have the camera as parent should actually have the rig cameras as a parent.
  100380. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  100381. * the second will not show it correctly.
  100382. *
  100383. * To solve this - each object that has the camera as parent will be added to a protected array.
  100384. * When the rig camera renders, it will take this array and set all of those to be its children.
  100385. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  100386. * Amazing!
  100387. */
  100388. scene.onBeforeCameraRenderObservable.add(function (camera) {
  100389. if (camera.parent === _this && _this.rigParenting) {
  100390. _this._descendants = _this.getDescendants(true, function (n) {
  100391. // don't take the cameras or the controllers!
  100392. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  100393. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  100394. return !isController && !isRigCamera;
  100395. });
  100396. _this._descendants.forEach(function (node) {
  100397. node.parent = camera;
  100398. });
  100399. }
  100400. });
  100401. scene.onAfterCameraRenderObservable.add(function (camera) {
  100402. if (camera.parent === _this && _this.rigParenting) {
  100403. _this._descendants.forEach(function (node) {
  100404. node.parent = _this;
  100405. });
  100406. }
  100407. });
  100408. return _this;
  100409. }
  100410. /**
  100411. * Gets the device distance from the ground in meters.
  100412. * @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.
  100413. */
  100414. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  100415. if (this._standingMatrix) {
  100416. // Add standing matrix offset to get real offset from ground in room
  100417. this._standingMatrix.getTranslationToRef(this._workingVector);
  100418. return this._deviceRoomPosition.y + this._workingVector.y;
  100419. }
  100420. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  100421. return this._defaultHeight || 0;
  100422. };
  100423. /**
  100424. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  100425. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  100426. */
  100427. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  100428. var _this = this;
  100429. if (callback === void 0) { callback = function (bool) { }; }
  100430. // Use standing matrix if available
  100431. this.getEngine().initWebVRAsync().then(function (result) {
  100432. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  100433. callback(false);
  100434. }
  100435. else {
  100436. _this._standingMatrix = new BABYLON.Matrix();
  100437. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  100438. if (!_this.getScene().useRightHandedSystem) {
  100439. [2, 6, 8, 9, 14].forEach(function (num) {
  100440. if (_this._standingMatrix) {
  100441. _this._standingMatrix.m[num] *= -1;
  100442. }
  100443. });
  100444. }
  100445. callback(true);
  100446. }
  100447. });
  100448. };
  100449. /**
  100450. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  100451. * @returns A promise with a boolean set to if the standing matrix is supported.
  100452. */
  100453. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  100454. var _this = this;
  100455. return new Promise(function (res, rej) {
  100456. _this.useStandingMatrix(function (supported) {
  100457. res(supported);
  100458. });
  100459. });
  100460. };
  100461. /**
  100462. * Disposes the camera
  100463. */
  100464. WebVRFreeCamera.prototype.dispose = function () {
  100465. this._detachIfAttached();
  100466. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  100467. if (this._updateCacheWhenTrackingDisabledObserver) {
  100468. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  100469. }
  100470. _super.prototype.dispose.call(this);
  100471. };
  100472. /**
  100473. * Gets a vrController by name.
  100474. * @param name The name of the controller to retreive
  100475. * @returns the controller matching the name specified or null if not found
  100476. */
  100477. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  100478. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  100479. var gp = _a[_i];
  100480. if (gp.hand === name) {
  100481. return gp;
  100482. }
  100483. }
  100484. return null;
  100485. };
  100486. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  100487. /**
  100488. * The controller corrisponding to the users left hand.
  100489. */
  100490. get: function () {
  100491. if (!this._leftController) {
  100492. this._leftController = this.getControllerByName("left");
  100493. }
  100494. return this._leftController;
  100495. },
  100496. enumerable: true,
  100497. configurable: true
  100498. });
  100499. ;
  100500. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  100501. /**
  100502. * The controller corrisponding to the users right hand.
  100503. */
  100504. get: function () {
  100505. if (!this._rightController) {
  100506. this._rightController = this.getControllerByName("right");
  100507. }
  100508. return this._rightController;
  100509. },
  100510. enumerable: true,
  100511. configurable: true
  100512. });
  100513. ;
  100514. /**
  100515. * Casts a ray forward from the vrCamera's gaze.
  100516. * @param length Length of the ray (default: 100)
  100517. * @returns the ray corrisponding to the gaze
  100518. */
  100519. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  100520. if (length === void 0) { length = 100; }
  100521. if (this.leftCamera) {
  100522. // Use left eye to avoid computation to compute center on every call
  100523. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  100524. }
  100525. else {
  100526. return _super.prototype.getForwardRay.call(this, length);
  100527. }
  100528. };
  100529. /**
  100530. * @hidden
  100531. * Updates the camera based on device's frame data
  100532. */
  100533. WebVRFreeCamera.prototype._checkInputs = function () {
  100534. if (this._vrDevice && this._vrDevice.isPresenting) {
  100535. this._vrDevice.getFrameData(this._frameData);
  100536. this.updateFromDevice(this._frameData.pose);
  100537. }
  100538. _super.prototype._checkInputs.call(this);
  100539. };
  100540. /**
  100541. * Updates the poseControlled values based on the input device pose.
  100542. * @param poseData Pose coming from the device
  100543. */
  100544. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  100545. if (poseData && poseData.orientation) {
  100546. this.rawPose = poseData;
  100547. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  100548. if (this.getScene().useRightHandedSystem) {
  100549. this._deviceRoomRotationQuaternion.z *= -1;
  100550. this._deviceRoomRotationQuaternion.w *= -1;
  100551. }
  100552. if (this.webVROptions.trackPosition && this.rawPose.position) {
  100553. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  100554. if (this.getScene().useRightHandedSystem) {
  100555. this._deviceRoomPosition.z *= -1;
  100556. }
  100557. }
  100558. this._poseSet = true;
  100559. }
  100560. };
  100561. /**
  100562. * WebVR's attach control will start broadcasting frames to the device.
  100563. * Note that in certain browsers (chrome for example) this function must be called
  100564. * within a user-interaction callback. Example:
  100565. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  100566. *
  100567. * @param element html element to attach the vrDevice to
  100568. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  100569. */
  100570. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  100571. _super.prototype.attachControl.call(this, element, noPreventDefault);
  100572. this._attached = true;
  100573. this._htmlElementAttached = element;
  100574. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  100575. if (this._vrDevice) {
  100576. this.getEngine().enableVR();
  100577. }
  100578. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  100579. };
  100580. /**
  100581. * Detaches the camera from the html element and disables VR
  100582. *
  100583. * @param element html element to detach from
  100584. */
  100585. WebVRFreeCamera.prototype.detachControl = function (element) {
  100586. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  100587. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  100588. _super.prototype.detachControl.call(this, element);
  100589. this._attached = false;
  100590. this.getEngine().disableVR();
  100591. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  100592. };
  100593. /**
  100594. * @returns the name of this class
  100595. */
  100596. WebVRFreeCamera.prototype.getClassName = function () {
  100597. return "WebVRFreeCamera";
  100598. };
  100599. /**
  100600. * Calls resetPose on the vrDisplay
  100601. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  100602. */
  100603. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  100604. //uses the vrDisplay's "resetPose()".
  100605. //pitch and roll won't be affected.
  100606. this._vrDevice.resetPose();
  100607. };
  100608. /**
  100609. * @hidden
  100610. * Updates the rig cameras (left and right eye)
  100611. */
  100612. WebVRFreeCamera.prototype._updateRigCameras = function () {
  100613. var camLeft = this._rigCameras[0];
  100614. var camRight = this._rigCameras[1];
  100615. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  100616. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  100617. camLeft.position.copyFrom(this._deviceRoomPosition);
  100618. camRight.position.copyFrom(this._deviceRoomPosition);
  100619. };
  100620. // Remove translation from 6dof headset if trackposition is set to false
  100621. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  100622. if (isViewMatrix === void 0) { isViewMatrix = false; }
  100623. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  100624. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  100625. if (!isViewMatrix) {
  100626. this._tmpMatrix.invert();
  100627. }
  100628. this._tmpMatrix.multiplyToRef(matrix, matrix);
  100629. }
  100630. };
  100631. /**
  100632. * @hidden
  100633. * Updates the cached values of the camera
  100634. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  100635. */
  100636. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  100637. var _this = this;
  100638. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  100639. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  100640. if (!this.updateCacheCalled) {
  100641. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  100642. this.updateCacheCalled = true;
  100643. this.update();
  100644. }
  100645. // Set working vector to the device position in room space rotated by the new rotation
  100646. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  100647. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  100648. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  100649. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  100650. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  100651. // Add translation from anchor position
  100652. this._deviceToWorld.getTranslationToRef(this._workingVector);
  100653. this._workingVector.addInPlace(this.position);
  100654. this._workingVector.subtractInPlace(this._cache.position);
  100655. this._deviceToWorld.setTranslation(this._workingVector);
  100656. // Set an inverted matrix to be used when updating the camera
  100657. this._deviceToWorld.invertToRef(this._worldToDevice);
  100658. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  100659. this.controllers.forEach(function (controller) {
  100660. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  100661. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  100662. controller.update();
  100663. });
  100664. }
  100665. if (!ignoreParentClass) {
  100666. _super.prototype._updateCache.call(this);
  100667. }
  100668. this.updateCacheCalled = false;
  100669. };
  100670. /**
  100671. * @hidden
  100672. * Get current device position in babylon world
  100673. */
  100674. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  100675. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  100676. };
  100677. /**
  100678. * Updates the current device position and rotation in the babylon world
  100679. */
  100680. WebVRFreeCamera.prototype.update = function () {
  100681. this._computeDevicePosition();
  100682. // Get current device rotation in babylon world
  100683. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  100684. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  100685. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  100686. if (this._poseSet) {
  100687. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  100688. }
  100689. _super.prototype.update.call(this);
  100690. };
  100691. /**
  100692. * @hidden
  100693. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  100694. * @returns an identity matrix
  100695. */
  100696. WebVRFreeCamera.prototype._getViewMatrix = function () {
  100697. return BABYLON.Matrix.Identity();
  100698. };
  100699. /**
  100700. * This function is called by the two RIG cameras.
  100701. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  100702. */
  100703. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  100704. var _this = this;
  100705. // Update the parent camera prior to using a child camera to avoid desynchronization
  100706. var parentCamera = this._cameraRigParams["parentCamera"];
  100707. parentCamera._updateCache();
  100708. //WebVR 1.1
  100709. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  100710. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  100711. if (!this.getScene().useRightHandedSystem) {
  100712. [2, 6, 8, 9, 14].forEach(function (num) {
  100713. _this._webvrViewMatrix.m[num] *= -1;
  100714. });
  100715. }
  100716. // update the camera rotation matrix
  100717. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  100718. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  100719. // Computing target and final matrix
  100720. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  100721. // should the view matrix be updated with scale and position offset?
  100722. if (parentCamera.deviceScaleFactor !== 1) {
  100723. this._webvrViewMatrix.invert();
  100724. // scale the position, if set
  100725. if (parentCamera.deviceScaleFactor) {
  100726. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  100727. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  100728. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  100729. }
  100730. this._webvrViewMatrix.invert();
  100731. }
  100732. // Remove translation from 6dof headset if trackposition is set to false
  100733. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  100734. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  100735. // Compute global position
  100736. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  100737. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  100738. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  100739. this._workingMatrix.getTranslationToRef(this._globalPosition);
  100740. this._markSyncedWithParent();
  100741. return this._webvrViewMatrix;
  100742. };
  100743. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  100744. var _this = this;
  100745. var parentCamera = this.parent;
  100746. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  100747. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  100748. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  100749. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  100750. //babylon compatible matrix
  100751. if (!this.getScene().useRightHandedSystem) {
  100752. [8, 9, 10, 11].forEach(function (num) {
  100753. _this._projectionMatrix.m[num] *= -1;
  100754. });
  100755. }
  100756. return this._projectionMatrix;
  100757. };
  100758. /**
  100759. * Initializes the controllers and their meshes
  100760. */
  100761. WebVRFreeCamera.prototype.initControllers = function () {
  100762. var _this = this;
  100763. this.controllers = [];
  100764. var manager = this.getScene().gamepadManager;
  100765. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  100766. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  100767. var webVrController = gamepad;
  100768. if (webVrController.defaultModel) {
  100769. webVrController.defaultModel.setEnabled(false);
  100770. }
  100771. if (webVrController.hand === "right") {
  100772. _this._rightController = null;
  100773. }
  100774. if (webVrController.hand === "left") {
  100775. _this._leftController = null;
  100776. }
  100777. var controllerIndex = _this.controllers.indexOf(webVrController);
  100778. if (controllerIndex !== -1) {
  100779. _this.controllers.splice(controllerIndex, 1);
  100780. }
  100781. }
  100782. });
  100783. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  100784. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  100785. var webVrController_1 = gamepad;
  100786. if (!_this.webVROptions.trackPosition) {
  100787. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  100788. // Cache must be updated before rendering controllers to avoid them being one frame behind
  100789. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  100790. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  100791. _this._updateCache();
  100792. });
  100793. }
  100794. }
  100795. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  100796. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  100797. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  100798. if (_this.webVROptions.controllerMeshes) {
  100799. if (webVrController_1.defaultModel) {
  100800. webVrController_1.defaultModel.setEnabled(true);
  100801. }
  100802. else {
  100803. // Load the meshes
  100804. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  100805. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  100806. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  100807. if (_this.webVROptions.defaultLightingOnControllers) {
  100808. if (!_this._lightOnControllers) {
  100809. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  100810. }
  100811. var activateLightOnSubMeshes_1 = function (mesh, light) {
  100812. var children = mesh.getChildren();
  100813. if (children && children.length !== 0) {
  100814. children.forEach(function (mesh) {
  100815. light.includedOnlyMeshes.push(mesh);
  100816. activateLightOnSubMeshes_1(mesh, light);
  100817. });
  100818. }
  100819. };
  100820. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  100821. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  100822. }
  100823. });
  100824. }
  100825. }
  100826. webVrController_1.attachToPoseControlledCamera(_this);
  100827. // since this is async - sanity check. Is the controller already stored?
  100828. if (_this.controllers.indexOf(webVrController_1) === -1) {
  100829. //add to the controllers array
  100830. _this.controllers.push(webVrController_1);
  100831. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  100832. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  100833. // So we're overriding setting left & right manually to be sure
  100834. var firstViveWandDetected = false;
  100835. for (var i = 0; i < _this.controllers.length; i++) {
  100836. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  100837. if (!firstViveWandDetected) {
  100838. firstViveWandDetected = true;
  100839. _this.controllers[i].hand = "left";
  100840. }
  100841. else {
  100842. _this.controllers[i].hand = "right";
  100843. }
  100844. }
  100845. }
  100846. //did we find enough controllers? Great! let the developer know.
  100847. if (_this.controllers.length >= 2) {
  100848. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  100849. }
  100850. }
  100851. }
  100852. });
  100853. };
  100854. return WebVRFreeCamera;
  100855. }(BABYLON.FreeCamera));
  100856. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  100857. })(BABYLON || (BABYLON = {}));
  100858. //# sourceMappingURL=babylon.webVRCamera.js.map
  100859. var BABYLON;
  100860. (function (BABYLON) {
  100861. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  100862. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  100863. });
  100864. // We're mainly based on the logic defined into the FreeCamera code
  100865. /**
  100866. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  100867. * being tilted forward or back and left or right.
  100868. */
  100869. var DeviceOrientationCamera = /** @class */ (function (_super) {
  100870. __extends(DeviceOrientationCamera, _super);
  100871. /**
  100872. * Creates a new device orientation camera
  100873. * @param name The name of the camera
  100874. * @param position The start position camera
  100875. * @param scene The scene the camera belongs to
  100876. */
  100877. function DeviceOrientationCamera(name, position, scene) {
  100878. var _this = _super.call(this, name, position, scene) || this;
  100879. _this._quaternionCache = new BABYLON.Quaternion();
  100880. _this.inputs.addDeviceOrientation();
  100881. return _this;
  100882. }
  100883. /**
  100884. * Gets the current instance class name ("DeviceOrientationCamera").
  100885. * This helps avoiding instanceof at run time.
  100886. * @returns the class name
  100887. */
  100888. DeviceOrientationCamera.prototype.getClassName = function () {
  100889. return "DeviceOrientationCamera";
  100890. };
  100891. /**
  100892. * @hidden
  100893. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  100894. */
  100895. DeviceOrientationCamera.prototype._checkInputs = function () {
  100896. _super.prototype._checkInputs.call(this);
  100897. this._quaternionCache.copyFrom(this.rotationQuaternion);
  100898. if (this._initialQuaternion) {
  100899. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  100900. }
  100901. };
  100902. /**
  100903. * Reset the camera to its default orientation on the specified axis only.
  100904. * @param axis The axis to reset
  100905. */
  100906. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  100907. var _this = this;
  100908. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  100909. //can only work if this camera has a rotation quaternion already.
  100910. if (!this.rotationQuaternion)
  100911. return;
  100912. if (!this._initialQuaternion) {
  100913. this._initialQuaternion = new BABYLON.Quaternion();
  100914. }
  100915. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  100916. ['x', 'y', 'z'].forEach(function (axisName) {
  100917. if (!axis[axisName]) {
  100918. _this._initialQuaternion[axisName] = 0;
  100919. }
  100920. else {
  100921. _this._initialQuaternion[axisName] *= -1;
  100922. }
  100923. });
  100924. this._initialQuaternion.normalize();
  100925. //force rotation update
  100926. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  100927. };
  100928. return DeviceOrientationCamera;
  100929. }(BABYLON.FreeCamera));
  100930. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  100931. })(BABYLON || (BABYLON = {}));
  100932. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  100933. var BABYLON;
  100934. (function (BABYLON) {
  100935. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  100936. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  100937. });
  100938. /**
  100939. * Camera used to simulate VR rendering (based on FreeCamera)
  100940. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  100941. */
  100942. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  100943. __extends(VRDeviceOrientationFreeCamera, _super);
  100944. /**
  100945. * Creates a new VRDeviceOrientationFreeCamera
  100946. * @param name defines camera name
  100947. * @param position defines the start position of the camera
  100948. * @param scene defines the scene the camera belongs to
  100949. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  100950. * @param vrCameraMetrics defines the vr metrics associated to the camera
  100951. */
  100952. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  100953. if (compensateDistortion === void 0) { compensateDistortion = true; }
  100954. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  100955. var _this = _super.call(this, name, position, scene) || this;
  100956. vrCameraMetrics.compensateDistortion = compensateDistortion;
  100957. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  100958. return _this;
  100959. }
  100960. /**
  100961. * Gets camera class name
  100962. * @returns VRDeviceOrientationFreeCamera
  100963. */
  100964. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  100965. return "VRDeviceOrientationFreeCamera";
  100966. };
  100967. return VRDeviceOrientationFreeCamera;
  100968. }(BABYLON.DeviceOrientationCamera));
  100969. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  100970. })(BABYLON || (BABYLON = {}));
  100971. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  100972. var BABYLON;
  100973. (function (BABYLON) {
  100974. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  100975. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  100976. });
  100977. /**
  100978. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  100979. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  100980. */
  100981. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  100982. __extends(VRDeviceOrientationArcRotateCamera, _super);
  100983. /**
  100984. * Creates a new VRDeviceOrientationArcRotateCamera
  100985. * @param name defines camera name
  100986. * @param alpha defines the camera rotation along the logitudinal axis
  100987. * @param beta defines the camera rotation along the latitudinal axis
  100988. * @param radius defines the camera distance from its target
  100989. * @param target defines the camera target
  100990. * @param scene defines the scene the camera belongs to
  100991. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  100992. * @param vrCameraMetrics defines the vr metrics associated to the camera
  100993. */
  100994. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  100995. if (compensateDistortion === void 0) { compensateDistortion = true; }
  100996. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  100997. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  100998. vrCameraMetrics.compensateDistortion = compensateDistortion;
  100999. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  101000. _this.inputs.addVRDeviceOrientation();
  101001. return _this;
  101002. }
  101003. /**
  101004. * Gets camera class name
  101005. * @returns VRDeviceOrientationArcRotateCamera
  101006. */
  101007. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  101008. return "VRDeviceOrientationArcRotateCamera";
  101009. };
  101010. return VRDeviceOrientationArcRotateCamera;
  101011. }(BABYLON.ArcRotateCamera));
  101012. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  101013. })(BABYLON || (BABYLON = {}));
  101014. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  101015. var BABYLON;
  101016. (function (BABYLON) {
  101017. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  101018. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  101019. });
  101020. /**
  101021. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  101022. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  101023. */
  101024. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  101025. __extends(VRDeviceOrientationGamepadCamera, _super);
  101026. /**
  101027. * Creates a new VRDeviceOrientationGamepadCamera
  101028. * @param name defines camera name
  101029. * @param position defines the start position of the camera
  101030. * @param scene defines the scene the camera belongs to
  101031. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  101032. * @param vrCameraMetrics defines the vr metrics associated to the camera
  101033. */
  101034. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  101035. if (compensateDistortion === void 0) { compensateDistortion = true; }
  101036. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  101037. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  101038. _this.inputs.addGamepad();
  101039. return _this;
  101040. }
  101041. /**
  101042. * Gets camera class name
  101043. * @returns VRDeviceOrientationGamepadCamera
  101044. */
  101045. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  101046. return "VRDeviceOrientationGamepadCamera";
  101047. };
  101048. return VRDeviceOrientationGamepadCamera;
  101049. }(BABYLON.VRDeviceOrientationFreeCamera));
  101050. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  101051. })(BABYLON || (BABYLON = {}));
  101052. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  101053. var BABYLON;
  101054. (function (BABYLON) {
  101055. var VRExperienceHelperGazer = /** @class */ (function () {
  101056. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  101057. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  101058. this.scene = scene;
  101059. /** @hidden */
  101060. this._pointerDownOnMeshAsked = false;
  101061. /** @hidden */
  101062. this._isActionableMesh = false;
  101063. /** @hidden */
  101064. this._teleportationRequestInitiated = false;
  101065. /** @hidden */
  101066. this._teleportationBackRequestInitiated = false;
  101067. /** @hidden */
  101068. this._rotationRightAsked = false;
  101069. /** @hidden */
  101070. this._rotationLeftAsked = false;
  101071. /** @hidden */
  101072. this._dpadPressed = true;
  101073. /** @hidden */
  101074. this._activePointer = false;
  101075. this._id = VRExperienceHelperGazer._idCounter++;
  101076. // Gaze tracker
  101077. if (!gazeTrackerToClone) {
  101078. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  101079. this._gazeTracker.bakeCurrentTransformIntoVertices();
  101080. this._gazeTracker.isPickable = false;
  101081. this._gazeTracker.isVisible = false;
  101082. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  101083. targetMat.specularColor = BABYLON.Color3.Black();
  101084. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  101085. targetMat.backFaceCulling = false;
  101086. this._gazeTracker.material = targetMat;
  101087. }
  101088. else {
  101089. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  101090. }
  101091. }
  101092. /** @hidden */
  101093. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  101094. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  101095. };
  101096. /** @hidden */
  101097. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  101098. this._pointerDownOnMeshAsked = true;
  101099. if (this._currentHit) {
  101100. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  101101. }
  101102. };
  101103. /** @hidden */
  101104. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  101105. if (this._currentHit) {
  101106. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  101107. }
  101108. this._pointerDownOnMeshAsked = false;
  101109. };
  101110. /** @hidden */
  101111. VRExperienceHelperGazer.prototype._activatePointer = function () {
  101112. this._activePointer = true;
  101113. };
  101114. /** @hidden */
  101115. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  101116. this._activePointer = false;
  101117. };
  101118. /** @hidden */
  101119. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  101120. if (distance === void 0) { distance = 100; }
  101121. };
  101122. VRExperienceHelperGazer.prototype.dispose = function () {
  101123. this._interactionsEnabled = false;
  101124. this._teleportationEnabled = false;
  101125. if (this._gazeTracker) {
  101126. this._gazeTracker.dispose();
  101127. }
  101128. };
  101129. VRExperienceHelperGazer._idCounter = 0;
  101130. return VRExperienceHelperGazer;
  101131. }());
  101132. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  101133. __extends(VRExperienceHelperControllerGazer, _super);
  101134. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  101135. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  101136. _this.webVRController = webVRController;
  101137. // Laser pointer
  101138. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  101139. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  101140. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  101141. laserPointerMaterial.alpha = 0.6;
  101142. _this._laserPointer.material = laserPointerMaterial;
  101143. _this._laserPointer.rotation.x = Math.PI / 2;
  101144. _this._laserPointer.position.z = -0.5;
  101145. _this._laserPointer.isVisible = false;
  101146. _this._laserPointer.isPickable = false;
  101147. if (!webVRController.mesh) {
  101148. // Create an empty mesh that is used prior to loading the high quality model
  101149. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  101150. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  101151. preloadPointerPose.rotation.x = -0.7;
  101152. preloadMesh.addChild(preloadPointerPose);
  101153. webVRController.attachToMesh(preloadMesh);
  101154. }
  101155. _this._setLaserPointerParent(webVRController.mesh);
  101156. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  101157. _this._setLaserPointerParent(mesh);
  101158. });
  101159. return _this;
  101160. }
  101161. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  101162. return this.webVRController.getForwardRay(length);
  101163. };
  101164. /** @hidden */
  101165. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  101166. _super.prototype._activatePointer.call(this);
  101167. this._laserPointer.isVisible = true;
  101168. };
  101169. /** @hidden */
  101170. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  101171. _super.prototype._deactivatePointer.call(this);
  101172. this._laserPointer.isVisible = false;
  101173. };
  101174. /** @hidden */
  101175. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  101176. this._laserPointer.material.emissiveColor = color;
  101177. };
  101178. /** @hidden */
  101179. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  101180. var makeNotPick = function (root) {
  101181. root.isPickable = false;
  101182. root.getChildMeshes().forEach(function (c) {
  101183. makeNotPick(c);
  101184. });
  101185. };
  101186. makeNotPick(mesh);
  101187. var childMeshes = mesh.getChildMeshes();
  101188. this.webVRController._pointingPoseNode = null;
  101189. for (var i = 0; i < childMeshes.length; i++) {
  101190. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  101191. mesh = childMeshes[i];
  101192. this.webVRController._pointingPoseNode = mesh;
  101193. break;
  101194. }
  101195. }
  101196. this._laserPointer.parent = mesh;
  101197. };
  101198. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  101199. if (distance === void 0) { distance = 100; }
  101200. this._laserPointer.scaling.y = distance;
  101201. this._laserPointer.position.z = -distance / 2;
  101202. };
  101203. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  101204. _super.prototype.dispose.call(this);
  101205. this._laserPointer.dispose();
  101206. if (this._meshAttachedObserver) {
  101207. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  101208. }
  101209. };
  101210. return VRExperienceHelperControllerGazer;
  101211. }(VRExperienceHelperGazer));
  101212. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  101213. __extends(VRExperienceHelperCameraGazer, _super);
  101214. function VRExperienceHelperCameraGazer(getCamera, scene) {
  101215. var _this = _super.call(this, scene) || this;
  101216. _this.getCamera = getCamera;
  101217. return _this;
  101218. }
  101219. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  101220. var camera = this.getCamera();
  101221. if (camera) {
  101222. return camera.getForwardRay(length);
  101223. }
  101224. else {
  101225. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  101226. }
  101227. };
  101228. return VRExperienceHelperCameraGazer;
  101229. }(VRExperienceHelperGazer));
  101230. /**
  101231. * Helps to quickly add VR support to an existing scene.
  101232. * See http://doc.babylonjs.com/how_to/webvr_helper
  101233. */
  101234. var VRExperienceHelper = /** @class */ (function () {
  101235. /**
  101236. * Instantiates a VRExperienceHelper.
  101237. * Helps to quickly add VR support to an existing scene.
  101238. * @param scene The scene the VRExperienceHelper belongs to.
  101239. * @param webVROptions Options to modify the vr experience helper's behavior.
  101240. */
  101241. function VRExperienceHelper(scene,
  101242. /** Options to modify the vr experience helper's behavior. */
  101243. webVROptions) {
  101244. if (webVROptions === void 0) { webVROptions = {}; }
  101245. var _this = this;
  101246. this.webVROptions = webVROptions;
  101247. // Can the system support WebVR, even if a headset isn't plugged in?
  101248. this._webVRsupported = false;
  101249. // If WebVR is supported, is a headset plugged in and are we ready to present?
  101250. this._webVRready = false;
  101251. // Are we waiting for the requestPresent callback to complete?
  101252. this._webVRrequesting = false;
  101253. // Are we presenting to the headset right now? (this is the vrDevice state)
  101254. this._webVRpresenting = false;
  101255. // Are we presenting in the fullscreen fallback?
  101256. this._fullscreenVRpresenting = false;
  101257. /**
  101258. * Observable raised when entering VR.
  101259. */
  101260. this.onEnteringVRObservable = new BABYLON.Observable();
  101261. /**
  101262. * Observable raised when exiting VR.
  101263. */
  101264. this.onExitingVRObservable = new BABYLON.Observable();
  101265. /**
  101266. * Observable raised when controller mesh is loaded.
  101267. */
  101268. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  101269. this._useCustomVRButton = false;
  101270. this._teleportationRequested = false;
  101271. this._teleportActive = false;
  101272. this._floorMeshesCollection = [];
  101273. this._rotationAllowed = true;
  101274. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  101275. this._isDefaultTeleportationTarget = true;
  101276. this._teleportationFillColor = "#444444";
  101277. this._teleportationBorderColor = "#FFFFFF";
  101278. this._rotationAngle = 0;
  101279. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  101280. this._padSensibilityUp = 0.65;
  101281. this._padSensibilityDown = 0.35;
  101282. this._leftController = null;
  101283. this._rightController = null;
  101284. /**
  101285. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  101286. */
  101287. this.onNewMeshSelected = new BABYLON.Observable();
  101288. /**
  101289. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  101290. */
  101291. this.onNewMeshPicked = new BABYLON.Observable();
  101292. /**
  101293. * Observable raised before camera teleportation
  101294. */
  101295. this.onBeforeCameraTeleport = new BABYLON.Observable();
  101296. /**
  101297. * Observable raised after camera teleportation
  101298. */
  101299. this.onAfterCameraTeleport = new BABYLON.Observable();
  101300. /**
  101301. * Observable raised when current selected mesh gets unselected
  101302. */
  101303. this.onSelectedMeshUnselected = new BABYLON.Observable();
  101304. /**
  101305. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  101306. */
  101307. this.teleportationEnabled = true;
  101308. this._teleportationInitialized = false;
  101309. this._interactionsEnabled = false;
  101310. this._interactionsRequested = false;
  101311. this._displayGaze = true;
  101312. this._displayLaserPointer = true;
  101313. /**
  101314. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  101315. */
  101316. this.updateGazeTrackerScale = true;
  101317. this._onResize = function () {
  101318. _this.moveButtonToBottomRight();
  101319. if (_this._fullscreenVRpresenting && _this._webVRready) {
  101320. _this.exitVR();
  101321. }
  101322. };
  101323. this._onFullscreenChange = function () {
  101324. if (document.fullscreen !== undefined) {
  101325. _this._fullscreenVRpresenting = document.fullscreen;
  101326. }
  101327. else if (document.mozFullScreen !== undefined) {
  101328. _this._fullscreenVRpresenting = document.mozFullScreen;
  101329. }
  101330. else if (document.webkitIsFullScreen !== undefined) {
  101331. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  101332. }
  101333. else if (document.msIsFullScreen !== undefined) {
  101334. _this._fullscreenVRpresenting = document.msIsFullScreen;
  101335. }
  101336. else if (document.msFullscreenElement !== undefined) {
  101337. _this._fullscreenVRpresenting = document.msFullscreenElement;
  101338. }
  101339. if (!_this._fullscreenVRpresenting && _this._canvas) {
  101340. _this.exitVR();
  101341. if (!_this._useCustomVRButton) {
  101342. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  101343. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  101344. }
  101345. }
  101346. };
  101347. this.beforeRender = function () {
  101348. if (_this._leftController && _this._leftController._activePointer) {
  101349. _this._castRayAndSelectObject(_this._leftController);
  101350. }
  101351. if (_this._rightController && _this._rightController._activePointer) {
  101352. _this._castRayAndSelectObject(_this._rightController);
  101353. }
  101354. if (_this._noControllerIsActive) {
  101355. _this._castRayAndSelectObject(_this._cameraGazer);
  101356. }
  101357. else {
  101358. _this._cameraGazer._gazeTracker.isVisible = false;
  101359. }
  101360. };
  101361. this._onNewGamepadConnected = function (gamepad) {
  101362. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  101363. if (gamepad.leftStick) {
  101364. gamepad.onleftstickchanged(function (stickValues) {
  101365. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  101366. // Listening to classic/xbox gamepad only if no VR controller is active
  101367. if ((!_this._leftController && !_this._rightController) ||
  101368. ((_this._leftController && !_this._leftController._activePointer) &&
  101369. (_this._rightController && !_this._rightController._activePointer))) {
  101370. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  101371. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  101372. }
  101373. }
  101374. });
  101375. }
  101376. if (gamepad.rightStick) {
  101377. gamepad.onrightstickchanged(function (stickValues) {
  101378. if (_this._teleportationInitialized) {
  101379. _this._checkRotate(stickValues, _this._cameraGazer);
  101380. }
  101381. });
  101382. }
  101383. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  101384. gamepad.onbuttondown(function (buttonPressed) {
  101385. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  101386. _this._cameraGazer._selectionPointerDown();
  101387. }
  101388. });
  101389. gamepad.onbuttonup(function (buttonPressed) {
  101390. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  101391. _this._cameraGazer._selectionPointerUp();
  101392. }
  101393. });
  101394. }
  101395. }
  101396. else {
  101397. var webVRController = gamepad;
  101398. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  101399. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  101400. _this._rightController = controller;
  101401. }
  101402. else {
  101403. _this._leftController = controller;
  101404. }
  101405. _this._tryEnableInteractionOnController(controller);
  101406. }
  101407. };
  101408. // 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
  101409. this._tryEnableInteractionOnController = function (controller) {
  101410. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  101411. _this._enableInteractionOnController(controller);
  101412. }
  101413. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  101414. _this._enableTeleportationOnController(controller);
  101415. }
  101416. };
  101417. this._onNewGamepadDisconnected = function (gamepad) {
  101418. if (gamepad instanceof BABYLON.WebVRController) {
  101419. if (gamepad.hand === "left" && _this._leftController != null) {
  101420. _this._leftController.dispose();
  101421. _this._leftController = null;
  101422. }
  101423. if (gamepad.hand === "right" && _this._rightController != null) {
  101424. _this._rightController.dispose();
  101425. _this._rightController = null;
  101426. }
  101427. }
  101428. };
  101429. this._workingVector = BABYLON.Vector3.Zero();
  101430. this._workingQuaternion = BABYLON.Quaternion.Identity();
  101431. this._workingMatrix = BABYLON.Matrix.Identity();
  101432. this._scene = scene;
  101433. this._canvas = scene.getEngine().getRenderingCanvas();
  101434. // Parse options
  101435. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  101436. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  101437. }
  101438. if (webVROptions.createDeviceOrientationCamera === undefined) {
  101439. webVROptions.createDeviceOrientationCamera = true;
  101440. }
  101441. if (webVROptions.laserToggle === undefined) {
  101442. webVROptions.laserToggle = true;
  101443. }
  101444. if (webVROptions.defaultHeight === undefined) {
  101445. webVROptions.defaultHeight = 1.7;
  101446. }
  101447. if (webVROptions.useCustomVRButton) {
  101448. this._useCustomVRButton = true;
  101449. if (webVROptions.customVRButton) {
  101450. this._btnVR = webVROptions.customVRButton;
  101451. }
  101452. }
  101453. if (webVROptions.rayLength) {
  101454. this._rayLength = webVROptions.rayLength;
  101455. }
  101456. this._defaultHeight = webVROptions.defaultHeight;
  101457. if (webVROptions.positionScale) {
  101458. this._rayLength *= webVROptions.positionScale;
  101459. this._defaultHeight *= webVROptions.positionScale;
  101460. }
  101461. this._hasEnteredVR = false;
  101462. // Set position
  101463. if (this._scene.activeCamera) {
  101464. this._position = this._scene.activeCamera.position.clone();
  101465. }
  101466. else {
  101467. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  101468. }
  101469. // Set non-vr camera
  101470. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  101471. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  101472. // Copy data from existing camera
  101473. if (this._scene.activeCamera) {
  101474. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  101475. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  101476. // Set rotation from previous camera
  101477. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  101478. var targetCamera = this._scene.activeCamera;
  101479. if (targetCamera.rotationQuaternion) {
  101480. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  101481. }
  101482. else {
  101483. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  101484. }
  101485. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  101486. }
  101487. }
  101488. this._scene.activeCamera = this._deviceOrientationCamera;
  101489. if (this._canvas) {
  101490. this._scene.activeCamera.attachControl(this._canvas);
  101491. }
  101492. }
  101493. else {
  101494. this._existingCamera = this._scene.activeCamera;
  101495. }
  101496. // Create VR cameras
  101497. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  101498. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  101499. }
  101500. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  101501. this._webVRCamera.useStandingMatrix();
  101502. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  101503. // Create default button
  101504. if (!this._useCustomVRButton) {
  101505. this._btnVR = document.createElement("BUTTON");
  101506. this._btnVR.className = "babylonVRicon";
  101507. this._btnVR.id = "babylonVRiconbtn";
  101508. this._btnVR.title = "Click to switch to VR";
  101509. 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) }";
  101510. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  101511. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  101512. // css += ".babylonVRicon.vrdisplaysupported { }";
  101513. // css += ".babylonVRicon.vrdisplayready { }";
  101514. // css += ".babylonVRicon.vrdisplayrequesting { }";
  101515. var style = document.createElement('style');
  101516. style.appendChild(document.createTextNode(css));
  101517. document.getElementsByTagName('head')[0].appendChild(style);
  101518. this.moveButtonToBottomRight();
  101519. }
  101520. // VR button click event
  101521. if (this._btnVR) {
  101522. this._btnVR.addEventListener("click", function () {
  101523. if (!_this.isInVRMode) {
  101524. _this.enterVR();
  101525. }
  101526. else {
  101527. _this.exitVR();
  101528. }
  101529. });
  101530. }
  101531. // Window events
  101532. window.addEventListener("resize", this._onResize);
  101533. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  101534. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  101535. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  101536. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  101537. document.onmsfullscreenchange = this._onFullscreenChange;
  101538. // Display vr button when headset is connected
  101539. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  101540. this.displayVRButton();
  101541. }
  101542. else {
  101543. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  101544. if (e.vrDisplay) {
  101545. _this.displayVRButton();
  101546. }
  101547. });
  101548. }
  101549. // Exiting VR mode using 'ESC' key on desktop
  101550. this._onKeyDown = function (event) {
  101551. if (event.keyCode === 27 && _this.isInVRMode) {
  101552. _this.exitVR();
  101553. }
  101554. };
  101555. document.addEventListener("keydown", this._onKeyDown);
  101556. // Exiting VR mode double tapping the touch screen
  101557. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  101558. if (_this.isInVRMode) {
  101559. _this.exitVR();
  101560. if (_this._fullscreenVRpresenting) {
  101561. _this._scene.getEngine().switchFullscreen(true);
  101562. }
  101563. }
  101564. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  101565. // Listen for WebVR display changes
  101566. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  101567. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  101568. this._onVRRequestPresentStart = function () {
  101569. _this._webVRrequesting = true;
  101570. _this.updateButtonVisibility();
  101571. };
  101572. this._onVRRequestPresentComplete = function (success) {
  101573. _this._webVRrequesting = false;
  101574. _this.updateButtonVisibility();
  101575. };
  101576. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  101577. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  101578. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  101579. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  101580. scene.onDisposeObservable.add(function () {
  101581. _this.dispose();
  101582. });
  101583. // Gamepad connection events
  101584. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  101585. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  101586. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  101587. this.updateButtonVisibility();
  101588. //create easing functions
  101589. this._circleEase = new BABYLON.CircleEase();
  101590. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  101591. if (this.webVROptions.floorMeshes) {
  101592. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  101593. }
  101594. }
  101595. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  101596. /** Return this.onEnteringVRObservable
  101597. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  101598. */
  101599. get: function () {
  101600. return this.onEnteringVRObservable;
  101601. },
  101602. enumerable: true,
  101603. configurable: true
  101604. });
  101605. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  101606. /** Return this.onExitingVRObservable
  101607. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  101608. */
  101609. get: function () {
  101610. return this.onExitingVRObservable;
  101611. },
  101612. enumerable: true,
  101613. configurable: true
  101614. });
  101615. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  101616. /** Return this.onControllerMeshLoadedObservable
  101617. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  101618. */
  101619. get: function () {
  101620. return this.onControllerMeshLoadedObservable;
  101621. },
  101622. enumerable: true,
  101623. configurable: true
  101624. });
  101625. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  101626. /**
  101627. * The mesh used to display where the user is going to teleport.
  101628. */
  101629. get: function () {
  101630. return this._teleportationTarget;
  101631. },
  101632. /**
  101633. * Sets the mesh to be used to display where the user is going to teleport.
  101634. */
  101635. set: function (value) {
  101636. if (value) {
  101637. value.name = "teleportationTarget";
  101638. this._isDefaultTeleportationTarget = false;
  101639. this._teleportationTarget = value;
  101640. }
  101641. },
  101642. enumerable: true,
  101643. configurable: true
  101644. });
  101645. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  101646. /**
  101647. * 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
  101648. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  101649. * See http://doc.babylonjs.com/resources/baking_transformations
  101650. */
  101651. get: function () {
  101652. return this._cameraGazer._gazeTracker;
  101653. },
  101654. set: function (value) {
  101655. if (value) {
  101656. // Dispose of existing meshes
  101657. if (this._cameraGazer._gazeTracker) {
  101658. this._cameraGazer._gazeTracker.dispose();
  101659. }
  101660. if (this._leftController && this._leftController._gazeTracker) {
  101661. this._leftController._gazeTracker.dispose();
  101662. }
  101663. if (this._rightController && this._rightController._gazeTracker) {
  101664. this._rightController._gazeTracker.dispose();
  101665. }
  101666. // Set and create gaze trackers on head and controllers
  101667. this._cameraGazer._gazeTracker = value;
  101668. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  101669. this._cameraGazer._gazeTracker.isPickable = false;
  101670. this._cameraGazer._gazeTracker.isVisible = false;
  101671. this._cameraGazer._gazeTracker.name = "gazeTracker";
  101672. if (this._leftController) {
  101673. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  101674. }
  101675. if (this._rightController) {
  101676. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  101677. }
  101678. }
  101679. },
  101680. enumerable: true,
  101681. configurable: true
  101682. });
  101683. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  101684. /**
  101685. * The gaze tracking mesh corresponding to the left controller
  101686. */
  101687. get: function () {
  101688. if (this._leftController) {
  101689. return this._leftController._gazeTracker;
  101690. }
  101691. return null;
  101692. },
  101693. enumerable: true,
  101694. configurable: true
  101695. });
  101696. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  101697. /**
  101698. * The gaze tracking mesh corresponding to the right controller
  101699. */
  101700. get: function () {
  101701. if (this._rightController) {
  101702. return this._rightController._gazeTracker;
  101703. }
  101704. return null;
  101705. },
  101706. enumerable: true,
  101707. configurable: true
  101708. });
  101709. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  101710. /**
  101711. * If the ray of the gaze should be displayed.
  101712. */
  101713. get: function () {
  101714. return this._displayGaze;
  101715. },
  101716. /**
  101717. * Sets if the ray of the gaze should be displayed.
  101718. */
  101719. set: function (value) {
  101720. this._displayGaze = value;
  101721. if (!value) {
  101722. this._cameraGazer._gazeTracker.isVisible = false;
  101723. if (this._leftController) {
  101724. this._leftController._gazeTracker.isVisible = false;
  101725. }
  101726. if (this._rightController) {
  101727. this._rightController._gazeTracker.isVisible = false;
  101728. }
  101729. }
  101730. },
  101731. enumerable: true,
  101732. configurable: true
  101733. });
  101734. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  101735. /**
  101736. * If the ray of the LaserPointer should be displayed.
  101737. */
  101738. get: function () {
  101739. return this._displayLaserPointer;
  101740. },
  101741. /**
  101742. * Sets if the ray of the LaserPointer should be displayed.
  101743. */
  101744. set: function (value) {
  101745. this._displayLaserPointer = value;
  101746. if (!value) {
  101747. if (this._rightController) {
  101748. this._rightController._deactivatePointer();
  101749. this._rightController._gazeTracker.isVisible = false;
  101750. }
  101751. if (this._leftController) {
  101752. this._leftController._deactivatePointer();
  101753. this._leftController._gazeTracker.isVisible = false;
  101754. }
  101755. }
  101756. else {
  101757. if (this._rightController) {
  101758. this._rightController._activatePointer();
  101759. }
  101760. if (this._leftController) {
  101761. this._leftController._activatePointer();
  101762. }
  101763. }
  101764. },
  101765. enumerable: true,
  101766. configurable: true
  101767. });
  101768. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  101769. /**
  101770. * The deviceOrientationCamera used as the camera when not in VR.
  101771. */
  101772. get: function () {
  101773. return this._deviceOrientationCamera;
  101774. },
  101775. enumerable: true,
  101776. configurable: true
  101777. });
  101778. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  101779. /**
  101780. * Based on the current WebVR support, returns the current VR camera used.
  101781. */
  101782. get: function () {
  101783. if (this._webVRready) {
  101784. return this._webVRCamera;
  101785. }
  101786. else {
  101787. return this._scene.activeCamera;
  101788. }
  101789. },
  101790. enumerable: true,
  101791. configurable: true
  101792. });
  101793. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  101794. /**
  101795. * The webVRCamera which is used when in VR.
  101796. */
  101797. get: function () {
  101798. return this._webVRCamera;
  101799. },
  101800. enumerable: true,
  101801. configurable: true
  101802. });
  101803. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  101804. /**
  101805. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  101806. */
  101807. get: function () {
  101808. return this._vrDeviceOrientationCamera;
  101809. },
  101810. enumerable: true,
  101811. configurable: true
  101812. });
  101813. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  101814. get: function () {
  101815. var result = this._cameraGazer._teleportationRequestInitiated
  101816. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  101817. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  101818. return result;
  101819. },
  101820. enumerable: true,
  101821. configurable: true
  101822. });
  101823. // Raised when one of the controller has loaded successfully its associated default mesh
  101824. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  101825. if (this._leftController && this._leftController.webVRController == webVRController) {
  101826. if (webVRController.mesh) {
  101827. this._leftController._setLaserPointerParent(webVRController.mesh);
  101828. }
  101829. }
  101830. if (this._rightController && this._rightController.webVRController == webVRController) {
  101831. if (webVRController.mesh) {
  101832. this._rightController._setLaserPointerParent(webVRController.mesh);
  101833. }
  101834. }
  101835. try {
  101836. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  101837. }
  101838. catch (err) {
  101839. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  101840. }
  101841. };
  101842. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  101843. /**
  101844. * Gets a value indicating if we are currently in VR mode.
  101845. */
  101846. get: function () {
  101847. return this._webVRpresenting || this._fullscreenVRpresenting;
  101848. },
  101849. enumerable: true,
  101850. configurable: true
  101851. });
  101852. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  101853. var vrDisplay = this._scene.getEngine().getVRDevice();
  101854. if (vrDisplay) {
  101855. var wasPresenting = this._webVRpresenting;
  101856. this._webVRpresenting = vrDisplay.isPresenting;
  101857. if (wasPresenting && !this._webVRpresenting)
  101858. this.exitVR();
  101859. }
  101860. else {
  101861. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  101862. }
  101863. this.updateButtonVisibility();
  101864. };
  101865. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  101866. this._webVRsupported = eventArgs.vrSupported;
  101867. this._webVRready = !!eventArgs.vrDisplay;
  101868. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  101869. this.updateButtonVisibility();
  101870. };
  101871. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  101872. if (this._canvas && !this._useCustomVRButton) {
  101873. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  101874. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  101875. }
  101876. };
  101877. VRExperienceHelper.prototype.displayVRButton = function () {
  101878. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  101879. document.body.appendChild(this._btnVR);
  101880. this._btnVRDisplayed = true;
  101881. }
  101882. };
  101883. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  101884. if (!this._btnVR || this._useCustomVRButton) {
  101885. return;
  101886. }
  101887. this._btnVR.className = "babylonVRicon";
  101888. if (this.isInVRMode) {
  101889. this._btnVR.className += " vrdisplaypresenting";
  101890. }
  101891. else {
  101892. if (this._webVRready)
  101893. this._btnVR.className += " vrdisplayready";
  101894. if (this._webVRsupported)
  101895. this._btnVR.className += " vrdisplaysupported";
  101896. if (this._webVRrequesting)
  101897. this._btnVR.className += " vrdisplayrequesting";
  101898. }
  101899. };
  101900. /**
  101901. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  101902. * Otherwise, will use the fullscreen API.
  101903. */
  101904. VRExperienceHelper.prototype.enterVR = function () {
  101905. if (this.onEnteringVRObservable) {
  101906. try {
  101907. this.onEnteringVRObservable.notifyObservers(this);
  101908. }
  101909. catch (err) {
  101910. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  101911. }
  101912. }
  101913. if (this._scene.activeCamera) {
  101914. this._position = this._scene.activeCamera.position.clone();
  101915. // make sure that we return to the last active camera
  101916. this._existingCamera = this._scene.activeCamera;
  101917. }
  101918. if (this._webVRrequesting)
  101919. return;
  101920. // If WebVR is supported and a headset is connected
  101921. if (this._webVRready) {
  101922. if (!this._webVRpresenting) {
  101923. this._webVRCamera.position = this._position;
  101924. this._scene.activeCamera = this._webVRCamera;
  101925. }
  101926. }
  101927. else if (this._vrDeviceOrientationCamera) {
  101928. this._vrDeviceOrientationCamera.position = this._position;
  101929. if (this._scene.activeCamera) {
  101930. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  101931. }
  101932. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  101933. this._scene.getEngine().switchFullscreen(true);
  101934. this.updateButtonVisibility();
  101935. }
  101936. if (this._scene.activeCamera && this._canvas) {
  101937. this._scene.activeCamera.attachControl(this._canvas);
  101938. }
  101939. if (this._interactionsEnabled) {
  101940. this._scene.registerBeforeRender(this.beforeRender);
  101941. }
  101942. this._hasEnteredVR = true;
  101943. };
  101944. /**
  101945. * Attempt to exit VR, or fullscreen.
  101946. */
  101947. VRExperienceHelper.prototype.exitVR = function () {
  101948. if (this._hasEnteredVR) {
  101949. if (this.onExitingVRObservable) {
  101950. try {
  101951. this.onExitingVRObservable.notifyObservers(this);
  101952. }
  101953. catch (err) {
  101954. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  101955. }
  101956. }
  101957. if (this._webVRpresenting) {
  101958. this._scene.getEngine().disableVR();
  101959. }
  101960. if (this._scene.activeCamera) {
  101961. this._position = this._scene.activeCamera.position.clone();
  101962. }
  101963. if (this._deviceOrientationCamera) {
  101964. this._deviceOrientationCamera.position = this._position;
  101965. this._scene.activeCamera = this._deviceOrientationCamera;
  101966. if (this._canvas) {
  101967. this._scene.activeCamera.attachControl(this._canvas);
  101968. }
  101969. }
  101970. else if (this._existingCamera) {
  101971. this._existingCamera.position = this._position;
  101972. this._scene.activeCamera = this._existingCamera;
  101973. }
  101974. this.updateButtonVisibility();
  101975. if (this._interactionsEnabled) {
  101976. this._scene.unregisterBeforeRender(this.beforeRender);
  101977. this._cameraGazer._gazeTracker.isVisible = false;
  101978. if (this._leftController) {
  101979. this._leftController._gazeTracker.isVisible = false;
  101980. }
  101981. if (this._rightController) {
  101982. this._rightController._gazeTracker.isVisible = false;
  101983. }
  101984. }
  101985. // resize to update width and height when exiting vr exits fullscreen
  101986. this._scene.getEngine().resize();
  101987. this._hasEnteredVR = false;
  101988. }
  101989. };
  101990. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  101991. /**
  101992. * The position of the vr experience helper.
  101993. */
  101994. get: function () {
  101995. return this._position;
  101996. },
  101997. /**
  101998. * Sets the position of the vr experience helper.
  101999. */
  102000. set: function (value) {
  102001. this._position = value;
  102002. if (this._scene.activeCamera) {
  102003. this._scene.activeCamera.position = value;
  102004. }
  102005. },
  102006. enumerable: true,
  102007. configurable: true
  102008. });
  102009. /**
  102010. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  102011. */
  102012. VRExperienceHelper.prototype.enableInteractions = function () {
  102013. var _this = this;
  102014. if (!this._interactionsEnabled) {
  102015. this._interactionsRequested = true;
  102016. if (this._leftController) {
  102017. this._enableInteractionOnController(this._leftController);
  102018. }
  102019. if (this._rightController) {
  102020. this._enableInteractionOnController(this._rightController);
  102021. }
  102022. this.raySelectionPredicate = function (mesh) {
  102023. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  102024. };
  102025. this.meshSelectionPredicate = function (mesh) {
  102026. return true;
  102027. };
  102028. this._raySelectionPredicate = function (mesh) {
  102029. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  102030. && mesh.name.indexOf("teleportationTarget") === -1
  102031. && mesh.name.indexOf("torusTeleportation") === -1)) {
  102032. return _this.raySelectionPredicate(mesh);
  102033. }
  102034. return false;
  102035. };
  102036. this._interactionsEnabled = true;
  102037. }
  102038. };
  102039. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  102040. get: function () {
  102041. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  102042. },
  102043. enumerable: true,
  102044. configurable: true
  102045. });
  102046. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  102047. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  102048. if (this._floorMeshesCollection[i].id === mesh.id) {
  102049. return true;
  102050. }
  102051. }
  102052. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  102053. return true;
  102054. }
  102055. return false;
  102056. };
  102057. /**
  102058. * Adds a floor mesh to be used for teleportation.
  102059. * @param floorMesh the mesh to be used for teleportation.
  102060. */
  102061. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  102062. if (!this._floorMeshesCollection) {
  102063. return;
  102064. }
  102065. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  102066. return;
  102067. }
  102068. this._floorMeshesCollection.push(floorMesh);
  102069. };
  102070. /**
  102071. * Removes a floor mesh from being used for teleportation.
  102072. * @param floorMesh the mesh to be removed.
  102073. */
  102074. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  102075. if (!this._floorMeshesCollection) {
  102076. return;
  102077. }
  102078. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  102079. if (meshIndex !== -1) {
  102080. this._floorMeshesCollection.splice(meshIndex, 1);
  102081. }
  102082. };
  102083. /**
  102084. * Enables interactions and teleportation using the VR controllers and gaze.
  102085. * @param vrTeleportationOptions options to modify teleportation behavior.
  102086. */
  102087. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  102088. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  102089. if (!this._teleportationInitialized) {
  102090. this._teleportationRequested = true;
  102091. this.enableInteractions();
  102092. if (vrTeleportationOptions.floorMeshName) {
  102093. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  102094. }
  102095. if (vrTeleportationOptions.floorMeshes) {
  102096. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  102097. }
  102098. if (this._leftController != null) {
  102099. this._enableTeleportationOnController(this._leftController);
  102100. }
  102101. if (this._rightController != null) {
  102102. this._enableTeleportationOnController(this._rightController);
  102103. }
  102104. // Creates an image processing post process for the vignette not relying
  102105. // on the main scene configuration for image processing to reduce setup and spaces
  102106. // (gamma/linear) conflicts.
  102107. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  102108. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  102109. imageProcessingConfiguration.vignetteEnabled = true;
  102110. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  102111. this._webVRCamera.detachPostProcess(this._postProcessMove);
  102112. this._teleportationInitialized = true;
  102113. if (this._isDefaultTeleportationTarget) {
  102114. this._createTeleportationCircles();
  102115. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  102116. }
  102117. }
  102118. };
  102119. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  102120. var _this = this;
  102121. var controllerMesh = controller.webVRController.mesh;
  102122. if (controllerMesh) {
  102123. controller._interactionsEnabled = true;
  102124. controller._activatePointer();
  102125. if (this.webVROptions.laserToggle) {
  102126. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  102127. // Enabling / disabling laserPointer
  102128. if (_this._displayLaserPointer && stateObject.value === 1) {
  102129. if (controller._activePointer) {
  102130. controller._deactivatePointer();
  102131. }
  102132. else {
  102133. controller._activatePointer();
  102134. }
  102135. if (_this.displayGaze) {
  102136. controller._gazeTracker.isVisible = controller._activePointer;
  102137. }
  102138. }
  102139. });
  102140. }
  102141. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  102142. var gazer = controller;
  102143. if (_this._noControllerIsActive) {
  102144. gazer = _this._cameraGazer;
  102145. }
  102146. if (!gazer._pointerDownOnMeshAsked) {
  102147. if (stateObject.value > _this._padSensibilityUp) {
  102148. gazer._selectionPointerDown();
  102149. }
  102150. }
  102151. else if (stateObject.value < _this._padSensibilityDown) {
  102152. gazer._selectionPointerUp();
  102153. }
  102154. });
  102155. }
  102156. };
  102157. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  102158. // Dont teleport if another gaze already requested teleportation
  102159. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  102160. return;
  102161. }
  102162. if (!gazer._teleportationRequestInitiated) {
  102163. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  102164. gazer._activatePointer();
  102165. gazer._teleportationRequestInitiated = true;
  102166. }
  102167. }
  102168. else {
  102169. // Listening to the proper controller values changes to confirm teleportation
  102170. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  102171. if (this._teleportActive) {
  102172. this.teleportCamera(this._haloCenter);
  102173. }
  102174. gazer._teleportationRequestInitiated = false;
  102175. }
  102176. }
  102177. };
  102178. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  102179. // Only rotate when user is not currently selecting a teleportation location
  102180. if (gazer._teleportationRequestInitiated) {
  102181. return;
  102182. }
  102183. if (!gazer._rotationLeftAsked) {
  102184. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  102185. gazer._rotationLeftAsked = true;
  102186. if (this._rotationAllowed) {
  102187. this._rotateCamera(false);
  102188. }
  102189. }
  102190. }
  102191. else {
  102192. if (stateObject.x > -this._padSensibilityDown) {
  102193. gazer._rotationLeftAsked = false;
  102194. }
  102195. }
  102196. if (!gazer._rotationRightAsked) {
  102197. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  102198. gazer._rotationRightAsked = true;
  102199. if (this._rotationAllowed) {
  102200. this._rotateCamera(true);
  102201. }
  102202. }
  102203. }
  102204. else {
  102205. if (stateObject.x < this._padSensibilityDown) {
  102206. gazer._rotationRightAsked = false;
  102207. }
  102208. }
  102209. };
  102210. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  102211. // Only teleport backwards when user is not currently selecting a teleportation location
  102212. if (gazer._teleportationRequestInitiated) {
  102213. return;
  102214. }
  102215. // Teleport backwards
  102216. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  102217. if (!gazer._teleportationBackRequestInitiated) {
  102218. if (!this.currentVRCamera) {
  102219. return;
  102220. }
  102221. // Get rotation and position of the current camera
  102222. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  102223. var position = this.currentVRCamera.position;
  102224. // If the camera has device position, use that instead
  102225. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  102226. rotation = this.currentVRCamera.deviceRotationQuaternion;
  102227. position = this.currentVRCamera.devicePosition;
  102228. }
  102229. // Get matrix with only the y rotation of the device rotation
  102230. rotation.toEulerAnglesToRef(this._workingVector);
  102231. this._workingVector.z = 0;
  102232. this._workingVector.x = 0;
  102233. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  102234. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  102235. // Rotate backwards ray by device rotation to cast at the ground behind the user
  102236. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  102237. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  102238. var ray = new BABYLON.Ray(position, this._workingVector);
  102239. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  102240. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  102241. this.teleportCamera(hit.pickedPoint);
  102242. }
  102243. gazer._teleportationBackRequestInitiated = true;
  102244. }
  102245. }
  102246. else {
  102247. gazer._teleportationBackRequestInitiated = false;
  102248. }
  102249. };
  102250. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  102251. var _this = this;
  102252. var controllerMesh = controller.webVRController.mesh;
  102253. if (controllerMesh) {
  102254. if (!controller._interactionsEnabled) {
  102255. this._enableInteractionOnController(controller);
  102256. }
  102257. controller._interactionsEnabled = true;
  102258. controller._teleportationEnabled = true;
  102259. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  102260. controller._dpadPressed = false;
  102261. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  102262. controller._dpadPressed = stateObject.pressed;
  102263. if (!controller._dpadPressed) {
  102264. controller._rotationLeftAsked = false;
  102265. controller._rotationRightAsked = false;
  102266. controller._teleportationBackRequestInitiated = false;
  102267. }
  102268. });
  102269. }
  102270. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  102271. if (_this.teleportationEnabled) {
  102272. _this._checkTeleportBackwards(stateObject, controller);
  102273. _this._checkTeleportWithRay(stateObject, controller);
  102274. }
  102275. _this._checkRotate(stateObject, controller);
  102276. });
  102277. }
  102278. };
  102279. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  102280. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  102281. this._teleportationTarget.isPickable = false;
  102282. var length = 512;
  102283. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  102284. dynamicTexture.hasAlpha = true;
  102285. var context = dynamicTexture.getContext();
  102286. var centerX = length / 2;
  102287. var centerY = length / 2;
  102288. var radius = 200;
  102289. context.beginPath();
  102290. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  102291. context.fillStyle = this._teleportationFillColor;
  102292. context.fill();
  102293. context.lineWidth = 10;
  102294. context.strokeStyle = this._teleportationBorderColor;
  102295. context.stroke();
  102296. context.closePath();
  102297. dynamicTexture.update();
  102298. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  102299. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  102300. this._teleportationTarget.material = teleportationCircleMaterial;
  102301. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  102302. torus.isPickable = false;
  102303. torus.parent = this._teleportationTarget;
  102304. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  102305. var keys = [];
  102306. keys.push({
  102307. frame: 0,
  102308. value: 0
  102309. });
  102310. keys.push({
  102311. frame: 30,
  102312. value: 0.4
  102313. });
  102314. keys.push({
  102315. frame: 60,
  102316. value: 0
  102317. });
  102318. animationInnerCircle.setKeys(keys);
  102319. var easingFunction = new BABYLON.SineEase();
  102320. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  102321. animationInnerCircle.setEasingFunction(easingFunction);
  102322. torus.animations = [];
  102323. torus.animations.push(animationInnerCircle);
  102324. this._scene.beginAnimation(torus, 0, 60, true);
  102325. this._hideTeleportationTarget();
  102326. };
  102327. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  102328. this._teleportActive = true;
  102329. if (this._teleportationInitialized) {
  102330. this._teleportationTarget.isVisible = true;
  102331. if (this._isDefaultTeleportationTarget) {
  102332. this._teleportationTarget.getChildren()[0].isVisible = true;
  102333. }
  102334. }
  102335. };
  102336. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  102337. this._teleportActive = false;
  102338. if (this._teleportationInitialized) {
  102339. this._teleportationTarget.isVisible = false;
  102340. if (this._isDefaultTeleportationTarget) {
  102341. this._teleportationTarget.getChildren()[0].isVisible = false;
  102342. }
  102343. }
  102344. };
  102345. VRExperienceHelper.prototype._rotateCamera = function (right) {
  102346. var _this = this;
  102347. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  102348. return;
  102349. }
  102350. if (right) {
  102351. this._rotationAngle++;
  102352. }
  102353. else {
  102354. this._rotationAngle--;
  102355. }
  102356. this.currentVRCamera.animations = [];
  102357. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  102358. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  102359. var animationRotationKeys = [];
  102360. animationRotationKeys.push({
  102361. frame: 0,
  102362. value: this.currentVRCamera.rotationQuaternion
  102363. });
  102364. animationRotationKeys.push({
  102365. frame: 6,
  102366. value: target
  102367. });
  102368. animationRotation.setKeys(animationRotationKeys);
  102369. animationRotation.setEasingFunction(this._circleEase);
  102370. this.currentVRCamera.animations.push(animationRotation);
  102371. this._postProcessMove.animations = [];
  102372. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  102373. var vignetteWeightKeys = [];
  102374. vignetteWeightKeys.push({
  102375. frame: 0,
  102376. value: 0
  102377. });
  102378. vignetteWeightKeys.push({
  102379. frame: 3,
  102380. value: 4
  102381. });
  102382. vignetteWeightKeys.push({
  102383. frame: 6,
  102384. value: 0
  102385. });
  102386. animationPP.setKeys(vignetteWeightKeys);
  102387. animationPP.setEasingFunction(this._circleEase);
  102388. this._postProcessMove.animations.push(animationPP);
  102389. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  102390. var vignetteStretchKeys = [];
  102391. vignetteStretchKeys.push({
  102392. frame: 0,
  102393. value: 0
  102394. });
  102395. vignetteStretchKeys.push({
  102396. frame: 3,
  102397. value: 10
  102398. });
  102399. vignetteStretchKeys.push({
  102400. frame: 6,
  102401. value: 0
  102402. });
  102403. animationPP2.setKeys(vignetteStretchKeys);
  102404. animationPP2.setEasingFunction(this._circleEase);
  102405. this._postProcessMove.animations.push(animationPP2);
  102406. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  102407. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  102408. this._postProcessMove.samples = 4;
  102409. this._webVRCamera.attachPostProcess(this._postProcessMove);
  102410. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  102411. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  102412. });
  102413. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  102414. };
  102415. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  102416. if (hit.pickedPoint) {
  102417. if (gazer._teleportationRequestInitiated) {
  102418. this._displayTeleportationTarget();
  102419. this._haloCenter.copyFrom(hit.pickedPoint);
  102420. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  102421. }
  102422. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  102423. if (pickNormal) {
  102424. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  102425. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  102426. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  102427. }
  102428. this._teleportationTarget.position.y += 0.1;
  102429. }
  102430. };
  102431. /**
  102432. * Teleports the users feet to the desired location
  102433. * @param location The location where the user's feet should be placed
  102434. */
  102435. VRExperienceHelper.prototype.teleportCamera = function (location) {
  102436. var _this = this;
  102437. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  102438. return;
  102439. }
  102440. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  102441. // offset of the headset from the anchor.
  102442. if (this.webVRCamera.leftCamera) {
  102443. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  102444. this._workingVector.subtractInPlace(this.webVRCamera.position);
  102445. location.subtractToRef(this._workingVector, this._workingVector);
  102446. }
  102447. else {
  102448. this._workingVector.copyFrom(location);
  102449. }
  102450. // Add height to account for user's height offset
  102451. if (this.isInVRMode) {
  102452. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  102453. }
  102454. else {
  102455. this._workingVector.y += this._defaultHeight;
  102456. }
  102457. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  102458. // Create animation from the camera's position to the new location
  102459. this.currentVRCamera.animations = [];
  102460. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  102461. var animationCameraTeleportationKeys = [{
  102462. frame: 0,
  102463. value: this.currentVRCamera.position
  102464. },
  102465. {
  102466. frame: 11,
  102467. value: this._workingVector
  102468. }
  102469. ];
  102470. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  102471. animationCameraTeleportation.setEasingFunction(this._circleEase);
  102472. this.currentVRCamera.animations.push(animationCameraTeleportation);
  102473. this._postProcessMove.animations = [];
  102474. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  102475. var vignetteWeightKeys = [];
  102476. vignetteWeightKeys.push({
  102477. frame: 0,
  102478. value: 0
  102479. });
  102480. vignetteWeightKeys.push({
  102481. frame: 5,
  102482. value: 8
  102483. });
  102484. vignetteWeightKeys.push({
  102485. frame: 11,
  102486. value: 0
  102487. });
  102488. animationPP.setKeys(vignetteWeightKeys);
  102489. this._postProcessMove.animations.push(animationPP);
  102490. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  102491. var vignetteStretchKeys = [];
  102492. vignetteStretchKeys.push({
  102493. frame: 0,
  102494. value: 0
  102495. });
  102496. vignetteStretchKeys.push({
  102497. frame: 5,
  102498. value: 10
  102499. });
  102500. vignetteStretchKeys.push({
  102501. frame: 11,
  102502. value: 0
  102503. });
  102504. animationPP2.setKeys(vignetteStretchKeys);
  102505. this._postProcessMove.animations.push(animationPP2);
  102506. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  102507. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  102508. this._webVRCamera.attachPostProcess(this._postProcessMove);
  102509. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  102510. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  102511. });
  102512. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  102513. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  102514. });
  102515. this._hideTeleportationTarget();
  102516. };
  102517. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  102518. if (normal) {
  102519. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  102520. if (angle < Math.PI / 2) {
  102521. normal.scaleInPlace(-1);
  102522. }
  102523. }
  102524. return normal;
  102525. };
  102526. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  102527. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  102528. return;
  102529. }
  102530. var ray = gazer._getForwardRay(this._rayLength);
  102531. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  102532. if (hit) {
  102533. // Populate the contrllers mesh that can be used for drag/drop
  102534. if (gazer._laserPointer) {
  102535. hit.originMesh = gazer._laserPointer.parent;
  102536. }
  102537. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  102538. }
  102539. gazer._currentHit = hit;
  102540. // Moving the gazeTracker on the mesh face targetted
  102541. if (hit && hit.pickedPoint) {
  102542. if (this._displayGaze) {
  102543. var multiplier = 1;
  102544. gazer._gazeTracker.isVisible = true;
  102545. if (gazer._isActionableMesh) {
  102546. multiplier = 3;
  102547. }
  102548. if (this.updateGazeTrackerScale) {
  102549. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  102550. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  102551. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  102552. }
  102553. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  102554. // To avoid z-fighting
  102555. var deltaFighting = 0.002;
  102556. if (pickNormal) {
  102557. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  102558. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  102559. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  102560. }
  102561. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  102562. if (gazer._gazeTracker.position.x < 0) {
  102563. gazer._gazeTracker.position.x += deltaFighting;
  102564. }
  102565. else {
  102566. gazer._gazeTracker.position.x -= deltaFighting;
  102567. }
  102568. if (gazer._gazeTracker.position.y < 0) {
  102569. gazer._gazeTracker.position.y += deltaFighting;
  102570. }
  102571. else {
  102572. gazer._gazeTracker.position.y -= deltaFighting;
  102573. }
  102574. if (gazer._gazeTracker.position.z < 0) {
  102575. gazer._gazeTracker.position.z += deltaFighting;
  102576. }
  102577. else {
  102578. gazer._gazeTracker.position.z -= deltaFighting;
  102579. }
  102580. }
  102581. // Changing the size of the laser pointer based on the distance from the targetted point
  102582. gazer._updatePointerDistance(hit.distance);
  102583. }
  102584. else {
  102585. gazer._updatePointerDistance();
  102586. gazer._gazeTracker.isVisible = false;
  102587. }
  102588. if (hit && hit.pickedMesh) {
  102589. // The object selected is the floor, we're in a teleportation scenario
  102590. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  102591. // Moving the teleportation area to this targetted point
  102592. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  102593. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  102594. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  102595. }
  102596. gazer._currentMeshSelected = null;
  102597. if (gazer._teleportationRequestInitiated) {
  102598. this._moveTeleportationSelectorTo(hit, gazer, ray);
  102599. }
  102600. return;
  102601. }
  102602. // If not, we're in a selection scenario
  102603. //this._teleportationAllowed = false;
  102604. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  102605. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  102606. this.onNewMeshPicked.notifyObservers(hit);
  102607. gazer._currentMeshSelected = hit.pickedMesh;
  102608. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  102609. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  102610. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  102611. gazer._isActionableMesh = true;
  102612. }
  102613. else {
  102614. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102615. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102616. gazer._isActionableMesh = false;
  102617. }
  102618. try {
  102619. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  102620. }
  102621. catch (err) {
  102622. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  102623. }
  102624. }
  102625. else {
  102626. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  102627. gazer._currentMeshSelected = null;
  102628. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102629. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102630. }
  102631. }
  102632. }
  102633. else {
  102634. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  102635. gazer._currentMeshSelected = null;
  102636. //this._teleportationAllowed = false;
  102637. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102638. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102639. }
  102640. };
  102641. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  102642. if (mesh) {
  102643. this.onSelectedMeshUnselected.notifyObservers(mesh);
  102644. }
  102645. };
  102646. /**
  102647. * Sets the color of the laser ray from the vr controllers.
  102648. * @param color new color for the ray.
  102649. */
  102650. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  102651. if (this._leftController) {
  102652. this._leftController._setLaserPointerColor(color);
  102653. }
  102654. if (this._rightController) {
  102655. this._rightController._setLaserPointerColor(color);
  102656. }
  102657. };
  102658. /**
  102659. * Sets the color of the ray from the vr headsets gaze.
  102660. * @param color new color for the ray.
  102661. */
  102662. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  102663. if (!this._cameraGazer._gazeTracker.material) {
  102664. return;
  102665. }
  102666. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  102667. if (this._leftController) {
  102668. this._leftController._gazeTracker.material.emissiveColor = color;
  102669. }
  102670. if (this._rightController) {
  102671. this._rightController._gazeTracker.material.emissiveColor = color;
  102672. }
  102673. };
  102674. /**
  102675. * Exits VR and disposes of the vr experience helper
  102676. */
  102677. VRExperienceHelper.prototype.dispose = function () {
  102678. if (this.isInVRMode) {
  102679. this.exitVR();
  102680. }
  102681. if (this._postProcessMove) {
  102682. this._postProcessMove.dispose();
  102683. }
  102684. if (this._webVRCamera) {
  102685. this._webVRCamera.dispose();
  102686. }
  102687. if (this._vrDeviceOrientationCamera) {
  102688. this._vrDeviceOrientationCamera.dispose();
  102689. }
  102690. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  102691. document.body.removeChild(this._btnVR);
  102692. }
  102693. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  102694. this._deviceOrientationCamera.dispose();
  102695. }
  102696. if (this._cameraGazer) {
  102697. this._cameraGazer.dispose();
  102698. }
  102699. if (this._leftController) {
  102700. this._leftController.dispose();
  102701. }
  102702. if (this._rightController) {
  102703. this._rightController.dispose();
  102704. }
  102705. if (this._teleportationTarget) {
  102706. this._teleportationTarget.dispose();
  102707. }
  102708. this._floorMeshesCollection = [];
  102709. document.removeEventListener("keydown", this._onKeyDown);
  102710. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  102711. window.removeEventListener("resize", this._onResize);
  102712. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  102713. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  102714. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  102715. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  102716. document.onmsfullscreenchange = null;
  102717. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  102718. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  102719. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  102720. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  102721. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  102722. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  102723. this._scene.unregisterBeforeRender(this.beforeRender);
  102724. };
  102725. /**
  102726. * Gets the name of the VRExperienceHelper class
  102727. * @returns "VRExperienceHelper"
  102728. */
  102729. VRExperienceHelper.prototype.getClassName = function () {
  102730. return "VRExperienceHelper";
  102731. };
  102732. return VRExperienceHelper;
  102733. }());
  102734. BABYLON.VRExperienceHelper = VRExperienceHelper;
  102735. })(BABYLON || (BABYLON = {}));
  102736. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  102737. // Mainly based on these 2 articles :
  102738. // 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
  102739. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  102740. var BABYLON;
  102741. (function (BABYLON) {
  102742. /**
  102743. * Defines the potential axis of a Joystick
  102744. */
  102745. var JoystickAxis;
  102746. (function (JoystickAxis) {
  102747. /** X axis */
  102748. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  102749. /** Y axis */
  102750. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  102751. /** Z axis */
  102752. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  102753. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  102754. /**
  102755. * Class used to define virtual joystick (used in touch mode)
  102756. */
  102757. var VirtualJoystick = /** @class */ (function () {
  102758. /**
  102759. * Creates a new virtual joystick
  102760. * @param leftJoystick defines that the joystick is for left hand (false by default)
  102761. */
  102762. function VirtualJoystick(leftJoystick) {
  102763. var _this = this;
  102764. if (leftJoystick) {
  102765. this._leftJoystick = true;
  102766. }
  102767. else {
  102768. this._leftJoystick = false;
  102769. }
  102770. VirtualJoystick._globalJoystickIndex++;
  102771. // By default left & right arrow keys are moving the X
  102772. // and up & down keys are moving the Y
  102773. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  102774. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  102775. this.reverseLeftRight = false;
  102776. this.reverseUpDown = false;
  102777. // collections of pointers
  102778. this._touches = new BABYLON.StringDictionary();
  102779. this.deltaPosition = BABYLON.Vector3.Zero();
  102780. this._joystickSensibility = 25;
  102781. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  102782. this._onResize = function (evt) {
  102783. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  102784. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  102785. if (VirtualJoystick.vjCanvas) {
  102786. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  102787. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  102788. }
  102789. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  102790. };
  102791. // injecting a canvas element on top of the canvas 3D game
  102792. if (!VirtualJoystick.vjCanvas) {
  102793. window.addEventListener("resize", this._onResize, false);
  102794. VirtualJoystick.vjCanvas = document.createElement("canvas");
  102795. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  102796. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  102797. VirtualJoystick.vjCanvas.width = window.innerWidth;
  102798. VirtualJoystick.vjCanvas.height = window.innerHeight;
  102799. VirtualJoystick.vjCanvas.style.width = "100%";
  102800. VirtualJoystick.vjCanvas.style.height = "100%";
  102801. VirtualJoystick.vjCanvas.style.position = "absolute";
  102802. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  102803. VirtualJoystick.vjCanvas.style.top = "0px";
  102804. VirtualJoystick.vjCanvas.style.left = "0px";
  102805. VirtualJoystick.vjCanvas.style.zIndex = "5";
  102806. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  102807. // Support for jQuery PEP polyfill
  102808. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  102809. var context = VirtualJoystick.vjCanvas.getContext('2d');
  102810. if (!context) {
  102811. throw new Error("Unable to create canvas for virtual joystick");
  102812. }
  102813. VirtualJoystick.vjCanvasContext = context;
  102814. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  102815. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  102816. document.body.appendChild(VirtualJoystick.vjCanvas);
  102817. }
  102818. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  102819. this.pressed = false;
  102820. // default joystick color
  102821. this._joystickColor = "cyan";
  102822. this._joystickPointerID = -1;
  102823. // current joystick position
  102824. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  102825. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  102826. // origin joystick position
  102827. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  102828. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  102829. this._onPointerDownHandlerRef = function (evt) {
  102830. _this._onPointerDown(evt);
  102831. };
  102832. this._onPointerMoveHandlerRef = function (evt) {
  102833. _this._onPointerMove(evt);
  102834. };
  102835. this._onPointerUpHandlerRef = function (evt) {
  102836. _this._onPointerUp(evt);
  102837. };
  102838. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  102839. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  102840. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  102841. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  102842. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  102843. evt.preventDefault(); // Disables system menu
  102844. }, false);
  102845. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  102846. }
  102847. /**
  102848. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  102849. * @param newJoystickSensibility defines the new sensibility
  102850. */
  102851. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  102852. this._joystickSensibility = newJoystickSensibility;
  102853. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  102854. };
  102855. VirtualJoystick.prototype._onPointerDown = function (e) {
  102856. var positionOnScreenCondition;
  102857. e.preventDefault();
  102858. if (this._leftJoystick === true) {
  102859. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  102860. }
  102861. else {
  102862. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  102863. }
  102864. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  102865. // First contact will be dedicated to the virtual joystick
  102866. this._joystickPointerID = e.pointerId;
  102867. this._joystickPointerStartPos.x = e.clientX;
  102868. this._joystickPointerStartPos.y = e.clientY;
  102869. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  102870. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  102871. this._deltaJoystickVector.x = 0;
  102872. this._deltaJoystickVector.y = 0;
  102873. this.pressed = true;
  102874. this._touches.add(e.pointerId.toString(), e);
  102875. }
  102876. else {
  102877. // You can only trigger the action buttons with a joystick declared
  102878. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  102879. this._action();
  102880. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  102881. }
  102882. }
  102883. };
  102884. VirtualJoystick.prototype._onPointerMove = function (e) {
  102885. // If the current pointer is the one associated to the joystick (first touch contact)
  102886. if (this._joystickPointerID == e.pointerId) {
  102887. this._joystickPointerPos.x = e.clientX;
  102888. this._joystickPointerPos.y = e.clientY;
  102889. this._deltaJoystickVector = this._joystickPointerPos.clone();
  102890. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  102891. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  102892. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  102893. switch (this._axisTargetedByLeftAndRight) {
  102894. case JoystickAxis.X:
  102895. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  102896. break;
  102897. case JoystickAxis.Y:
  102898. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  102899. break;
  102900. case JoystickAxis.Z:
  102901. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  102902. break;
  102903. }
  102904. var directionUpDown = this.reverseUpDown ? 1 : -1;
  102905. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  102906. switch (this._axisTargetedByUpAndDown) {
  102907. case JoystickAxis.X:
  102908. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  102909. break;
  102910. case JoystickAxis.Y:
  102911. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  102912. break;
  102913. case JoystickAxis.Z:
  102914. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  102915. break;
  102916. }
  102917. }
  102918. else {
  102919. var data = this._touches.get(e.pointerId.toString());
  102920. if (data) {
  102921. data.x = e.clientX;
  102922. data.y = e.clientY;
  102923. }
  102924. }
  102925. };
  102926. VirtualJoystick.prototype._onPointerUp = function (e) {
  102927. if (this._joystickPointerID == e.pointerId) {
  102928. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  102929. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  102930. this._joystickPointerID = -1;
  102931. this.pressed = false;
  102932. }
  102933. else {
  102934. var touch = this._touches.get(e.pointerId.toString());
  102935. if (touch) {
  102936. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  102937. }
  102938. }
  102939. this._deltaJoystickVector.x = 0;
  102940. this._deltaJoystickVector.y = 0;
  102941. this._touches.remove(e.pointerId.toString());
  102942. };
  102943. /**
  102944. * Change the color of the virtual joystick
  102945. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  102946. */
  102947. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  102948. this._joystickColor = newColor;
  102949. };
  102950. /**
  102951. * Defines a callback to call when the joystick is touched
  102952. * @param action defines the callback
  102953. */
  102954. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  102955. this._action = action;
  102956. };
  102957. /**
  102958. * Defines which axis you'd like to control for left & right
  102959. * @param axis defines the axis to use
  102960. */
  102961. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  102962. switch (axis) {
  102963. case JoystickAxis.X:
  102964. case JoystickAxis.Y:
  102965. case JoystickAxis.Z:
  102966. this._axisTargetedByLeftAndRight = axis;
  102967. break;
  102968. default:
  102969. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  102970. break;
  102971. }
  102972. };
  102973. /**
  102974. * Defines which axis you'd like to control for up & down
  102975. * @param axis defines the axis to use
  102976. */
  102977. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  102978. switch (axis) {
  102979. case JoystickAxis.X:
  102980. case JoystickAxis.Y:
  102981. case JoystickAxis.Z:
  102982. this._axisTargetedByUpAndDown = axis;
  102983. break;
  102984. default:
  102985. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  102986. break;
  102987. }
  102988. };
  102989. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  102990. var _this = this;
  102991. if (this.pressed) {
  102992. this._touches.forEach(function (key, touch) {
  102993. if (touch.pointerId === _this._joystickPointerID) {
  102994. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  102995. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  102996. VirtualJoystick.vjCanvasContext.beginPath();
  102997. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  102998. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  102999. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  103000. VirtualJoystick.vjCanvasContext.stroke();
  103001. VirtualJoystick.vjCanvasContext.closePath();
  103002. VirtualJoystick.vjCanvasContext.beginPath();
  103003. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  103004. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  103005. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  103006. VirtualJoystick.vjCanvasContext.stroke();
  103007. VirtualJoystick.vjCanvasContext.closePath();
  103008. VirtualJoystick.vjCanvasContext.beginPath();
  103009. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  103010. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  103011. VirtualJoystick.vjCanvasContext.stroke();
  103012. VirtualJoystick.vjCanvasContext.closePath();
  103013. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  103014. }
  103015. else {
  103016. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  103017. VirtualJoystick.vjCanvasContext.beginPath();
  103018. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  103019. VirtualJoystick.vjCanvasContext.beginPath();
  103020. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  103021. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  103022. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  103023. VirtualJoystick.vjCanvasContext.stroke();
  103024. VirtualJoystick.vjCanvasContext.closePath();
  103025. touch.prevX = touch.x;
  103026. touch.prevY = touch.y;
  103027. }
  103028. ;
  103029. });
  103030. }
  103031. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  103032. };
  103033. /**
  103034. * Release internal HTML canvas
  103035. */
  103036. VirtualJoystick.prototype.releaseCanvas = function () {
  103037. if (VirtualJoystick.vjCanvas) {
  103038. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  103039. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  103040. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  103041. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  103042. window.removeEventListener("resize", this._onResize);
  103043. document.body.removeChild(VirtualJoystick.vjCanvas);
  103044. VirtualJoystick.vjCanvas = null;
  103045. }
  103046. };
  103047. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  103048. VirtualJoystick._globalJoystickIndex = 0;
  103049. return VirtualJoystick;
  103050. }());
  103051. BABYLON.VirtualJoystick = VirtualJoystick;
  103052. })(BABYLON || (BABYLON = {}));
  103053. //# sourceMappingURL=babylon.virtualJoystick.js.map
  103054. var BABYLON;
  103055. (function (BABYLON) {
  103056. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  103057. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  103058. });
  103059. /**
  103060. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  103061. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  103062. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  103063. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  103064. */
  103065. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  103066. __extends(VirtualJoysticksCamera, _super);
  103067. /**
  103068. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  103069. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  103070. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  103071. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  103072. * @param name Define the name of the camera in the scene
  103073. * @param position Define the start position of the camera in the scene
  103074. * @param scene Define the scene the camera belongs to
  103075. */
  103076. function VirtualJoysticksCamera(name, position, scene) {
  103077. var _this = _super.call(this, name, position, scene) || this;
  103078. _this.inputs.addVirtualJoystick();
  103079. return _this;
  103080. }
  103081. /**
  103082. * Gets the current object class name.
  103083. * @return the class name
  103084. */
  103085. VirtualJoysticksCamera.prototype.getClassName = function () {
  103086. return "VirtualJoysticksCamera";
  103087. };
  103088. return VirtualJoysticksCamera;
  103089. }(BABYLON.FreeCamera));
  103090. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  103091. })(BABYLON || (BABYLON = {}));
  103092. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  103093. var BABYLON;
  103094. (function (BABYLON) {
  103095. /**
  103096. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  103097. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103098. */
  103099. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  103100. function FreeCameraVirtualJoystickInput() {
  103101. }
  103102. /**
  103103. * Gets the left stick of the virtual joystick.
  103104. * @returns The virtual Joystick
  103105. */
  103106. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  103107. return this._leftjoystick;
  103108. };
  103109. /**
  103110. * Gets the right stick of the virtual joystick.
  103111. * @returns The virtual Joystick
  103112. */
  103113. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  103114. return this._rightjoystick;
  103115. };
  103116. /**
  103117. * Update the current camera state depending on the inputs that have been used this frame.
  103118. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  103119. */
  103120. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  103121. if (this._leftjoystick) {
  103122. var camera = this.camera;
  103123. var speed = camera._computeLocalCameraSpeed() * 50;
  103124. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  103125. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  103126. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  103127. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  103128. if (!this._leftjoystick.pressed) {
  103129. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  103130. }
  103131. if (!this._rightjoystick.pressed) {
  103132. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  103133. }
  103134. }
  103135. };
  103136. /**
  103137. * Attach the input controls to a specific dom element to get the input from.
  103138. * @param element Defines the element the controls should be listened from
  103139. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  103140. */
  103141. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  103142. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  103143. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  103144. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  103145. this._leftjoystick.setJoystickSensibility(0.15);
  103146. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  103147. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  103148. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  103149. this._rightjoystick.reverseUpDown = true;
  103150. this._rightjoystick.setJoystickSensibility(0.05);
  103151. this._rightjoystick.setJoystickColor("yellow");
  103152. };
  103153. /**
  103154. * Detach the current controls from the specified dom element.
  103155. * @param element Defines the element to stop listening the inputs from
  103156. */
  103157. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  103158. this._leftjoystick.releaseCanvas();
  103159. this._rightjoystick.releaseCanvas();
  103160. };
  103161. /**
  103162. * Gets the class name of the current intput.
  103163. * @returns the class name
  103164. */
  103165. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  103166. return "FreeCameraVirtualJoystickInput";
  103167. };
  103168. /**
  103169. * Get the friendly name associated with the input class.
  103170. * @returns the input friendly name
  103171. */
  103172. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  103173. return "virtualJoystick";
  103174. };
  103175. return FreeCameraVirtualJoystickInput;
  103176. }());
  103177. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  103178. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  103179. })(BABYLON || (BABYLON = {}));
  103180. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  103181. var BABYLON;
  103182. (function (BABYLON) {
  103183. /**
  103184. * Class used to specify simplification options
  103185. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  103186. */
  103187. var SimplificationSettings = /** @class */ (function () {
  103188. /**
  103189. * Creates a SimplificationSettings
  103190. * @param quality expected quality
  103191. * @param distance distance when this optimized version should be used
  103192. * @param optimizeMesh already optimized mesh
  103193. */
  103194. function SimplificationSettings(
  103195. /** expected quality */
  103196. quality,
  103197. /** distance when this optimized version should be used */
  103198. distance,
  103199. /** already optimized mesh */
  103200. optimizeMesh) {
  103201. this.quality = quality;
  103202. this.distance = distance;
  103203. this.optimizeMesh = optimizeMesh;
  103204. }
  103205. return SimplificationSettings;
  103206. }());
  103207. BABYLON.SimplificationSettings = SimplificationSettings;
  103208. /**
  103209. * Queue used to order the simplification tasks
  103210. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  103211. */
  103212. var SimplificationQueue = /** @class */ (function () {
  103213. /**
  103214. * Creates a new queue
  103215. */
  103216. function SimplificationQueue() {
  103217. this.running = false;
  103218. this._simplificationArray = [];
  103219. }
  103220. /**
  103221. * Adds a new simplification task
  103222. * @param task defines a task to add
  103223. */
  103224. SimplificationQueue.prototype.addTask = function (task) {
  103225. this._simplificationArray.push(task);
  103226. };
  103227. /**
  103228. * Execute next task
  103229. */
  103230. SimplificationQueue.prototype.executeNext = function () {
  103231. var task = this._simplificationArray.pop();
  103232. if (task) {
  103233. this.running = true;
  103234. this.runSimplification(task);
  103235. }
  103236. else {
  103237. this.running = false;
  103238. }
  103239. };
  103240. /**
  103241. * Execute a simplification task
  103242. * @param task defines the task to run
  103243. */
  103244. SimplificationQueue.prototype.runSimplification = function (task) {
  103245. var _this = this;
  103246. if (task.parallelProcessing) {
  103247. //parallel simplifier
  103248. task.settings.forEach(function (setting) {
  103249. var simplifier = _this.getSimplifier(task);
  103250. simplifier.simplify(setting, function (newMesh) {
  103251. task.mesh.addLODLevel(setting.distance, newMesh);
  103252. newMesh.isVisible = true;
  103253. //check if it is the last
  103254. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  103255. //all done, run the success callback.
  103256. task.successCallback();
  103257. }
  103258. _this.executeNext();
  103259. });
  103260. });
  103261. }
  103262. else {
  103263. //single simplifier.
  103264. var simplifier = this.getSimplifier(task);
  103265. var runDecimation = function (setting, callback) {
  103266. simplifier.simplify(setting, function (newMesh) {
  103267. task.mesh.addLODLevel(setting.distance, newMesh);
  103268. newMesh.isVisible = true;
  103269. //run the next quality level
  103270. callback();
  103271. });
  103272. };
  103273. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  103274. runDecimation(task.settings[loop.index], function () {
  103275. loop.executeNext();
  103276. });
  103277. }, function () {
  103278. //execution ended, run the success callback.
  103279. if (task.successCallback) {
  103280. task.successCallback();
  103281. }
  103282. _this.executeNext();
  103283. });
  103284. }
  103285. };
  103286. SimplificationQueue.prototype.getSimplifier = function (task) {
  103287. switch (task.simplificationType) {
  103288. case SimplificationType.QUADRATIC:
  103289. default:
  103290. return new QuadraticErrorSimplification(task.mesh);
  103291. }
  103292. };
  103293. return SimplificationQueue;
  103294. }());
  103295. BABYLON.SimplificationQueue = SimplificationQueue;
  103296. /**
  103297. * The implemented types of simplification
  103298. * At the moment only Quadratic Error Decimation is implemented
  103299. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  103300. */
  103301. var SimplificationType;
  103302. (function (SimplificationType) {
  103303. /** Quadratic error decimation */
  103304. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  103305. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  103306. var DecimationTriangle = /** @class */ (function () {
  103307. function DecimationTriangle(vertices) {
  103308. this.vertices = vertices;
  103309. this.error = new Array(4);
  103310. this.deleted = false;
  103311. this.isDirty = false;
  103312. this.deletePending = false;
  103313. this.borderFactor = 0;
  103314. }
  103315. return DecimationTriangle;
  103316. }());
  103317. var DecimationVertex = /** @class */ (function () {
  103318. function DecimationVertex(position, id) {
  103319. this.position = position;
  103320. this.id = id;
  103321. this.isBorder = true;
  103322. this.q = new QuadraticMatrix();
  103323. this.triangleCount = 0;
  103324. this.triangleStart = 0;
  103325. this.originalOffsets = [];
  103326. }
  103327. DecimationVertex.prototype.updatePosition = function (newPosition) {
  103328. this.position.copyFrom(newPosition);
  103329. };
  103330. return DecimationVertex;
  103331. }());
  103332. var QuadraticMatrix = /** @class */ (function () {
  103333. function QuadraticMatrix(data) {
  103334. this.data = new Array(10);
  103335. for (var i = 0; i < 10; ++i) {
  103336. if (data && data[i]) {
  103337. this.data[i] = data[i];
  103338. }
  103339. else {
  103340. this.data[i] = 0;
  103341. }
  103342. }
  103343. }
  103344. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  103345. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  103346. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  103347. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  103348. return det;
  103349. };
  103350. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  103351. for (var i = 0; i < 10; ++i) {
  103352. this.data[i] += matrix.data[i];
  103353. }
  103354. };
  103355. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  103356. for (var i = 0; i < 10; ++i) {
  103357. this.data[i] += data[i];
  103358. }
  103359. };
  103360. QuadraticMatrix.prototype.add = function (matrix) {
  103361. var m = new QuadraticMatrix();
  103362. for (var i = 0; i < 10; ++i) {
  103363. m.data[i] = this.data[i] + matrix.data[i];
  103364. }
  103365. return m;
  103366. };
  103367. QuadraticMatrix.FromData = function (a, b, c, d) {
  103368. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  103369. };
  103370. //returning an array to avoid garbage collection
  103371. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  103372. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  103373. };
  103374. return QuadraticMatrix;
  103375. }());
  103376. var Reference = /** @class */ (function () {
  103377. function Reference(vertexId, triangleId) {
  103378. this.vertexId = vertexId;
  103379. this.triangleId = triangleId;
  103380. }
  103381. return Reference;
  103382. }());
  103383. /**
  103384. * An implementation of the Quadratic Error simplification algorithm.
  103385. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  103386. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  103387. * @author RaananW
  103388. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  103389. */
  103390. var QuadraticErrorSimplification = /** @class */ (function () {
  103391. function QuadraticErrorSimplification(_mesh) {
  103392. this._mesh = _mesh;
  103393. this.syncIterations = 5000;
  103394. this.aggressiveness = 7;
  103395. this.decimationIterations = 100;
  103396. this.boundingBoxEpsilon = BABYLON.Epsilon;
  103397. }
  103398. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  103399. var _this = this;
  103400. this.initDecimatedMesh();
  103401. //iterating through the submeshes array, one after the other.
  103402. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  103403. _this.initWithMesh(loop.index, function () {
  103404. _this.runDecimation(settings, loop.index, function () {
  103405. loop.executeNext();
  103406. });
  103407. }, settings.optimizeMesh);
  103408. }, function () {
  103409. setTimeout(function () {
  103410. successCallback(_this._reconstructedMesh);
  103411. }, 0);
  103412. });
  103413. };
  103414. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  103415. var _this = this;
  103416. var targetCount = ~~(this.triangles.length * settings.quality);
  103417. var deletedTriangles = 0;
  103418. var triangleCount = this.triangles.length;
  103419. var iterationFunction = function (iteration, callback) {
  103420. setTimeout(function () {
  103421. if (iteration % 5 === 0) {
  103422. _this.updateMesh(iteration === 0);
  103423. }
  103424. for (var i = 0; i < _this.triangles.length; ++i) {
  103425. _this.triangles[i].isDirty = false;
  103426. }
  103427. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  103428. var trianglesIterator = function (i) {
  103429. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  103430. var t = _this.triangles[tIdx];
  103431. if (!t)
  103432. return;
  103433. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  103434. return;
  103435. }
  103436. for (var j = 0; j < 3; ++j) {
  103437. if (t.error[j] < threshold) {
  103438. var deleted0 = [];
  103439. var deleted1 = [];
  103440. var v0 = t.vertices[j];
  103441. var v1 = t.vertices[(j + 1) % 3];
  103442. if (v0.isBorder || v1.isBorder)
  103443. continue;
  103444. var p = BABYLON.Vector3.Zero();
  103445. var n = BABYLON.Vector3.Zero();
  103446. var uv = BABYLON.Vector2.Zero();
  103447. var color = new BABYLON.Color4(0, 0, 0, 1);
  103448. _this.calculateError(v0, v1, p, n, uv, color);
  103449. var delTr = new Array();
  103450. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  103451. continue;
  103452. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  103453. continue;
  103454. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  103455. continue;
  103456. var uniqueArray = new Array();
  103457. delTr.forEach(function (deletedT) {
  103458. if (uniqueArray.indexOf(deletedT) === -1) {
  103459. deletedT.deletePending = true;
  103460. uniqueArray.push(deletedT);
  103461. }
  103462. });
  103463. if (uniqueArray.length % 2 !== 0) {
  103464. continue;
  103465. }
  103466. v0.q = v1.q.add(v0.q);
  103467. v0.updatePosition(p);
  103468. var tStart = _this.references.length;
  103469. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  103470. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  103471. var tCount = _this.references.length - tStart;
  103472. if (tCount <= v0.triangleCount) {
  103473. if (tCount) {
  103474. for (var c = 0; c < tCount; c++) {
  103475. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  103476. }
  103477. }
  103478. }
  103479. else {
  103480. v0.triangleStart = tStart;
  103481. }
  103482. v0.triangleCount = tCount;
  103483. break;
  103484. }
  103485. }
  103486. };
  103487. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  103488. }, 0);
  103489. };
  103490. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  103491. if (triangleCount - deletedTriangles <= targetCount)
  103492. loop.breakLoop();
  103493. else {
  103494. iterationFunction(loop.index, function () {
  103495. loop.executeNext();
  103496. });
  103497. }
  103498. }, function () {
  103499. setTimeout(function () {
  103500. //reconstruct this part of the mesh
  103501. _this.reconstructMesh(submeshIndex);
  103502. successCallback();
  103503. }, 0);
  103504. });
  103505. };
  103506. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  103507. var _this = this;
  103508. this.vertices = [];
  103509. this.triangles = [];
  103510. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  103511. var indices = this._mesh.getIndices();
  103512. var submesh = this._mesh.subMeshes[submeshIndex];
  103513. var findInVertices = function (positionToSearch) {
  103514. if (optimizeMesh) {
  103515. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  103516. if (_this.vertices[ii].position.equals(positionToSearch)) {
  103517. return _this.vertices[ii];
  103518. }
  103519. }
  103520. }
  103521. return null;
  103522. };
  103523. var vertexReferences = [];
  103524. var vertexInit = function (i) {
  103525. if (!positionData) {
  103526. return;
  103527. }
  103528. var offset = i + submesh.verticesStart;
  103529. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  103530. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  103531. vertex.originalOffsets.push(offset);
  103532. if (vertex.id === _this.vertices.length) {
  103533. _this.vertices.push(vertex);
  103534. }
  103535. vertexReferences.push(vertex.id);
  103536. };
  103537. //var totalVertices = mesh.getTotalVertices();
  103538. var totalVertices = submesh.verticesCount;
  103539. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  103540. var indicesInit = function (i) {
  103541. if (!indices) {
  103542. return;
  103543. }
  103544. var offset = (submesh.indexStart / 3) + i;
  103545. var pos = (offset * 3);
  103546. var i0 = indices[pos + 0];
  103547. var i1 = indices[pos + 1];
  103548. var i2 = indices[pos + 2];
  103549. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  103550. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  103551. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  103552. var triangle = new DecimationTriangle([v0, v1, v2]);
  103553. triangle.originalOffset = pos;
  103554. _this.triangles.push(triangle);
  103555. };
  103556. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  103557. _this.init(callback);
  103558. });
  103559. });
  103560. };
  103561. QuadraticErrorSimplification.prototype.init = function (callback) {
  103562. var _this = this;
  103563. var triangleInit1 = function (i) {
  103564. var t = _this.triangles[i];
  103565. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  103566. for (var j = 0; j < 3; j++) {
  103567. 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))));
  103568. }
  103569. };
  103570. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  103571. var triangleInit2 = function (i) {
  103572. var t = _this.triangles[i];
  103573. for (var j = 0; j < 3; ++j) {
  103574. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  103575. }
  103576. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  103577. };
  103578. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  103579. callback();
  103580. });
  103581. });
  103582. };
  103583. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  103584. var newTriangles = [];
  103585. var i;
  103586. for (i = 0; i < this.vertices.length; ++i) {
  103587. this.vertices[i].triangleCount = 0;
  103588. }
  103589. var t;
  103590. var j;
  103591. for (i = 0; i < this.triangles.length; ++i) {
  103592. if (!this.triangles[i].deleted) {
  103593. t = this.triangles[i];
  103594. for (j = 0; j < 3; ++j) {
  103595. t.vertices[j].triangleCount = 1;
  103596. }
  103597. newTriangles.push(t);
  103598. }
  103599. }
  103600. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  103601. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  103602. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  103603. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  103604. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  103605. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  103606. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  103607. var vertexCount = 0;
  103608. for (i = 0; i < this.vertices.length; ++i) {
  103609. var vertex = this.vertices[i];
  103610. vertex.id = vertexCount;
  103611. if (vertex.triangleCount) {
  103612. vertex.originalOffsets.forEach(function (originalOffset) {
  103613. if (!normalData) {
  103614. return;
  103615. }
  103616. newPositionData.push(vertex.position.x);
  103617. newPositionData.push(vertex.position.y);
  103618. newPositionData.push(vertex.position.z);
  103619. newNormalData.push(normalData[originalOffset * 3]);
  103620. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  103621. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  103622. if (uvs && uvs.length) {
  103623. newUVsData.push(uvs[(originalOffset * 2)]);
  103624. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  103625. }
  103626. else if (colorsData && colorsData.length) {
  103627. newColorsData.push(colorsData[(originalOffset * 4)]);
  103628. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  103629. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  103630. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  103631. }
  103632. ++vertexCount;
  103633. });
  103634. }
  103635. }
  103636. var startingIndex = this._reconstructedMesh.getTotalIndices();
  103637. var startingVertex = this._reconstructedMesh.getTotalVertices();
  103638. var submeshesArray = this._reconstructedMesh.subMeshes;
  103639. this._reconstructedMesh.subMeshes = [];
  103640. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  103641. var originalIndices = this._mesh.getIndices();
  103642. for (i = 0; i < newTriangles.length; ++i) {
  103643. t = newTriangles[i]; //now get the new referencing point for each vertex
  103644. [0, 1, 2].forEach(function (idx) {
  103645. var id = originalIndices[t.originalOffset + idx];
  103646. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  103647. if (offset < 0)
  103648. offset = 0;
  103649. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  103650. });
  103651. }
  103652. //overwriting the old vertex buffers and indices.
  103653. this._reconstructedMesh.setIndices(newIndicesArray);
  103654. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  103655. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  103656. if (newUVsData.length > 0)
  103657. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  103658. if (newColorsData.length > 0)
  103659. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  103660. //create submesh
  103661. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  103662. if (submeshIndex > 0) {
  103663. this._reconstructedMesh.subMeshes = [];
  103664. submeshesArray.forEach(function (submesh) {
  103665. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  103666. });
  103667. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  103668. }
  103669. };
  103670. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  103671. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  103672. this._reconstructedMesh.material = this._mesh.material;
  103673. this._reconstructedMesh.parent = this._mesh.parent;
  103674. this._reconstructedMesh.isVisible = false;
  103675. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  103676. };
  103677. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  103678. for (var i = 0; i < vertex1.triangleCount; ++i) {
  103679. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  103680. if (t.deleted)
  103681. continue;
  103682. var s = this.references[vertex1.triangleStart + i].vertexId;
  103683. var v1 = t.vertices[(s + 1) % 3];
  103684. var v2 = t.vertices[(s + 2) % 3];
  103685. if ((v1 === vertex2 || v2 === vertex2)) {
  103686. deletedArray[i] = true;
  103687. delTr.push(t);
  103688. continue;
  103689. }
  103690. var d1 = v1.position.subtract(point);
  103691. d1 = d1.normalize();
  103692. var d2 = v2.position.subtract(point);
  103693. d2 = d2.normalize();
  103694. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  103695. return true;
  103696. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  103697. deletedArray[i] = false;
  103698. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  103699. return true;
  103700. }
  103701. return false;
  103702. };
  103703. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  103704. var newDeleted = deletedTriangles;
  103705. for (var i = 0; i < vertex.triangleCount; ++i) {
  103706. var ref = this.references[vertex.triangleStart + i];
  103707. var t = this.triangles[ref.triangleId];
  103708. if (t.deleted)
  103709. continue;
  103710. if (deletedArray[i] && t.deletePending) {
  103711. t.deleted = true;
  103712. newDeleted++;
  103713. continue;
  103714. }
  103715. t.vertices[ref.vertexId] = origVertex;
  103716. t.isDirty = true;
  103717. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  103718. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  103719. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  103720. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  103721. this.references.push(ref);
  103722. }
  103723. return newDeleted;
  103724. };
  103725. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  103726. for (var i = 0; i < this.vertices.length; ++i) {
  103727. var vCount = [];
  103728. var vId = [];
  103729. var v = this.vertices[i];
  103730. var j;
  103731. for (j = 0; j < v.triangleCount; ++j) {
  103732. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  103733. for (var ii = 0; ii < 3; ii++) {
  103734. var ofs = 0;
  103735. var vv = triangle.vertices[ii];
  103736. while (ofs < vCount.length) {
  103737. if (vId[ofs] === vv.id)
  103738. break;
  103739. ++ofs;
  103740. }
  103741. if (ofs === vCount.length) {
  103742. vCount.push(1);
  103743. vId.push(vv.id);
  103744. }
  103745. else {
  103746. vCount[ofs]++;
  103747. }
  103748. }
  103749. }
  103750. for (j = 0; j < vCount.length; ++j) {
  103751. if (vCount[j] === 1) {
  103752. this.vertices[vId[j]].isBorder = true;
  103753. }
  103754. else {
  103755. this.vertices[vId[j]].isBorder = false;
  103756. }
  103757. }
  103758. }
  103759. };
  103760. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  103761. if (identifyBorders === void 0) { identifyBorders = false; }
  103762. var i;
  103763. if (!identifyBorders) {
  103764. var newTrianglesVector = [];
  103765. for (i = 0; i < this.triangles.length; ++i) {
  103766. if (!this.triangles[i].deleted) {
  103767. newTrianglesVector.push(this.triangles[i]);
  103768. }
  103769. }
  103770. this.triangles = newTrianglesVector;
  103771. }
  103772. for (i = 0; i < this.vertices.length; ++i) {
  103773. this.vertices[i].triangleCount = 0;
  103774. this.vertices[i].triangleStart = 0;
  103775. }
  103776. var t;
  103777. var j;
  103778. var v;
  103779. for (i = 0; i < this.triangles.length; ++i) {
  103780. t = this.triangles[i];
  103781. for (j = 0; j < 3; ++j) {
  103782. v = t.vertices[j];
  103783. v.triangleCount++;
  103784. }
  103785. }
  103786. var tStart = 0;
  103787. for (i = 0; i < this.vertices.length; ++i) {
  103788. this.vertices[i].triangleStart = tStart;
  103789. tStart += this.vertices[i].triangleCount;
  103790. this.vertices[i].triangleCount = 0;
  103791. }
  103792. var newReferences = new Array(this.triangles.length * 3);
  103793. for (i = 0; i < this.triangles.length; ++i) {
  103794. t = this.triangles[i];
  103795. for (j = 0; j < 3; ++j) {
  103796. v = t.vertices[j];
  103797. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  103798. v.triangleCount++;
  103799. }
  103800. }
  103801. this.references = newReferences;
  103802. if (identifyBorders) {
  103803. this.identifyBorder();
  103804. }
  103805. };
  103806. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  103807. var x = point.x;
  103808. var y = point.y;
  103809. var z = point.z;
  103810. 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
  103811. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  103812. };
  103813. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  103814. var q = vertex1.q.add(vertex2.q);
  103815. var border = vertex1.isBorder && vertex2.isBorder;
  103816. var error = 0;
  103817. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  103818. if (qDet !== 0 && !border) {
  103819. if (!pointResult) {
  103820. pointResult = BABYLON.Vector3.Zero();
  103821. }
  103822. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  103823. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  103824. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  103825. error = this.vertexError(q, pointResult);
  103826. }
  103827. else {
  103828. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  103829. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  103830. var error1 = this.vertexError(q, vertex1.position);
  103831. var error2 = this.vertexError(q, vertex2.position);
  103832. var error3 = this.vertexError(q, p3);
  103833. error = Math.min(error1, error2, error3);
  103834. if (error === error1) {
  103835. if (pointResult) {
  103836. pointResult.copyFrom(vertex1.position);
  103837. }
  103838. }
  103839. else if (error === error2) {
  103840. if (pointResult) {
  103841. pointResult.copyFrom(vertex2.position);
  103842. }
  103843. }
  103844. else {
  103845. if (pointResult) {
  103846. pointResult.copyFrom(p3);
  103847. }
  103848. }
  103849. }
  103850. return error;
  103851. };
  103852. return QuadraticErrorSimplification;
  103853. }());
  103854. })(BABYLON || (BABYLON = {}));
  103855. //# sourceMappingURL=babylon.meshSimplification.js.map
  103856. var BABYLON;
  103857. (function (BABYLON) {
  103858. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  103859. get: function () {
  103860. if (!this._simplificationQueue) {
  103861. this._simplificationQueue = new BABYLON.SimplificationQueue();
  103862. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  103863. if (!component) {
  103864. component = new SimplicationQueueSceneComponent(this);
  103865. this._addComponent(component);
  103866. }
  103867. }
  103868. return this._simplificationQueue;
  103869. },
  103870. set: function (value) {
  103871. this._simplificationQueue = value;
  103872. },
  103873. enumerable: true,
  103874. configurable: true
  103875. });
  103876. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  103877. if (parallelProcessing === void 0) { parallelProcessing = true; }
  103878. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  103879. this.getScene().simplificationQueue.addTask({
  103880. settings: settings,
  103881. parallelProcessing: parallelProcessing,
  103882. mesh: this,
  103883. simplificationType: simplificationType,
  103884. successCallback: successCallback
  103885. });
  103886. return this;
  103887. };
  103888. /**
  103889. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  103890. * created in a scene
  103891. */
  103892. var SimplicationQueueSceneComponent = /** @class */ (function () {
  103893. /**
  103894. * Creates a new instance of the component for the given scene
  103895. * @param scene Defines the scene to register the component in
  103896. */
  103897. function SimplicationQueueSceneComponent(scene) {
  103898. /**
  103899. * The component name helpfull to identify the component in the list of scene components.
  103900. */
  103901. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  103902. this.scene = scene;
  103903. }
  103904. /**
  103905. * Registers the component in a given scene
  103906. */
  103907. SimplicationQueueSceneComponent.prototype.register = function () {
  103908. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  103909. };
  103910. /**
  103911. * Rebuilds the elements related to this component in case of
  103912. * context lost for instance.
  103913. */
  103914. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  103915. // Nothing to do for this component
  103916. };
  103917. /**
  103918. * Disposes the component and the associated ressources
  103919. */
  103920. SimplicationQueueSceneComponent.prototype.dispose = function () {
  103921. // Nothing to do for this component
  103922. };
  103923. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  103924. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  103925. this.scene._simplificationQueue.executeNext();
  103926. }
  103927. };
  103928. return SimplicationQueueSceneComponent;
  103929. }());
  103930. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  103931. })(BABYLON || (BABYLON = {}));
  103932. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  103933. var BABYLON;
  103934. (function (BABYLON) {
  103935. /**
  103936. * Class used to represent a specific level of detail of a mesh
  103937. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  103938. */
  103939. var MeshLODLevel = /** @class */ (function () {
  103940. /**
  103941. * Creates a new LOD level
  103942. * @param distance defines the distance where this level should star being displayed
  103943. * @param mesh defines the mesh to use to render this level
  103944. */
  103945. function MeshLODLevel(
  103946. /** Defines the distance where this level should star being displayed */
  103947. distance,
  103948. /** Defines the mesh to use to render this level */
  103949. mesh) {
  103950. this.distance = distance;
  103951. this.mesh = mesh;
  103952. }
  103953. return MeshLODLevel;
  103954. }());
  103955. BABYLON.MeshLODLevel = MeshLODLevel;
  103956. })(BABYLON || (BABYLON = {}));
  103957. //# sourceMappingURL=babylon.meshLODLevel.js.map
  103958. var BABYLON;
  103959. (function (BABYLON) {
  103960. /**
  103961. * Defines the root class used to create scene optimization to use with SceneOptimizer
  103962. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103963. */
  103964. var SceneOptimization = /** @class */ (function () {
  103965. /**
  103966. * Creates the SceneOptimization object
  103967. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  103968. * @param desc defines the description associated with the optimization
  103969. */
  103970. function SceneOptimization(
  103971. /**
  103972. * Defines the priority of this optimization (0 by default which means first in the list)
  103973. */
  103974. priority) {
  103975. if (priority === void 0) { priority = 0; }
  103976. this.priority = priority;
  103977. }
  103978. /**
  103979. * Gets a string describing the action executed by the current optimization
  103980. * @returns description string
  103981. */
  103982. SceneOptimization.prototype.getDescription = function () {
  103983. return "";
  103984. };
  103985. /**
  103986. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103987. * @param scene defines the current scene where to apply this optimization
  103988. * @param optimizer defines the current optimizer
  103989. * @returns true if everything that can be done was applied
  103990. */
  103991. SceneOptimization.prototype.apply = function (scene, optimizer) {
  103992. return true;
  103993. };
  103994. ;
  103995. return SceneOptimization;
  103996. }());
  103997. BABYLON.SceneOptimization = SceneOptimization;
  103998. /**
  103999. * Defines an optimization used to reduce the size of render target textures
  104000. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104001. */
  104002. var TextureOptimization = /** @class */ (function (_super) {
  104003. __extends(TextureOptimization, _super);
  104004. /**
  104005. * Creates the TextureOptimization object
  104006. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  104007. * @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
  104008. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  104009. */
  104010. function TextureOptimization(
  104011. /**
  104012. * Defines the priority of this optimization (0 by default which means first in the list)
  104013. */
  104014. priority,
  104015. /**
  104016. * 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
  104017. */
  104018. maximumSize,
  104019. /**
  104020. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  104021. */
  104022. step) {
  104023. if (priority === void 0) { priority = 0; }
  104024. if (maximumSize === void 0) { maximumSize = 1024; }
  104025. if (step === void 0) { step = 0.5; }
  104026. var _this = _super.call(this, priority) || this;
  104027. _this.priority = priority;
  104028. _this.maximumSize = maximumSize;
  104029. _this.step = step;
  104030. return _this;
  104031. }
  104032. /**
  104033. * Gets a string describing the action executed by the current optimization
  104034. * @returns description string
  104035. */
  104036. TextureOptimization.prototype.getDescription = function () {
  104037. return "Reducing render target texture size to " + this.maximumSize;
  104038. };
  104039. /**
  104040. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104041. * @param scene defines the current scene where to apply this optimization
  104042. * @param optimizer defines the current optimizer
  104043. * @returns true if everything that can be done was applied
  104044. */
  104045. TextureOptimization.prototype.apply = function (scene, optimizer) {
  104046. var allDone = true;
  104047. for (var index = 0; index < scene.textures.length; index++) {
  104048. var texture = scene.textures[index];
  104049. if (!texture.canRescale || texture.getContext) {
  104050. continue;
  104051. }
  104052. var currentSize = texture.getSize();
  104053. var maxDimension = Math.max(currentSize.width, currentSize.height);
  104054. if (maxDimension > this.maximumSize) {
  104055. texture.scale(this.step);
  104056. allDone = false;
  104057. }
  104058. }
  104059. return allDone;
  104060. };
  104061. return TextureOptimization;
  104062. }(SceneOptimization));
  104063. BABYLON.TextureOptimization = TextureOptimization;
  104064. /**
  104065. * Defines an optimization used to increase or decrease the rendering resolution
  104066. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104067. */
  104068. var HardwareScalingOptimization = /** @class */ (function (_super) {
  104069. __extends(HardwareScalingOptimization, _super);
  104070. /**
  104071. * Creates the HardwareScalingOptimization object
  104072. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  104073. * @param maximumScale defines the maximum scale to use (2 by default)
  104074. * @param step defines the step to use between two passes (0.5 by default)
  104075. */
  104076. function HardwareScalingOptimization(
  104077. /**
  104078. * Defines the priority of this optimization (0 by default which means first in the list)
  104079. */
  104080. priority,
  104081. /**
  104082. * Defines the maximum scale to use (2 by default)
  104083. */
  104084. maximumScale,
  104085. /**
  104086. * Defines the step to use between two passes (0.5 by default)
  104087. */
  104088. step) {
  104089. if (priority === void 0) { priority = 0; }
  104090. if (maximumScale === void 0) { maximumScale = 2; }
  104091. if (step === void 0) { step = 0.25; }
  104092. var _this = _super.call(this, priority) || this;
  104093. _this.priority = priority;
  104094. _this.maximumScale = maximumScale;
  104095. _this.step = step;
  104096. _this._currentScale = -1;
  104097. _this._directionOffset = 1;
  104098. return _this;
  104099. }
  104100. /**
  104101. * Gets a string describing the action executed by the current optimization
  104102. * @return description string
  104103. */
  104104. HardwareScalingOptimization.prototype.getDescription = function () {
  104105. return "Setting hardware scaling level to " + this._currentScale;
  104106. };
  104107. /**
  104108. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104109. * @param scene defines the current scene where to apply this optimization
  104110. * @param optimizer defines the current optimizer
  104111. * @returns true if everything that can be done was applied
  104112. */
  104113. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  104114. if (this._currentScale === -1) {
  104115. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  104116. if (this._currentScale > this.maximumScale) {
  104117. this._directionOffset = -1;
  104118. }
  104119. }
  104120. this._currentScale += this._directionOffset * this.step;
  104121. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  104122. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  104123. };
  104124. ;
  104125. return HardwareScalingOptimization;
  104126. }(SceneOptimization));
  104127. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  104128. /**
  104129. * Defines an optimization used to remove shadows
  104130. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104131. */
  104132. var ShadowsOptimization = /** @class */ (function (_super) {
  104133. __extends(ShadowsOptimization, _super);
  104134. function ShadowsOptimization() {
  104135. return _super !== null && _super.apply(this, arguments) || this;
  104136. }
  104137. /**
  104138. * Gets a string describing the action executed by the current optimization
  104139. * @return description string
  104140. */
  104141. ShadowsOptimization.prototype.getDescription = function () {
  104142. return "Turning shadows on/off";
  104143. };
  104144. /**
  104145. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104146. * @param scene defines the current scene where to apply this optimization
  104147. * @param optimizer defines the current optimizer
  104148. * @returns true if everything that can be done was applied
  104149. */
  104150. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  104151. scene.shadowsEnabled = optimizer.isInImprovementMode;
  104152. return true;
  104153. };
  104154. ;
  104155. return ShadowsOptimization;
  104156. }(SceneOptimization));
  104157. BABYLON.ShadowsOptimization = ShadowsOptimization;
  104158. /**
  104159. * Defines an optimization used to turn post-processes off
  104160. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104161. */
  104162. var PostProcessesOptimization = /** @class */ (function (_super) {
  104163. __extends(PostProcessesOptimization, _super);
  104164. function PostProcessesOptimization() {
  104165. return _super !== null && _super.apply(this, arguments) || this;
  104166. }
  104167. /**
  104168. * Gets a string describing the action executed by the current optimization
  104169. * @return description string
  104170. */
  104171. PostProcessesOptimization.prototype.getDescription = function () {
  104172. return "Turning post-processes on/off";
  104173. };
  104174. /**
  104175. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104176. * @param scene defines the current scene where to apply this optimization
  104177. * @param optimizer defines the current optimizer
  104178. * @returns true if everything that can be done was applied
  104179. */
  104180. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  104181. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  104182. return true;
  104183. };
  104184. ;
  104185. return PostProcessesOptimization;
  104186. }(SceneOptimization));
  104187. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  104188. /**
  104189. * Defines an optimization used to turn lens flares off
  104190. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104191. */
  104192. var LensFlaresOptimization = /** @class */ (function (_super) {
  104193. __extends(LensFlaresOptimization, _super);
  104194. function LensFlaresOptimization() {
  104195. return _super !== null && _super.apply(this, arguments) || this;
  104196. }
  104197. /**
  104198. * Gets a string describing the action executed by the current optimization
  104199. * @return description string
  104200. */
  104201. LensFlaresOptimization.prototype.getDescription = function () {
  104202. return "Turning lens flares on/off";
  104203. };
  104204. /**
  104205. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104206. * @param scene defines the current scene where to apply this optimization
  104207. * @param optimizer defines the current optimizer
  104208. * @returns true if everything that can be done was applied
  104209. */
  104210. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  104211. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  104212. return true;
  104213. };
  104214. ;
  104215. return LensFlaresOptimization;
  104216. }(SceneOptimization));
  104217. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  104218. /**
  104219. * Defines an optimization based on user defined callback.
  104220. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104221. */
  104222. var CustomOptimization = /** @class */ (function (_super) {
  104223. __extends(CustomOptimization, _super);
  104224. function CustomOptimization() {
  104225. return _super !== null && _super.apply(this, arguments) || this;
  104226. }
  104227. /**
  104228. * Gets a string describing the action executed by the current optimization
  104229. * @returns description string
  104230. */
  104231. CustomOptimization.prototype.getDescription = function () {
  104232. if (this.onGetDescription) {
  104233. return this.onGetDescription();
  104234. }
  104235. return "Running user defined callback";
  104236. };
  104237. /**
  104238. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104239. * @param scene defines the current scene where to apply this optimization
  104240. * @param optimizer defines the current optimizer
  104241. * @returns true if everything that can be done was applied
  104242. */
  104243. CustomOptimization.prototype.apply = function (scene, optimizer) {
  104244. if (this.onApply) {
  104245. return this.onApply(scene, optimizer);
  104246. }
  104247. return true;
  104248. };
  104249. ;
  104250. return CustomOptimization;
  104251. }(SceneOptimization));
  104252. BABYLON.CustomOptimization = CustomOptimization;
  104253. /**
  104254. * Defines an optimization used to turn particles off
  104255. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104256. */
  104257. var ParticlesOptimization = /** @class */ (function (_super) {
  104258. __extends(ParticlesOptimization, _super);
  104259. function ParticlesOptimization() {
  104260. return _super !== null && _super.apply(this, arguments) || this;
  104261. }
  104262. /**
  104263. * Gets a string describing the action executed by the current optimization
  104264. * @return description string
  104265. */
  104266. ParticlesOptimization.prototype.getDescription = function () {
  104267. return "Turning particles on/off";
  104268. };
  104269. /**
  104270. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104271. * @param scene defines the current scene where to apply this optimization
  104272. * @param optimizer defines the current optimizer
  104273. * @returns true if everything that can be done was applied
  104274. */
  104275. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  104276. scene.particlesEnabled = optimizer.isInImprovementMode;
  104277. return true;
  104278. };
  104279. ;
  104280. return ParticlesOptimization;
  104281. }(SceneOptimization));
  104282. BABYLON.ParticlesOptimization = ParticlesOptimization;
  104283. /**
  104284. * Defines an optimization used to turn render targets off
  104285. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104286. */
  104287. var RenderTargetsOptimization = /** @class */ (function (_super) {
  104288. __extends(RenderTargetsOptimization, _super);
  104289. function RenderTargetsOptimization() {
  104290. return _super !== null && _super.apply(this, arguments) || this;
  104291. }
  104292. /**
  104293. * Gets a string describing the action executed by the current optimization
  104294. * @return description string
  104295. */
  104296. RenderTargetsOptimization.prototype.getDescription = function () {
  104297. return "Turning render targets off";
  104298. };
  104299. /**
  104300. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104301. * @param scene defines the current scene where to apply this optimization
  104302. * @param optimizer defines the current optimizer
  104303. * @returns true if everything that can be done was applied
  104304. */
  104305. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  104306. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  104307. return true;
  104308. };
  104309. ;
  104310. return RenderTargetsOptimization;
  104311. }(SceneOptimization));
  104312. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  104313. /**
  104314. * Defines an optimization used to merge meshes with compatible materials
  104315. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104316. */
  104317. var MergeMeshesOptimization = /** @class */ (function (_super) {
  104318. __extends(MergeMeshesOptimization, _super);
  104319. function MergeMeshesOptimization() {
  104320. var _this = _super !== null && _super.apply(this, arguments) || this;
  104321. _this._canBeMerged = function (abstractMesh) {
  104322. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  104323. return false;
  104324. }
  104325. var mesh = abstractMesh;
  104326. if (mesh.isDisposed()) {
  104327. return false;
  104328. }
  104329. if (!mesh.isVisible || !mesh.isEnabled()) {
  104330. return false;
  104331. }
  104332. if (mesh.instances.length > 0) {
  104333. return false;
  104334. }
  104335. if (mesh.skeleton || mesh.hasLODLevels) {
  104336. return false;
  104337. }
  104338. return true;
  104339. };
  104340. return _this;
  104341. }
  104342. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  104343. /**
  104344. * Gets or sets a boolean which defines if optimization octree has to be updated
  104345. */
  104346. get: function () {
  104347. return MergeMeshesOptimization._UpdateSelectionTree;
  104348. },
  104349. /**
  104350. * Gets or sets a boolean which defines if optimization octree has to be updated
  104351. */
  104352. set: function (value) {
  104353. MergeMeshesOptimization._UpdateSelectionTree = value;
  104354. },
  104355. enumerable: true,
  104356. configurable: true
  104357. });
  104358. /**
  104359. * Gets a string describing the action executed by the current optimization
  104360. * @return description string
  104361. */
  104362. MergeMeshesOptimization.prototype.getDescription = function () {
  104363. return "Merging similar meshes together";
  104364. };
  104365. /**
  104366. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  104367. * @param scene defines the current scene where to apply this optimization
  104368. * @param optimizer defines the current optimizer
  104369. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  104370. * @returns true if everything that can be done was applied
  104371. */
  104372. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  104373. var globalPool = scene.meshes.slice(0);
  104374. var globalLength = globalPool.length;
  104375. for (var index = 0; index < globalLength; index++) {
  104376. var currentPool = new Array();
  104377. var current = globalPool[index];
  104378. // Checks
  104379. if (!this._canBeMerged(current)) {
  104380. continue;
  104381. }
  104382. currentPool.push(current);
  104383. // Find compatible meshes
  104384. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  104385. var otherMesh = globalPool[subIndex];
  104386. if (!this._canBeMerged(otherMesh)) {
  104387. continue;
  104388. }
  104389. if (otherMesh.material !== current.material) {
  104390. continue;
  104391. }
  104392. if (otherMesh.checkCollisions !== current.checkCollisions) {
  104393. continue;
  104394. }
  104395. currentPool.push(otherMesh);
  104396. globalLength--;
  104397. globalPool.splice(subIndex, 1);
  104398. subIndex--;
  104399. }
  104400. if (currentPool.length < 2) {
  104401. continue;
  104402. }
  104403. // Merge meshes
  104404. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  104405. }
  104406. // Call the octree system optimization if it is defined.
  104407. var sceneAsAny = scene;
  104408. if (sceneAsAny.createOrUpdateSelectionOctree) {
  104409. if (updateSelectionTree != undefined) {
  104410. if (updateSelectionTree) {
  104411. sceneAsAny.createOrUpdateSelectionOctree();
  104412. }
  104413. }
  104414. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  104415. sceneAsAny.createOrUpdateSelectionOctree();
  104416. }
  104417. }
  104418. return true;
  104419. };
  104420. ;
  104421. MergeMeshesOptimization._UpdateSelectionTree = false;
  104422. return MergeMeshesOptimization;
  104423. }(SceneOptimization));
  104424. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  104425. /**
  104426. * Defines a list of options used by SceneOptimizer
  104427. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104428. */
  104429. var SceneOptimizerOptions = /** @class */ (function () {
  104430. /**
  104431. * Creates a new list of options used by SceneOptimizer
  104432. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  104433. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  104434. */
  104435. function SceneOptimizerOptions(
  104436. /**
  104437. * Defines the target frame rate to reach (60 by default)
  104438. */
  104439. targetFrameRate,
  104440. /**
  104441. * Defines the interval between two checkes (2000ms by default)
  104442. */
  104443. trackerDuration) {
  104444. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  104445. if (trackerDuration === void 0) { trackerDuration = 2000; }
  104446. this.targetFrameRate = targetFrameRate;
  104447. this.trackerDuration = trackerDuration;
  104448. /**
  104449. * Gets the list of optimizations to apply
  104450. */
  104451. this.optimizations = new Array();
  104452. }
  104453. /**
  104454. * Add a new optimization
  104455. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  104456. * @returns the current SceneOptimizerOptions
  104457. */
  104458. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  104459. this.optimizations.push(optimization);
  104460. return this;
  104461. };
  104462. /**
  104463. * Add a new custom optimization
  104464. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  104465. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  104466. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  104467. * @returns the current SceneOptimizerOptions
  104468. */
  104469. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  104470. if (priority === void 0) { priority = 0; }
  104471. var optimization = new CustomOptimization(priority);
  104472. optimization.onApply = onApply;
  104473. optimization.onGetDescription = onGetDescription;
  104474. this.optimizations.push(optimization);
  104475. return this;
  104476. };
  104477. /**
  104478. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  104479. * @param targetFrameRate defines the target frame rate (60 by default)
  104480. * @returns a SceneOptimizerOptions object
  104481. */
  104482. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  104483. var result = new SceneOptimizerOptions(targetFrameRate);
  104484. var priority = 0;
  104485. result.addOptimization(new MergeMeshesOptimization(priority));
  104486. result.addOptimization(new ShadowsOptimization(priority));
  104487. result.addOptimization(new LensFlaresOptimization(priority));
  104488. // Next priority
  104489. priority++;
  104490. result.addOptimization(new PostProcessesOptimization(priority));
  104491. result.addOptimization(new ParticlesOptimization(priority));
  104492. // Next priority
  104493. priority++;
  104494. result.addOptimization(new TextureOptimization(priority, 1024));
  104495. return result;
  104496. };
  104497. /**
  104498. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  104499. * @param targetFrameRate defines the target frame rate (60 by default)
  104500. * @returns a SceneOptimizerOptions object
  104501. */
  104502. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  104503. var result = new SceneOptimizerOptions(targetFrameRate);
  104504. var priority = 0;
  104505. result.addOptimization(new MergeMeshesOptimization(priority));
  104506. result.addOptimization(new ShadowsOptimization(priority));
  104507. result.addOptimization(new LensFlaresOptimization(priority));
  104508. // Next priority
  104509. priority++;
  104510. result.addOptimization(new PostProcessesOptimization(priority));
  104511. result.addOptimization(new ParticlesOptimization(priority));
  104512. // Next priority
  104513. priority++;
  104514. result.addOptimization(new TextureOptimization(priority, 512));
  104515. // Next priority
  104516. priority++;
  104517. result.addOptimization(new RenderTargetsOptimization(priority));
  104518. // Next priority
  104519. priority++;
  104520. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  104521. return result;
  104522. };
  104523. /**
  104524. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  104525. * @param targetFrameRate defines the target frame rate (60 by default)
  104526. * @returns a SceneOptimizerOptions object
  104527. */
  104528. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  104529. var result = new SceneOptimizerOptions(targetFrameRate);
  104530. var priority = 0;
  104531. result.addOptimization(new MergeMeshesOptimization(priority));
  104532. result.addOptimization(new ShadowsOptimization(priority));
  104533. result.addOptimization(new LensFlaresOptimization(priority));
  104534. // Next priority
  104535. priority++;
  104536. result.addOptimization(new PostProcessesOptimization(priority));
  104537. result.addOptimization(new ParticlesOptimization(priority));
  104538. // Next priority
  104539. priority++;
  104540. result.addOptimization(new TextureOptimization(priority, 256));
  104541. // Next priority
  104542. priority++;
  104543. result.addOptimization(new RenderTargetsOptimization(priority));
  104544. // Next priority
  104545. priority++;
  104546. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  104547. return result;
  104548. };
  104549. return SceneOptimizerOptions;
  104550. }());
  104551. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  104552. /**
  104553. * Class used to run optimizations in order to reach a target frame rate
  104554. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104555. */
  104556. var SceneOptimizer = /** @class */ (function () {
  104557. /**
  104558. * Creates a new SceneOptimizer
  104559. * @param scene defines the scene to work on
  104560. * @param options defines the options to use with the SceneOptimizer
  104561. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  104562. * @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)
  104563. */
  104564. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  104565. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  104566. if (improvementMode === void 0) { improvementMode = false; }
  104567. var _this = this;
  104568. this._isRunning = false;
  104569. this._currentPriorityLevel = 0;
  104570. this._targetFrameRate = 60;
  104571. this._trackerDuration = 2000;
  104572. this._currentFrameRate = 0;
  104573. this._improvementMode = false;
  104574. /**
  104575. * Defines an observable called when the optimizer reaches the target frame rate
  104576. */
  104577. this.onSuccessObservable = new BABYLON.Observable();
  104578. /**
  104579. * Defines an observable called when the optimizer enables an optimization
  104580. */
  104581. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  104582. /**
  104583. * Defines an observable called when the optimizer is not able to reach the target frame rate
  104584. */
  104585. this.onFailureObservable = new BABYLON.Observable();
  104586. if (!options) {
  104587. this._options = new SceneOptimizerOptions();
  104588. }
  104589. else {
  104590. this._options = options;
  104591. }
  104592. if (this._options.targetFrameRate) {
  104593. this._targetFrameRate = this._options.targetFrameRate;
  104594. }
  104595. if (this._options.trackerDuration) {
  104596. this._trackerDuration = this._options.trackerDuration;
  104597. }
  104598. if (autoGeneratePriorities) {
  104599. var priority = 0;
  104600. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  104601. var optim = _a[_i];
  104602. optim.priority = priority++;
  104603. }
  104604. }
  104605. this._improvementMode = improvementMode;
  104606. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  104607. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  104608. _this._sceneDisposeObserver = null;
  104609. _this.dispose();
  104610. });
  104611. }
  104612. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  104613. /**
  104614. * Gets a boolean indicating if the optimizer is in improvement mode
  104615. */
  104616. get: function () {
  104617. return this._improvementMode;
  104618. },
  104619. enumerable: true,
  104620. configurable: true
  104621. });
  104622. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  104623. /**
  104624. * Gets the current priority level (0 at start)
  104625. */
  104626. get: function () {
  104627. return this._currentPriorityLevel;
  104628. },
  104629. enumerable: true,
  104630. configurable: true
  104631. });
  104632. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  104633. /**
  104634. * Gets the current frame rate checked by the SceneOptimizer
  104635. */
  104636. get: function () {
  104637. return this._currentFrameRate;
  104638. },
  104639. enumerable: true,
  104640. configurable: true
  104641. });
  104642. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  104643. /**
  104644. * Gets or sets the current target frame rate (60 by default)
  104645. */
  104646. get: function () {
  104647. return this._targetFrameRate;
  104648. },
  104649. /**
  104650. * Gets or sets the current target frame rate (60 by default)
  104651. */
  104652. set: function (value) {
  104653. this._targetFrameRate = value;
  104654. },
  104655. enumerable: true,
  104656. configurable: true
  104657. });
  104658. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  104659. /**
  104660. * Gets or sets the current interval between two checks (every 2000ms by default)
  104661. */
  104662. get: function () {
  104663. return this._trackerDuration;
  104664. },
  104665. /**
  104666. * Gets or sets the current interval between two checks (every 2000ms by default)
  104667. */
  104668. set: function (value) {
  104669. this._trackerDuration = value;
  104670. },
  104671. enumerable: true,
  104672. configurable: true
  104673. });
  104674. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  104675. /**
  104676. * Gets the list of active optimizations
  104677. */
  104678. get: function () {
  104679. return this._options.optimizations;
  104680. },
  104681. enumerable: true,
  104682. configurable: true
  104683. });
  104684. /**
  104685. * Stops the current optimizer
  104686. */
  104687. SceneOptimizer.prototype.stop = function () {
  104688. this._isRunning = false;
  104689. };
  104690. /**
  104691. * Reset the optimizer to initial step (current priority level = 0)
  104692. */
  104693. SceneOptimizer.prototype.reset = function () {
  104694. this._currentPriorityLevel = 0;
  104695. };
  104696. /**
  104697. * Start the optimizer. By default it will try to reach a specific framerate
  104698. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  104699. */
  104700. SceneOptimizer.prototype.start = function () {
  104701. var _this = this;
  104702. if (this._isRunning) {
  104703. return;
  104704. }
  104705. this._isRunning = true;
  104706. // Let's wait for the scene to be ready before running our check
  104707. this._scene.executeWhenReady(function () {
  104708. setTimeout(function () {
  104709. _this._checkCurrentState();
  104710. }, _this._trackerDuration);
  104711. });
  104712. };
  104713. SceneOptimizer.prototype._checkCurrentState = function () {
  104714. var _this = this;
  104715. if (!this._isRunning) {
  104716. return;
  104717. }
  104718. var scene = this._scene;
  104719. var options = this._options;
  104720. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  104721. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  104722. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  104723. this._isRunning = false;
  104724. this.onSuccessObservable.notifyObservers(this);
  104725. return;
  104726. }
  104727. // Apply current level of optimizations
  104728. var allDone = true;
  104729. var noOptimizationApplied = true;
  104730. for (var index = 0; index < options.optimizations.length; index++) {
  104731. var optimization = options.optimizations[index];
  104732. if (optimization.priority === this._currentPriorityLevel) {
  104733. noOptimizationApplied = false;
  104734. allDone = allDone && optimization.apply(scene, this);
  104735. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  104736. }
  104737. }
  104738. // If no optimization was applied, this is a failure :(
  104739. if (noOptimizationApplied) {
  104740. this._isRunning = false;
  104741. this.onFailureObservable.notifyObservers(this);
  104742. return;
  104743. }
  104744. // If all optimizations were done, move to next level
  104745. if (allDone) {
  104746. this._currentPriorityLevel++;
  104747. }
  104748. // Let's the system running for a specific amount of time before checking FPS
  104749. scene.executeWhenReady(function () {
  104750. setTimeout(function () {
  104751. _this._checkCurrentState();
  104752. }, _this._trackerDuration);
  104753. });
  104754. };
  104755. /**
  104756. * Release all resources
  104757. */
  104758. SceneOptimizer.prototype.dispose = function () {
  104759. this.stop();
  104760. this.onSuccessObservable.clear();
  104761. this.onFailureObservable.clear();
  104762. this.onNewOptimizationAppliedObservable.clear();
  104763. if (this._sceneDisposeObserver) {
  104764. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  104765. }
  104766. };
  104767. /**
  104768. * Helper function to create a SceneOptimizer with one single line of code
  104769. * @param scene defines the scene to work on
  104770. * @param options defines the options to use with the SceneOptimizer
  104771. * @param onSuccess defines a callback to call on success
  104772. * @param onFailure defines a callback to call on failure
  104773. * @returns the new SceneOptimizer object
  104774. */
  104775. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  104776. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  104777. if (onSuccess) {
  104778. optimizer.onSuccessObservable.add(function () {
  104779. onSuccess();
  104780. });
  104781. }
  104782. if (onFailure) {
  104783. optimizer.onFailureObservable.add(function () {
  104784. onFailure();
  104785. });
  104786. }
  104787. optimizer.start();
  104788. return optimizer;
  104789. };
  104790. return SceneOptimizer;
  104791. }());
  104792. BABYLON.SceneOptimizer = SceneOptimizer;
  104793. })(BABYLON || (BABYLON = {}));
  104794. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  104795. var BABYLON;
  104796. (function (BABYLON) {
  104797. /**
  104798. * Gets the outline renderer associated with the scene
  104799. * @returns a OutlineRenderer
  104800. */
  104801. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  104802. if (!this._outlineRenderer) {
  104803. this._outlineRenderer = new OutlineRenderer(this);
  104804. }
  104805. return this._outlineRenderer;
  104806. };
  104807. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  104808. get: function () {
  104809. return this._renderOutline;
  104810. },
  104811. set: function (value) {
  104812. if (value) {
  104813. // Lazy Load the component.
  104814. this.getScene().getOutlineRenderer();
  104815. }
  104816. this._renderOutline = value;
  104817. },
  104818. enumerable: true,
  104819. configurable: true
  104820. });
  104821. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  104822. get: function () {
  104823. return this._renderOverlay;
  104824. },
  104825. set: function (value) {
  104826. if (value) {
  104827. // Lazy Load the component.
  104828. this.getScene().getOutlineRenderer();
  104829. }
  104830. this._renderOverlay = value;
  104831. },
  104832. enumerable: true,
  104833. configurable: true
  104834. });
  104835. /**
  104836. * This class is responsible to draw bothe outline/overlay of meshes.
  104837. * It should not be used directly but through the available method on mesh.
  104838. */
  104839. var OutlineRenderer = /** @class */ (function () {
  104840. /**
  104841. * Instantiates a new outline renderer. (There could be only one per scene).
  104842. * @param scene Defines the scene it belongs to
  104843. */
  104844. function OutlineRenderer(scene) {
  104845. /**
  104846. * The name of the component. Each component must have a unique name.
  104847. */
  104848. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  104849. /**
  104850. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  104851. */
  104852. this.zOffset = 1;
  104853. this.scene = scene;
  104854. this._engine = scene.getEngine();
  104855. this.scene._addComponent(this);
  104856. }
  104857. /**
  104858. * Register the component to one instance of a scene.
  104859. */
  104860. OutlineRenderer.prototype.register = function () {
  104861. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  104862. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  104863. };
  104864. /**
  104865. * Rebuilds the elements related to this component in case of
  104866. * context lost for instance.
  104867. */
  104868. OutlineRenderer.prototype.rebuild = function () {
  104869. // Nothing to do here.
  104870. };
  104871. /**
  104872. * Disposes the component and the associated ressources.
  104873. */
  104874. OutlineRenderer.prototype.dispose = function () {
  104875. // Nothing to do here.
  104876. };
  104877. /**
  104878. * Renders the outline in the canvas.
  104879. * @param subMesh Defines the sumesh to render
  104880. * @param batch Defines the batch of meshes in case of instances
  104881. * @param useOverlay Defines if the rendering is for the overlay or the outline
  104882. */
  104883. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  104884. var _this = this;
  104885. if (useOverlay === void 0) { useOverlay = false; }
  104886. var scene = this.scene;
  104887. var engine = scene.getEngine();
  104888. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  104889. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  104890. return;
  104891. }
  104892. var mesh = subMesh.getRenderingMesh();
  104893. var material = subMesh.getMaterial();
  104894. if (!material || !scene.activeCamera) {
  104895. return;
  104896. }
  104897. engine.enableEffect(this._effect);
  104898. // Logarithmic depth
  104899. if (material.useLogarithmicDepth) {
  104900. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  104901. }
  104902. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  104903. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  104904. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  104905. // Bones
  104906. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  104907. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  104908. }
  104909. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  104910. // Alpha test
  104911. if (material && material.needAlphaTesting()) {
  104912. var alphaTexture = material.getAlphaTestTexture();
  104913. if (alphaTexture) {
  104914. this._effect.setTexture("diffuseSampler", alphaTexture);
  104915. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  104916. }
  104917. }
  104918. engine.setZOffset(-this.zOffset);
  104919. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  104920. engine.setZOffset(0);
  104921. };
  104922. /**
  104923. * Returns whether or not the outline renderer is ready for a given submesh.
  104924. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  104925. * @param subMesh Defines the submesh to check readyness for
  104926. * @param useInstances Defines wheter wee are trying to render instances or not
  104927. * @returns true if ready otherwise false
  104928. */
  104929. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  104930. var defines = [];
  104931. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  104932. var mesh = subMesh.getMesh();
  104933. var material = subMesh.getMaterial();
  104934. if (material) {
  104935. // Alpha test
  104936. if (material.needAlphaTesting()) {
  104937. defines.push("#define ALPHATEST");
  104938. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  104939. attribs.push(BABYLON.VertexBuffer.UVKind);
  104940. defines.push("#define UV1");
  104941. }
  104942. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  104943. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  104944. defines.push("#define UV2");
  104945. }
  104946. }
  104947. //Logarithmic depth
  104948. if (material.useLogarithmicDepth) {
  104949. defines.push("#define LOGARITHMICDEPTH");
  104950. }
  104951. }
  104952. // Bones
  104953. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  104954. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  104955. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  104956. if (mesh.numBoneInfluencers > 4) {
  104957. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  104958. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  104959. }
  104960. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  104961. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  104962. }
  104963. else {
  104964. defines.push("#define NUM_BONE_INFLUENCERS 0");
  104965. }
  104966. // Instances
  104967. if (useInstances) {
  104968. defines.push("#define INSTANCES");
  104969. attribs.push("world0");
  104970. attribs.push("world1");
  104971. attribs.push("world2");
  104972. attribs.push("world3");
  104973. }
  104974. // Get correct effect
  104975. var join = defines.join("\n");
  104976. if (this._cachedDefines !== join) {
  104977. this._cachedDefines = join;
  104978. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  104979. }
  104980. return this._effect.isReady();
  104981. };
  104982. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  104983. // Outline - step 1
  104984. this._savedDepthWrite = this._engine.getDepthWrite();
  104985. if (mesh.renderOutline) {
  104986. this._engine.setDepthWrite(false);
  104987. this.render(subMesh, batch);
  104988. this._engine.setDepthWrite(this._savedDepthWrite);
  104989. }
  104990. };
  104991. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  104992. // Outline - step 2
  104993. if (mesh.renderOutline && this._savedDepthWrite) {
  104994. this._engine.setDepthWrite(true);
  104995. this._engine.setColorWrite(false);
  104996. this.render(subMesh, batch);
  104997. this._engine.setColorWrite(true);
  104998. }
  104999. // Overlay
  105000. if (mesh.renderOverlay) {
  105001. var currentMode = this._engine.getAlphaMode();
  105002. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  105003. this.render(subMesh, batch, true);
  105004. this._engine.setAlphaMode(currentMode);
  105005. }
  105006. };
  105007. return OutlineRenderer;
  105008. }());
  105009. BABYLON.OutlineRenderer = OutlineRenderer;
  105010. })(BABYLON || (BABYLON = {}));
  105011. //# sourceMappingURL=babylon.outlineRenderer.js.map
  105012. var BABYLON;
  105013. (function (BABYLON) {
  105014. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  105015. if (this._edgesRenderer) {
  105016. this._edgesRenderer.dispose();
  105017. this._edgesRenderer = null;
  105018. }
  105019. return this;
  105020. };
  105021. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  105022. if (epsilon === void 0) { epsilon = 0.95; }
  105023. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  105024. this.disableEdgesRendering();
  105025. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  105026. return this;
  105027. };
  105028. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  105029. get: function () {
  105030. return this._edgesRenderer;
  105031. },
  105032. enumerable: true,
  105033. configurable: true
  105034. });
  105035. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  105036. if (epsilon === void 0) { epsilon = 0.95; }
  105037. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  105038. this.disableEdgesRendering();
  105039. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  105040. return this;
  105041. };
  105042. /**
  105043. * FaceAdjacencies Helper class to generate edges
  105044. */
  105045. var FaceAdjacencies = /** @class */ (function () {
  105046. function FaceAdjacencies() {
  105047. this.edges = new Array();
  105048. this.edgesConnectedCount = 0;
  105049. }
  105050. return FaceAdjacencies;
  105051. }());
  105052. /**
  105053. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  105054. */
  105055. var EdgesRenderer = /** @class */ (function () {
  105056. /**
  105057. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  105058. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  105059. * @param source Mesh used to create edges
  105060. * @param epsilon sum of angles in adjacency to check for edge
  105061. * @param checkVerticesInsteadOfIndices
  105062. * @param generateEdgesLines - should generate Lines or only prepare resources.
  105063. */
  105064. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  105065. if (epsilon === void 0) { epsilon = 0.95; }
  105066. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  105067. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  105068. var _this = this;
  105069. /**
  105070. * Define the size of the edges with an orthographic camera
  105071. */
  105072. this.edgesWidthScalerForOrthographic = 1000.0;
  105073. /**
  105074. * Define the size of the edges with a perspective camera
  105075. */
  105076. this.edgesWidthScalerForPerspective = 50.0;
  105077. this._linesPositions = new Array();
  105078. this._linesNormals = new Array();
  105079. this._linesIndices = new Array();
  105080. this._buffers = {};
  105081. this._checkVerticesInsteadOfIndices = false;
  105082. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  105083. this.isEnabled = true;
  105084. this._source = source;
  105085. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  105086. this._epsilon = epsilon;
  105087. this._prepareRessources();
  105088. if (generateEdgesLines) {
  105089. this._generateEdgesLines();
  105090. }
  105091. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  105092. _this._rebuild();
  105093. });
  105094. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  105095. _this.dispose();
  105096. });
  105097. }
  105098. EdgesRenderer.prototype._prepareRessources = function () {
  105099. if (this._lineShader) {
  105100. return;
  105101. }
  105102. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  105103. attributes: ["position", "normal"],
  105104. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  105105. });
  105106. this._lineShader.disableDepthWrite = true;
  105107. this._lineShader.backFaceCulling = false;
  105108. };
  105109. /** @hidden */
  105110. EdgesRenderer.prototype._rebuild = function () {
  105111. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  105112. if (buffer) {
  105113. buffer._rebuild();
  105114. }
  105115. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  105116. if (buffer) {
  105117. buffer._rebuild();
  105118. }
  105119. var scene = this._source.getScene();
  105120. var engine = scene.getEngine();
  105121. this._ib = engine.createIndexBuffer(this._linesIndices);
  105122. };
  105123. /**
  105124. * Releases the required resources for the edges renderer
  105125. */
  105126. EdgesRenderer.prototype.dispose = function () {
  105127. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  105128. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  105129. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  105130. if (buffer) {
  105131. buffer.dispose();
  105132. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  105133. }
  105134. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  105135. if (buffer) {
  105136. buffer.dispose();
  105137. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  105138. }
  105139. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  105140. this._lineShader.dispose();
  105141. };
  105142. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  105143. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  105144. return 0;
  105145. }
  105146. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  105147. return 1;
  105148. }
  105149. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  105150. return 2;
  105151. }
  105152. return -1;
  105153. };
  105154. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  105155. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  105156. return 0;
  105157. }
  105158. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  105159. return 1;
  105160. }
  105161. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  105162. return 2;
  105163. }
  105164. return -1;
  105165. };
  105166. /**
  105167. * Checks if the pair of p0 and p1 is en edge
  105168. * @param faceIndex
  105169. * @param edge
  105170. * @param faceNormals
  105171. * @param p0
  105172. * @param p1
  105173. * @private
  105174. */
  105175. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  105176. var needToCreateLine;
  105177. if (edge === undefined) {
  105178. needToCreateLine = true;
  105179. }
  105180. else {
  105181. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  105182. needToCreateLine = dotProduct < this._epsilon;
  105183. }
  105184. if (needToCreateLine) {
  105185. var offset = this._linesPositions.length / 3;
  105186. var normal = p0.subtract(p1);
  105187. normal.normalize();
  105188. // Positions
  105189. this._linesPositions.push(p0.x);
  105190. this._linesPositions.push(p0.y);
  105191. this._linesPositions.push(p0.z);
  105192. this._linesPositions.push(p0.x);
  105193. this._linesPositions.push(p0.y);
  105194. this._linesPositions.push(p0.z);
  105195. this._linesPositions.push(p1.x);
  105196. this._linesPositions.push(p1.y);
  105197. this._linesPositions.push(p1.z);
  105198. this._linesPositions.push(p1.x);
  105199. this._linesPositions.push(p1.y);
  105200. this._linesPositions.push(p1.z);
  105201. // Normals
  105202. this._linesNormals.push(p1.x);
  105203. this._linesNormals.push(p1.y);
  105204. this._linesNormals.push(p1.z);
  105205. this._linesNormals.push(-1);
  105206. this._linesNormals.push(p1.x);
  105207. this._linesNormals.push(p1.y);
  105208. this._linesNormals.push(p1.z);
  105209. this._linesNormals.push(1);
  105210. this._linesNormals.push(p0.x);
  105211. this._linesNormals.push(p0.y);
  105212. this._linesNormals.push(p0.z);
  105213. this._linesNormals.push(-1);
  105214. this._linesNormals.push(p0.x);
  105215. this._linesNormals.push(p0.y);
  105216. this._linesNormals.push(p0.z);
  105217. this._linesNormals.push(1);
  105218. // Indices
  105219. this._linesIndices.push(offset);
  105220. this._linesIndices.push(offset + 1);
  105221. this._linesIndices.push(offset + 2);
  105222. this._linesIndices.push(offset);
  105223. this._linesIndices.push(offset + 2);
  105224. this._linesIndices.push(offset + 3);
  105225. }
  105226. };
  105227. /**
  105228. * Generates lines edges from adjacencjes
  105229. * @private
  105230. */
  105231. EdgesRenderer.prototype._generateEdgesLines = function () {
  105232. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  105233. var indices = this._source.getIndices();
  105234. if (!indices || !positions) {
  105235. return;
  105236. }
  105237. // First let's find adjacencies
  105238. var adjacencies = new Array();
  105239. var faceNormals = new Array();
  105240. var index;
  105241. var faceAdjacencies;
  105242. // Prepare faces
  105243. for (index = 0; index < indices.length; index += 3) {
  105244. faceAdjacencies = new FaceAdjacencies();
  105245. var p0Index = indices[index];
  105246. var p1Index = indices[index + 1];
  105247. var p2Index = indices[index + 2];
  105248. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  105249. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  105250. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  105251. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  105252. faceNormal.normalize();
  105253. faceNormals.push(faceNormal);
  105254. adjacencies.push(faceAdjacencies);
  105255. }
  105256. // Scan
  105257. for (index = 0; index < adjacencies.length; index++) {
  105258. faceAdjacencies = adjacencies[index];
  105259. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  105260. var otherFaceAdjacencies = adjacencies[otherIndex];
  105261. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  105262. break;
  105263. }
  105264. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  105265. continue;
  105266. }
  105267. var otherP0 = indices[otherIndex * 3];
  105268. var otherP1 = indices[otherIndex * 3 + 1];
  105269. var otherP2 = indices[otherIndex * 3 + 2];
  105270. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  105271. var otherEdgeIndex = 0;
  105272. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  105273. continue;
  105274. }
  105275. switch (edgeIndex) {
  105276. case 0:
  105277. if (this._checkVerticesInsteadOfIndices) {
  105278. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  105279. }
  105280. else {
  105281. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  105282. }
  105283. break;
  105284. case 1:
  105285. if (this._checkVerticesInsteadOfIndices) {
  105286. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  105287. }
  105288. else {
  105289. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  105290. }
  105291. break;
  105292. case 2:
  105293. if (this._checkVerticesInsteadOfIndices) {
  105294. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  105295. }
  105296. else {
  105297. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  105298. }
  105299. break;
  105300. }
  105301. if (otherEdgeIndex === -1) {
  105302. continue;
  105303. }
  105304. faceAdjacencies.edges[edgeIndex] = otherIndex;
  105305. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  105306. faceAdjacencies.edgesConnectedCount++;
  105307. otherFaceAdjacencies.edgesConnectedCount++;
  105308. if (faceAdjacencies.edgesConnectedCount === 3) {
  105309. break;
  105310. }
  105311. }
  105312. }
  105313. }
  105314. // Create lines
  105315. for (index = 0; index < adjacencies.length; index++) {
  105316. // 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
  105317. var current = adjacencies[index];
  105318. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  105319. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  105320. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  105321. }
  105322. // Merge into a single mesh
  105323. var engine = this._source.getScene().getEngine();
  105324. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  105325. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  105326. this._ib = engine.createIndexBuffer(this._linesIndices);
  105327. this._indicesCount = this._linesIndices.length;
  105328. };
  105329. /**
  105330. * Checks wether or not the edges renderer is ready to render.
  105331. * @return true if ready, otherwise false.
  105332. */
  105333. EdgesRenderer.prototype.isReady = function () {
  105334. return this._lineShader.isReady();
  105335. };
  105336. /**
  105337. * Renders the edges of the attached mesh,
  105338. */
  105339. EdgesRenderer.prototype.render = function () {
  105340. var scene = this._source.getScene();
  105341. if (!this.isReady() || !scene.activeCamera) {
  105342. return;
  105343. }
  105344. var engine = scene.getEngine();
  105345. this._lineShader._preBind();
  105346. if (this._source.edgesColor.a !== 1) {
  105347. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  105348. }
  105349. else {
  105350. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  105351. }
  105352. // VBOs
  105353. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  105354. scene.resetCachedMaterial();
  105355. this._lineShader.setColor4("color", this._source.edgesColor);
  105356. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  105357. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  105358. }
  105359. else {
  105360. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  105361. }
  105362. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  105363. this._lineShader.bind(this._source.getWorldMatrix());
  105364. // Draw order
  105365. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  105366. this._lineShader.unbind();
  105367. };
  105368. return EdgesRenderer;
  105369. }());
  105370. BABYLON.EdgesRenderer = EdgesRenderer;
  105371. })(BABYLON || (BABYLON = {}));
  105372. //# sourceMappingURL=babylon.edgesRenderer.js.map
  105373. var BABYLON;
  105374. (function (BABYLON) {
  105375. /**
  105376. * FaceAdjacencies Helper class to generate edges
  105377. */
  105378. var FaceAdjacencies = /** @class */ (function () {
  105379. function FaceAdjacencies() {
  105380. this.edges = new Array();
  105381. this.edgesConnectedCount = 0;
  105382. }
  105383. return FaceAdjacencies;
  105384. }());
  105385. /**
  105386. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  105387. */
  105388. var LineEdgesRenderer = /** @class */ (function (_super) {
  105389. __extends(LineEdgesRenderer, _super);
  105390. /**
  105391. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  105392. * @param source LineMesh used to generate edges
  105393. * @param epsilon not important (specified angle for edge detection)
  105394. * @param checkVerticesInsteadOfIndices not important for LineMesh
  105395. */
  105396. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  105397. if (epsilon === void 0) { epsilon = 0.95; }
  105398. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  105399. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  105400. _this._generateEdgesLines();
  105401. return _this;
  105402. }
  105403. /**
  105404. * Always create the edge since its a line so only important things are p0 and p1
  105405. * @param faceIndex not important for LineMesh
  105406. * @param edge not important for LineMesh
  105407. * @param faceNormals not important for LineMesh
  105408. * @param p0 beginnig of line
  105409. * @param p1 end of line
  105410. */
  105411. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  105412. var offset = this._linesPositions.length / 3;
  105413. var normal = p0.subtract(p1);
  105414. normal.normalize();
  105415. // Positions
  105416. this._linesPositions.push(p0.x);
  105417. this._linesPositions.push(p0.y);
  105418. this._linesPositions.push(p0.z);
  105419. this._linesPositions.push(p0.x);
  105420. this._linesPositions.push(p0.y);
  105421. this._linesPositions.push(p0.z);
  105422. this._linesPositions.push(p1.x);
  105423. this._linesPositions.push(p1.y);
  105424. this._linesPositions.push(p1.z);
  105425. this._linesPositions.push(p1.x);
  105426. this._linesPositions.push(p1.y);
  105427. this._linesPositions.push(p1.z);
  105428. // Normals
  105429. this._linesNormals.push(p1.x);
  105430. this._linesNormals.push(p1.y);
  105431. this._linesNormals.push(p1.z);
  105432. this._linesNormals.push(-1);
  105433. this._linesNormals.push(p1.x);
  105434. this._linesNormals.push(p1.y);
  105435. this._linesNormals.push(p1.z);
  105436. this._linesNormals.push(1);
  105437. this._linesNormals.push(p0.x);
  105438. this._linesNormals.push(p0.y);
  105439. this._linesNormals.push(p0.z);
  105440. this._linesNormals.push(-1);
  105441. this._linesNormals.push(p0.x);
  105442. this._linesNormals.push(p0.y);
  105443. this._linesNormals.push(p0.z);
  105444. this._linesNormals.push(1);
  105445. // Indices
  105446. this._linesIndices.push(offset);
  105447. this._linesIndices.push(offset + 1);
  105448. this._linesIndices.push(offset + 2);
  105449. this._linesIndices.push(offset);
  105450. this._linesIndices.push(offset + 2);
  105451. this._linesIndices.push(offset + 3);
  105452. };
  105453. /**
  105454. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  105455. */
  105456. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  105457. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  105458. var indices = this._source.getIndices();
  105459. if (!indices || !positions) {
  105460. return;
  105461. }
  105462. // First let's find adjacencies
  105463. var adjacencies = new Array();
  105464. var faceNormals = new Array();
  105465. var index;
  105466. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  105467. var currentAdjecancy = new FaceAdjacencies();
  105468. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  105469. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  105470. adjacencies.push(currentAdjecancy);
  105471. }
  105472. // Create lines
  105473. for (index = 0; index < adjacencies.length; index++) {
  105474. // 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
  105475. var current = adjacencies[index];
  105476. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  105477. }
  105478. // Merge into a single mesh
  105479. var engine = this._source.getScene().getEngine();
  105480. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  105481. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  105482. this._ib = engine.createIndexBuffer(this._linesIndices);
  105483. this._indicesCount = this._linesIndices.length;
  105484. };
  105485. return LineEdgesRenderer;
  105486. }(BABYLON.EdgesRenderer));
  105487. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  105488. })(BABYLON || (BABYLON = {}));
  105489. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  105490. var BABYLON;
  105491. (function (BABYLON) {
  105492. // Adds the parser to the scene parsers.
  105493. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  105494. if (parsedData.effectLayers) {
  105495. if (!container.effectLayers) {
  105496. container.effectLayers = new Array();
  105497. }
  105498. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  105499. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  105500. container.effectLayers.push(effectLayer);
  105501. }
  105502. }
  105503. });
  105504. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  105505. var index = this.effectLayers.indexOf(toRemove);
  105506. if (index !== -1) {
  105507. this.effectLayers.splice(index, 1);
  105508. }
  105509. return index;
  105510. };
  105511. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  105512. this.effectLayers.push(newEffectLayer);
  105513. };
  105514. /**
  105515. * Defines the layer scene component responsible to manage any effect layers
  105516. * in a given scene.
  105517. */
  105518. var EffectLayerSceneComponent = /** @class */ (function () {
  105519. /**
  105520. * Creates a new instance of the component for the given scene
  105521. * @param scene Defines the scene to register the component in
  105522. */
  105523. function EffectLayerSceneComponent(scene) {
  105524. /**
  105525. * The component name helpfull to identify the component in the list of scene components.
  105526. */
  105527. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  105528. this._renderEffects = false;
  105529. this._needStencil = false;
  105530. this._previousStencilState = false;
  105531. this.scene = scene;
  105532. this._engine = scene.getEngine();
  105533. scene.effectLayers = new Array();
  105534. }
  105535. /**
  105536. * Registers the component in a given scene
  105537. */
  105538. EffectLayerSceneComponent.prototype.register = function () {
  105539. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  105540. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  105541. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  105542. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  105543. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  105544. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  105545. };
  105546. /**
  105547. * Rebuilds the elements related to this component in case of
  105548. * context lost for instance.
  105549. */
  105550. EffectLayerSceneComponent.prototype.rebuild = function () {
  105551. var layers = this.scene.effectLayers;
  105552. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  105553. var effectLayer = layers_1[_i];
  105554. effectLayer._rebuild();
  105555. }
  105556. };
  105557. /**
  105558. * Serializes the component data to the specified json object
  105559. * @param serializationObject The object to serialize to
  105560. */
  105561. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  105562. // Effect layers
  105563. serializationObject.effectLayers = [];
  105564. var layers = this.scene.effectLayers;
  105565. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  105566. var effectLayer = layers_2[_i];
  105567. if (effectLayer.serialize) {
  105568. serializationObject.effectLayers.push(effectLayer.serialize());
  105569. }
  105570. }
  105571. };
  105572. /**
  105573. * Adds all the element from the container to the scene
  105574. * @param container the container holding the elements
  105575. */
  105576. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  105577. var _this = this;
  105578. if (!container.effectLayers) {
  105579. return;
  105580. }
  105581. container.effectLayers.forEach(function (o) {
  105582. _this.scene.addEffectLayer(o);
  105583. });
  105584. };
  105585. /**
  105586. * Removes all the elements in the container from the scene
  105587. * @param container contains the elements to remove
  105588. */
  105589. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  105590. var _this = this;
  105591. if (!container.effectLayers) {
  105592. return;
  105593. }
  105594. container.effectLayers.forEach(function (o) {
  105595. _this.scene.removeEffectLayer(o);
  105596. });
  105597. };
  105598. /**
  105599. * Disposes the component and the associated ressources.
  105600. */
  105601. EffectLayerSceneComponent.prototype.dispose = function () {
  105602. var layers = this.scene.effectLayers;
  105603. while (layers.length) {
  105604. layers[0].dispose();
  105605. }
  105606. };
  105607. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  105608. var layers = this.scene.effectLayers;
  105609. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  105610. var layer = layers_3[_i];
  105611. if (!layer.hasMesh(mesh)) {
  105612. continue;
  105613. }
  105614. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  105615. var subMesh = _b[_a];
  105616. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  105617. return false;
  105618. }
  105619. }
  105620. }
  105621. return true;
  105622. };
  105623. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  105624. this._renderEffects = false;
  105625. this._needStencil = false;
  105626. var layers = this.scene.effectLayers;
  105627. if (layers && layers.length > 0) {
  105628. this._previousStencilState = this._engine.getStencilBuffer();
  105629. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  105630. var effectLayer = layers_4[_i];
  105631. if (effectLayer.shouldRender() &&
  105632. (!effectLayer.camera ||
  105633. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  105634. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  105635. this._renderEffects = true;
  105636. this._needStencil = this._needStencil || effectLayer.needStencil();
  105637. var renderTarget = effectLayer._mainTexture;
  105638. if (renderTarget._shouldRender()) {
  105639. this.scene.incrementRenderId();
  105640. renderTarget.render(false, false);
  105641. }
  105642. }
  105643. }
  105644. this.scene.incrementRenderId();
  105645. }
  105646. };
  105647. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  105648. // Activate effect Layer stencil
  105649. if (this._needStencil) {
  105650. this._engine.setStencilBuffer(true);
  105651. }
  105652. };
  105653. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  105654. // Restore effect Layer stencil
  105655. if (this._needStencil) {
  105656. this._engine.setStencilBuffer(this._previousStencilState);
  105657. }
  105658. };
  105659. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  105660. if (this._renderEffects) {
  105661. this._engine.setDepthBuffer(false);
  105662. var layers = this.scene.effectLayers;
  105663. for (var i = 0; i < layers.length; i++) {
  105664. var effectLayer = layers[i];
  105665. if (effectLayer.renderingGroupId === renderingGroupId) {
  105666. if (effectLayer.shouldRender()) {
  105667. effectLayer.render();
  105668. }
  105669. }
  105670. }
  105671. this._engine.setDepthBuffer(true);
  105672. }
  105673. };
  105674. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  105675. if (this._renderEffects) {
  105676. this._draw(-1);
  105677. }
  105678. };
  105679. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  105680. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  105681. this._draw(index);
  105682. }
  105683. };
  105684. return EffectLayerSceneComponent;
  105685. }());
  105686. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  105687. })(BABYLON || (BABYLON = {}));
  105688. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  105689. var __assign = (this && this.__assign) || function () {
  105690. __assign = Object.assign || function(t) {
  105691. for (var s, i = 1, n = arguments.length; i < n; i++) {
  105692. s = arguments[i];
  105693. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  105694. t[p] = s[p];
  105695. }
  105696. return t;
  105697. };
  105698. return __assign.apply(this, arguments);
  105699. };
  105700. var BABYLON;
  105701. (function (BABYLON) {
  105702. /**
  105703. * The effect layer Helps adding post process effect blended with the main pass.
  105704. *
  105705. * This can be for instance use to generate glow or higlight effects on the scene.
  105706. *
  105707. * The effect layer class can not be used directly and is intented to inherited from to be
  105708. * customized per effects.
  105709. */
  105710. var EffectLayer = /** @class */ (function () {
  105711. /**
  105712. * Instantiates a new effect Layer and references it in the scene.
  105713. * @param name The name of the layer
  105714. * @param scene The scene to use the layer in
  105715. */
  105716. function EffectLayer(
  105717. /** The Friendly of the effect in the scene */
  105718. name, scene) {
  105719. this._vertexBuffers = {};
  105720. this._maxSize = 0;
  105721. this._mainTextureDesiredSize = { width: 0, height: 0 };
  105722. this._shouldRender = true;
  105723. this._postProcesses = [];
  105724. this._textures = [];
  105725. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  105726. /**
  105727. * The clear color of the texture used to generate the glow map.
  105728. */
  105729. this.neutralColor = new BABYLON.Color4();
  105730. /**
  105731. * Specifies wether the highlight layer is enabled or not.
  105732. */
  105733. this.isEnabled = true;
  105734. /**
  105735. * An event triggered when the effect layer has been disposed.
  105736. */
  105737. this.onDisposeObservable = new BABYLON.Observable();
  105738. /**
  105739. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  105740. */
  105741. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  105742. /**
  105743. * An event triggered when the generated texture is being merged in the scene.
  105744. */
  105745. this.onBeforeComposeObservable = new BABYLON.Observable();
  105746. /**
  105747. * An event triggered when the generated texture has been merged in the scene.
  105748. */
  105749. this.onAfterComposeObservable = new BABYLON.Observable();
  105750. /**
  105751. * An event triggered when the efffect layer changes its size.
  105752. */
  105753. this.onSizeChangedObservable = new BABYLON.Observable();
  105754. this.name = name;
  105755. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  105756. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  105757. if (!component) {
  105758. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  105759. this._scene._addComponent(component);
  105760. }
  105761. this._engine = this._scene.getEngine();
  105762. this._maxSize = this._engine.getCaps().maxTextureSize;
  105763. this._scene.effectLayers.push(this);
  105764. // Generate Buffers
  105765. this._generateIndexBuffer();
  105766. this._genrateVertexBuffer();
  105767. }
  105768. Object.defineProperty(EffectLayer.prototype, "camera", {
  105769. /**
  105770. * Gets the camera attached to the layer.
  105771. */
  105772. get: function () {
  105773. return this._effectLayerOptions.camera;
  105774. },
  105775. enumerable: true,
  105776. configurable: true
  105777. });
  105778. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  105779. /**
  105780. * Gets the rendering group id the layer should render in.
  105781. */
  105782. get: function () {
  105783. return this._effectLayerOptions.renderingGroupId;
  105784. },
  105785. enumerable: true,
  105786. configurable: true
  105787. });
  105788. /**
  105789. * Initializes the effect layer with the required options.
  105790. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  105791. */
  105792. EffectLayer.prototype._init = function (options) {
  105793. // Adapt options
  105794. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  105795. this._setMainTextureSize();
  105796. this._createMainTexture();
  105797. this._createTextureAndPostProcesses();
  105798. this._mergeEffect = this._createMergeEffect();
  105799. };
  105800. /**
  105801. * Generates the index buffer of the full screen quad blending to the main canvas.
  105802. */
  105803. EffectLayer.prototype._generateIndexBuffer = function () {
  105804. // Indices
  105805. var indices = [];
  105806. indices.push(0);
  105807. indices.push(1);
  105808. indices.push(2);
  105809. indices.push(0);
  105810. indices.push(2);
  105811. indices.push(3);
  105812. this._indexBuffer = this._engine.createIndexBuffer(indices);
  105813. };
  105814. /**
  105815. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  105816. */
  105817. EffectLayer.prototype._genrateVertexBuffer = function () {
  105818. // VBO
  105819. var vertices = [];
  105820. vertices.push(1, 1);
  105821. vertices.push(-1, 1);
  105822. vertices.push(-1, -1);
  105823. vertices.push(1, -1);
  105824. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  105825. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  105826. };
  105827. /**
  105828. * Sets the main texture desired size which is the closest power of two
  105829. * of the engine canvas size.
  105830. */
  105831. EffectLayer.prototype._setMainTextureSize = function () {
  105832. if (this._effectLayerOptions.mainTextureFixedSize) {
  105833. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  105834. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  105835. }
  105836. else {
  105837. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  105838. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  105839. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  105840. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  105841. }
  105842. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  105843. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  105844. };
  105845. /**
  105846. * Creates the main texture for the effect layer.
  105847. */
  105848. EffectLayer.prototype._createMainTexture = function () {
  105849. var _this = this;
  105850. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  105851. width: this._mainTextureDesiredSize.width,
  105852. height: this._mainTextureDesiredSize.height
  105853. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  105854. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  105855. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105856. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105857. this._mainTexture.anisotropicFilteringLevel = 1;
  105858. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  105859. this._mainTexture.renderParticles = false;
  105860. this._mainTexture.renderList = null;
  105861. this._mainTexture.ignoreCameraViewport = true;
  105862. // Custom render function
  105863. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  105864. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  105865. var index;
  105866. var engine = _this._scene.getEngine();
  105867. if (depthOnlySubMeshes.length) {
  105868. engine.setColorWrite(false);
  105869. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  105870. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  105871. }
  105872. engine.setColorWrite(true);
  105873. }
  105874. for (index = 0; index < opaqueSubMeshes.length; index++) {
  105875. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  105876. }
  105877. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  105878. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  105879. }
  105880. for (index = 0; index < transparentSubMeshes.length; index++) {
  105881. _this._renderSubMesh(transparentSubMeshes.data[index]);
  105882. }
  105883. };
  105884. this._mainTexture.onClearObservable.add(function (engine) {
  105885. engine.clear(_this.neutralColor, true, true, true);
  105886. });
  105887. };
  105888. /**
  105889. * Checks for the readiness of the element composing the layer.
  105890. * @param subMesh the mesh to check for
  105891. * @param useInstances specify wether or not to use instances to render the mesh
  105892. * @param emissiveTexture the associated emissive texture used to generate the glow
  105893. * @return true if ready otherwise, false
  105894. */
  105895. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  105896. var material = subMesh.getMaterial();
  105897. if (!material) {
  105898. return false;
  105899. }
  105900. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  105901. return false;
  105902. }
  105903. var defines = [];
  105904. var attribs = [BABYLON.VertexBuffer.PositionKind];
  105905. var mesh = subMesh.getMesh();
  105906. var uv1 = false;
  105907. var uv2 = false;
  105908. // Alpha test
  105909. if (material && material.needAlphaTesting()) {
  105910. var alphaTexture = material.getAlphaTestTexture();
  105911. if (alphaTexture) {
  105912. defines.push("#define ALPHATEST");
  105913. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  105914. alphaTexture.coordinatesIndex === 1) {
  105915. defines.push("#define DIFFUSEUV2");
  105916. uv2 = true;
  105917. }
  105918. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  105919. defines.push("#define DIFFUSEUV1");
  105920. uv1 = true;
  105921. }
  105922. }
  105923. }
  105924. // Emissive
  105925. if (emissiveTexture) {
  105926. defines.push("#define EMISSIVE");
  105927. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  105928. emissiveTexture.coordinatesIndex === 1) {
  105929. defines.push("#define EMISSIVEUV2");
  105930. uv2 = true;
  105931. }
  105932. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  105933. defines.push("#define EMISSIVEUV1");
  105934. uv1 = true;
  105935. }
  105936. }
  105937. if (uv1) {
  105938. attribs.push(BABYLON.VertexBuffer.UVKind);
  105939. defines.push("#define UV1");
  105940. }
  105941. if (uv2) {
  105942. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  105943. defines.push("#define UV2");
  105944. }
  105945. // Bones
  105946. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  105947. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  105948. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  105949. if (mesh.numBoneInfluencers > 4) {
  105950. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  105951. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  105952. }
  105953. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  105954. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  105955. }
  105956. else {
  105957. defines.push("#define NUM_BONE_INFLUENCERS 0");
  105958. }
  105959. // Morph targets
  105960. var manager = mesh.morphTargetManager;
  105961. var morphInfluencers = 0;
  105962. if (manager) {
  105963. if (manager.numInfluencers > 0) {
  105964. defines.push("#define MORPHTARGETS");
  105965. morphInfluencers = manager.numInfluencers;
  105966. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  105967. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  105968. }
  105969. }
  105970. // Instances
  105971. if (useInstances) {
  105972. defines.push("#define INSTANCES");
  105973. attribs.push("world0");
  105974. attribs.push("world1");
  105975. attribs.push("world2");
  105976. attribs.push("world3");
  105977. }
  105978. // Get correct effect
  105979. var join = defines.join("\n");
  105980. if (this._cachedDefines !== join) {
  105981. this._cachedDefines = join;
  105982. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  105983. }
  105984. return this._effectLayerMapGenerationEffect.isReady();
  105985. };
  105986. /**
  105987. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  105988. */
  105989. EffectLayer.prototype.render = function () {
  105990. var currentEffect = this._mergeEffect;
  105991. // Check
  105992. if (!currentEffect.isReady())
  105993. return;
  105994. for (var i = 0; i < this._postProcesses.length; i++) {
  105995. if (!this._postProcesses[i].isReady()) {
  105996. return;
  105997. }
  105998. }
  105999. var engine = this._scene.getEngine();
  106000. this.onBeforeComposeObservable.notifyObservers(this);
  106001. // Render
  106002. engine.enableEffect(currentEffect);
  106003. engine.setState(false);
  106004. // VBOs
  106005. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  106006. // Cache
  106007. var previousAlphaMode = engine.getAlphaMode();
  106008. // Go Blend.
  106009. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  106010. // Blends the map on the main canvas.
  106011. this._internalRender(currentEffect);
  106012. // Restore Alpha
  106013. engine.setAlphaMode(previousAlphaMode);
  106014. this.onAfterComposeObservable.notifyObservers(this);
  106015. // Handle size changes.
  106016. var size = this._mainTexture.getSize();
  106017. this._setMainTextureSize();
  106018. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  106019. // Recreate RTT and post processes on size change.
  106020. this.onSizeChangedObservable.notifyObservers(this);
  106021. this._disposeTextureAndPostProcesses();
  106022. this._createMainTexture();
  106023. this._createTextureAndPostProcesses();
  106024. }
  106025. };
  106026. /**
  106027. * Determine if a given mesh will be used in the current effect.
  106028. * @param mesh mesh to test
  106029. * @returns true if the mesh will be used
  106030. */
  106031. EffectLayer.prototype.hasMesh = function (mesh) {
  106032. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  106033. return true;
  106034. }
  106035. return false;
  106036. };
  106037. /**
  106038. * Returns true if the layer contains information to display, otherwise false.
  106039. * @returns true if the glow layer should be rendered
  106040. */
  106041. EffectLayer.prototype.shouldRender = function () {
  106042. return this.isEnabled && this._shouldRender;
  106043. };
  106044. /**
  106045. * Returns true if the mesh should render, otherwise false.
  106046. * @param mesh The mesh to render
  106047. * @returns true if it should render otherwise false
  106048. */
  106049. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  106050. return true;
  106051. };
  106052. /**
  106053. * Returns true if the mesh should render, otherwise false.
  106054. * @param mesh The mesh to render
  106055. * @returns true if it should render otherwise false
  106056. */
  106057. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  106058. return true;
  106059. };
  106060. /**
  106061. * Renders the submesh passed in parameter to the generation map.
  106062. */
  106063. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  106064. var _this = this;
  106065. if (!this.shouldRender()) {
  106066. return;
  106067. }
  106068. var material = subMesh.getMaterial();
  106069. var mesh = subMesh.getRenderingMesh();
  106070. var scene = this._scene;
  106071. var engine = scene.getEngine();
  106072. if (!material) {
  106073. return;
  106074. }
  106075. // Do not block in blend mode.
  106076. if (material.needAlphaBlendingForMesh(mesh)) {
  106077. return;
  106078. }
  106079. // Culling
  106080. engine.setState(material.backFaceCulling);
  106081. // Managing instances
  106082. var batch = mesh._getInstancesRenderList(subMesh._id);
  106083. if (batch.mustReturn) {
  106084. return;
  106085. }
  106086. // Early Exit per mesh
  106087. if (!this._shouldRenderMesh(mesh)) {
  106088. return;
  106089. }
  106090. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  106091. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  106092. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  106093. engine.enableEffect(this._effectLayerMapGenerationEffect);
  106094. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  106095. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  106096. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  106097. // Alpha test
  106098. if (material && material.needAlphaTesting()) {
  106099. var alphaTexture = material.getAlphaTestTexture();
  106100. if (alphaTexture) {
  106101. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  106102. var textureMatrix = alphaTexture.getTextureMatrix();
  106103. if (textureMatrix) {
  106104. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  106105. }
  106106. }
  106107. }
  106108. // Glow emissive only
  106109. if (this._emissiveTextureAndColor.texture) {
  106110. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  106111. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  106112. }
  106113. // Bones
  106114. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  106115. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  106116. }
  106117. // Morph targets
  106118. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  106119. // Draw
  106120. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  106121. }
  106122. else {
  106123. // Need to reset refresh rate of the main map
  106124. this._mainTexture.resetRefreshCounter();
  106125. }
  106126. };
  106127. /**
  106128. * Rebuild the required buffers.
  106129. * @hidden Internal use only.
  106130. */
  106131. EffectLayer.prototype._rebuild = function () {
  106132. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  106133. if (vb) {
  106134. vb._rebuild();
  106135. }
  106136. this._generateIndexBuffer();
  106137. };
  106138. /**
  106139. * Dispose only the render target textures and post process.
  106140. */
  106141. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  106142. this._mainTexture.dispose();
  106143. for (var i = 0; i < this._postProcesses.length; i++) {
  106144. if (this._postProcesses[i]) {
  106145. this._postProcesses[i].dispose();
  106146. }
  106147. }
  106148. this._postProcesses = [];
  106149. for (var i = 0; i < this._textures.length; i++) {
  106150. if (this._textures[i]) {
  106151. this._textures[i].dispose();
  106152. }
  106153. }
  106154. this._textures = [];
  106155. };
  106156. /**
  106157. * Dispose the highlight layer and free resources.
  106158. */
  106159. EffectLayer.prototype.dispose = function () {
  106160. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  106161. if (vertexBuffer) {
  106162. vertexBuffer.dispose();
  106163. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  106164. }
  106165. if (this._indexBuffer) {
  106166. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  106167. this._indexBuffer = null;
  106168. }
  106169. // Clean textures and post processes
  106170. this._disposeTextureAndPostProcesses();
  106171. // Remove from scene
  106172. var index = this._scene.effectLayers.indexOf(this, 0);
  106173. if (index > -1) {
  106174. this._scene.effectLayers.splice(index, 1);
  106175. }
  106176. // Callback
  106177. this.onDisposeObservable.notifyObservers(this);
  106178. this.onDisposeObservable.clear();
  106179. this.onBeforeRenderMainTextureObservable.clear();
  106180. this.onBeforeComposeObservable.clear();
  106181. this.onAfterComposeObservable.clear();
  106182. this.onSizeChangedObservable.clear();
  106183. };
  106184. /**
  106185. * Gets the class name of the effect layer
  106186. * @returns the string with the class name of the effect layer
  106187. */
  106188. EffectLayer.prototype.getClassName = function () {
  106189. return "EffectLayer";
  106190. };
  106191. /**
  106192. * Creates an effect layer from parsed effect layer data
  106193. * @param parsedEffectLayer defines effect layer data
  106194. * @param scene defines the current scene
  106195. * @param rootUrl defines the root URL containing the effect layer information
  106196. * @returns a parsed effect Layer
  106197. */
  106198. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  106199. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  106200. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  106201. };
  106202. __decorate([
  106203. BABYLON.serialize()
  106204. ], EffectLayer.prototype, "name", void 0);
  106205. __decorate([
  106206. BABYLON.serializeAsColor4()
  106207. ], EffectLayer.prototype, "neutralColor", void 0);
  106208. __decorate([
  106209. BABYLON.serialize()
  106210. ], EffectLayer.prototype, "isEnabled", void 0);
  106211. __decorate([
  106212. BABYLON.serializeAsCameraReference()
  106213. ], EffectLayer.prototype, "camera", null);
  106214. __decorate([
  106215. BABYLON.serialize()
  106216. ], EffectLayer.prototype, "renderingGroupId", null);
  106217. return EffectLayer;
  106218. }());
  106219. BABYLON.EffectLayer = EffectLayer;
  106220. })(BABYLON || (BABYLON = {}));
  106221. //# sourceMappingURL=babylon.effectLayer.js.map
  106222. var BABYLON;
  106223. (function (BABYLON) {
  106224. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  106225. for (var index = 0; index < this.effectLayers.length; index++) {
  106226. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  106227. return this.effectLayers[index];
  106228. }
  106229. }
  106230. return null;
  106231. };
  106232. /**
  106233. * Special Glow Blur post process only blurring the alpha channel
  106234. * It enforces keeping the most luminous color in the color channel.
  106235. */
  106236. var GlowBlurPostProcess = /** @class */ (function (_super) {
  106237. __extends(GlowBlurPostProcess, _super);
  106238. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  106239. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  106240. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  106241. _this.direction = direction;
  106242. _this.kernel = kernel;
  106243. _this.onApplyObservable.add(function (effect) {
  106244. effect.setFloat2("screenSize", _this.width, _this.height);
  106245. effect.setVector2("direction", _this.direction);
  106246. effect.setFloat("blurWidth", _this.kernel);
  106247. });
  106248. return _this;
  106249. }
  106250. return GlowBlurPostProcess;
  106251. }(BABYLON.PostProcess));
  106252. /**
  106253. * The highlight layer Helps adding a glow effect around a mesh.
  106254. *
  106255. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  106256. * glowy meshes to your scene.
  106257. *
  106258. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  106259. */
  106260. var HighlightLayer = /** @class */ (function (_super) {
  106261. __extends(HighlightLayer, _super);
  106262. /**
  106263. * Instantiates a new highlight Layer and references it to the scene..
  106264. * @param name The name of the layer
  106265. * @param scene The scene to use the layer in
  106266. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  106267. */
  106268. function HighlightLayer(name, scene, options) {
  106269. var _this = _super.call(this, name, scene) || this;
  106270. _this.name = name;
  106271. /**
  106272. * Specifies whether or not the inner glow is ACTIVE in the layer.
  106273. */
  106274. _this.innerGlow = true;
  106275. /**
  106276. * Specifies whether or not the outer glow is ACTIVE in the layer.
  106277. */
  106278. _this.outerGlow = true;
  106279. /**
  106280. * An event triggered when the highlight layer is being blurred.
  106281. */
  106282. _this.onBeforeBlurObservable = new BABYLON.Observable();
  106283. /**
  106284. * An event triggered when the highlight layer has been blurred.
  106285. */
  106286. _this.onAfterBlurObservable = new BABYLON.Observable();
  106287. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  106288. _this._meshes = {};
  106289. _this._excludedMeshes = {};
  106290. _this.neutralColor = HighlightLayer.NeutralColor;
  106291. // Warn on stencil
  106292. if (!_this._engine.isStencilEnable) {
  106293. 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 }");
  106294. }
  106295. // Adapt options
  106296. _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);
  106297. // Initialize the layer
  106298. _this._init({
  106299. alphaBlendingMode: _this._options.alphaBlendingMode,
  106300. camera: _this._options.camera,
  106301. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  106302. mainTextureRatio: _this._options.mainTextureRatio,
  106303. renderingGroupId: _this._options.renderingGroupId
  106304. });
  106305. // Do not render as long as no meshes have been added
  106306. _this._shouldRender = false;
  106307. return _this;
  106308. }
  106309. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  106310. /**
  106311. * Gets the horizontal size of the blur.
  106312. */
  106313. get: function () {
  106314. return this._horizontalBlurPostprocess.kernel;
  106315. },
  106316. /**
  106317. * Specifies the horizontal size of the blur.
  106318. */
  106319. set: function (value) {
  106320. this._horizontalBlurPostprocess.kernel = value;
  106321. },
  106322. enumerable: true,
  106323. configurable: true
  106324. });
  106325. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  106326. /**
  106327. * Gets the vertical size of the blur.
  106328. */
  106329. get: function () {
  106330. return this._verticalBlurPostprocess.kernel;
  106331. },
  106332. /**
  106333. * Specifies the vertical size of the blur.
  106334. */
  106335. set: function (value) {
  106336. this._verticalBlurPostprocess.kernel = value;
  106337. },
  106338. enumerable: true,
  106339. configurable: true
  106340. });
  106341. /**
  106342. * Get the effect name of the layer.
  106343. * @return The effect name
  106344. */
  106345. HighlightLayer.prototype.getEffectName = function () {
  106346. return HighlightLayer.EffectName;
  106347. };
  106348. /**
  106349. * Create the merge effect. This is the shader use to blit the information back
  106350. * to the main canvas at the end of the scene rendering.
  106351. */
  106352. HighlightLayer.prototype._createMergeEffect = function () {
  106353. // Effect
  106354. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  106355. };
  106356. /**
  106357. * Creates the render target textures and post processes used in the highlight layer.
  106358. */
  106359. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  106360. var _this = this;
  106361. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  106362. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  106363. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  106364. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  106365. var textureType = 0;
  106366. if (this._engine.getCaps().textureHalfFloatRender) {
  106367. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  106368. }
  106369. else {
  106370. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  106371. }
  106372. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  106373. width: blurTextureWidth,
  106374. height: blurTextureHeight
  106375. }, this._scene, false, true, textureType);
  106376. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106377. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106378. this._blurTexture.anisotropicFilteringLevel = 16;
  106379. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  106380. this._blurTexture.renderParticles = false;
  106381. this._blurTexture.ignoreCameraViewport = true;
  106382. this._textures = [this._blurTexture];
  106383. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  106384. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  106385. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  106386. effect.setTexture("textureSampler", _this._mainTexture);
  106387. });
  106388. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  106389. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  106390. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  106391. });
  106392. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  106393. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  106394. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  106395. });
  106396. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  106397. }
  106398. else {
  106399. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  106400. width: blurTextureWidth,
  106401. height: blurTextureHeight
  106402. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106403. this._horizontalBlurPostprocess.width = blurTextureWidth;
  106404. this._horizontalBlurPostprocess.height = blurTextureHeight;
  106405. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  106406. effect.setTexture("textureSampler", _this._mainTexture);
  106407. });
  106408. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  106409. width: blurTextureWidth,
  106410. height: blurTextureHeight
  106411. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106412. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  106413. }
  106414. this._mainTexture.onAfterUnbindObservable.add(function () {
  106415. _this.onBeforeBlurObservable.notifyObservers(_this);
  106416. var internalTexture = _this._blurTexture.getInternalTexture();
  106417. if (internalTexture) {
  106418. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  106419. }
  106420. _this.onAfterBlurObservable.notifyObservers(_this);
  106421. });
  106422. // Prevent autoClear.
  106423. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  106424. };
  106425. /**
  106426. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  106427. */
  106428. HighlightLayer.prototype.needStencil = function () {
  106429. return true;
  106430. };
  106431. /**
  106432. * Checks for the readiness of the element composing the layer.
  106433. * @param subMesh the mesh to check for
  106434. * @param useInstances specify wether or not to use instances to render the mesh
  106435. * @param emissiveTexture the associated emissive texture used to generate the glow
  106436. * @return true if ready otherwise, false
  106437. */
  106438. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  106439. var material = subMesh.getMaterial();
  106440. var mesh = subMesh.getRenderingMesh();
  106441. if (!material || !mesh || !this._meshes) {
  106442. return false;
  106443. }
  106444. var emissiveTexture = null;
  106445. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  106446. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  106447. emissiveTexture = material.emissiveTexture;
  106448. }
  106449. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  106450. };
  106451. /**
  106452. * Implementation specific of rendering the generating effect on the main canvas.
  106453. * @param effect The effect used to render through
  106454. */
  106455. HighlightLayer.prototype._internalRender = function (effect) {
  106456. // Texture
  106457. effect.setTexture("textureSampler", this._blurTexture);
  106458. // Cache
  106459. var engine = this._engine;
  106460. var previousStencilBuffer = engine.getStencilBuffer();
  106461. var previousStencilFunction = engine.getStencilFunction();
  106462. var previousStencilMask = engine.getStencilMask();
  106463. var previousStencilOperationPass = engine.getStencilOperationPass();
  106464. var previousStencilOperationFail = engine.getStencilOperationFail();
  106465. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  106466. var previousStencilReference = engine.getStencilFunctionReference();
  106467. // Stencil operations
  106468. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  106469. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  106470. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  106471. // Draw order
  106472. engine.setStencilMask(0x00);
  106473. engine.setStencilBuffer(true);
  106474. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  106475. // 2 passes inner outer
  106476. if (this.outerGlow) {
  106477. effect.setFloat("offset", 0);
  106478. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  106479. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  106480. }
  106481. if (this.innerGlow) {
  106482. effect.setFloat("offset", 1);
  106483. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  106484. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  106485. }
  106486. // Restore Cache
  106487. engine.setStencilFunction(previousStencilFunction);
  106488. engine.setStencilMask(previousStencilMask);
  106489. engine.setStencilBuffer(previousStencilBuffer);
  106490. engine.setStencilOperationPass(previousStencilOperationPass);
  106491. engine.setStencilOperationFail(previousStencilOperationFail);
  106492. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  106493. engine.setStencilFunctionReference(previousStencilReference);
  106494. };
  106495. /**
  106496. * Returns true if the layer contains information to display, otherwise false.
  106497. */
  106498. HighlightLayer.prototype.shouldRender = function () {
  106499. if (_super.prototype.shouldRender.call(this)) {
  106500. return this._meshes ? true : false;
  106501. }
  106502. return false;
  106503. };
  106504. /**
  106505. * Returns true if the mesh should render, otherwise false.
  106506. * @param mesh The mesh to render
  106507. * @returns true if it should render otherwise false
  106508. */
  106509. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  106510. // Excluded Mesh
  106511. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  106512. return false;
  106513. }
  106514. ;
  106515. if (!_super.prototype.hasMesh.call(this, mesh)) {
  106516. return false;
  106517. }
  106518. return true;
  106519. };
  106520. /**
  106521. * Sets the required values for both the emissive texture and and the main color.
  106522. */
  106523. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  106524. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  106525. if (highlightLayerMesh) {
  106526. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  106527. }
  106528. else {
  106529. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  106530. }
  106531. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  106532. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  106533. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  106534. }
  106535. else {
  106536. this._emissiveTextureAndColor.texture = null;
  106537. }
  106538. };
  106539. /**
  106540. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  106541. * @param mesh The mesh to exclude from the highlight layer
  106542. */
  106543. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  106544. if (!this._excludedMeshes) {
  106545. return;
  106546. }
  106547. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  106548. if (!meshExcluded) {
  106549. this._excludedMeshes[mesh.uniqueId] = {
  106550. mesh: mesh,
  106551. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  106552. mesh.getEngine().setStencilBuffer(false);
  106553. }),
  106554. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  106555. mesh.getEngine().setStencilBuffer(true);
  106556. }),
  106557. };
  106558. }
  106559. };
  106560. /**
  106561. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  106562. * @param mesh The mesh to highlight
  106563. */
  106564. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  106565. if (!this._excludedMeshes) {
  106566. return;
  106567. }
  106568. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  106569. if (meshExcluded) {
  106570. if (meshExcluded.beforeRender) {
  106571. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  106572. }
  106573. if (meshExcluded.afterRender) {
  106574. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  106575. }
  106576. }
  106577. this._excludedMeshes[mesh.uniqueId] = null;
  106578. };
  106579. /**
  106580. * Determine if a given mesh will be highlighted by the current HighlightLayer
  106581. * @param mesh mesh to test
  106582. * @returns true if the mesh will be highlighted by the current HighlightLayer
  106583. */
  106584. HighlightLayer.prototype.hasMesh = function (mesh) {
  106585. if (!this._meshes) {
  106586. return false;
  106587. }
  106588. if (!_super.prototype.hasMesh.call(this, mesh)) {
  106589. return false;
  106590. }
  106591. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  106592. };
  106593. /**
  106594. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  106595. * @param mesh The mesh to highlight
  106596. * @param color The color of the highlight
  106597. * @param glowEmissiveOnly Extract the glow from the emissive texture
  106598. */
  106599. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  106600. var _this = this;
  106601. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  106602. if (!this._meshes) {
  106603. return;
  106604. }
  106605. var meshHighlight = this._meshes[mesh.uniqueId];
  106606. if (meshHighlight) {
  106607. meshHighlight.color = color;
  106608. }
  106609. else {
  106610. this._meshes[mesh.uniqueId] = {
  106611. mesh: mesh,
  106612. color: color,
  106613. // Lambda required for capture due to Observable this context
  106614. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  106615. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  106616. _this._defaultStencilReference(mesh);
  106617. }
  106618. else {
  106619. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  106620. }
  106621. }),
  106622. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  106623. glowEmissiveOnly: glowEmissiveOnly
  106624. };
  106625. mesh.onDisposeObservable.add(function () {
  106626. _this._disposeMesh(mesh);
  106627. });
  106628. }
  106629. this._shouldRender = true;
  106630. };
  106631. /**
  106632. * Remove a mesh from the highlight layer in order to make it stop glowing.
  106633. * @param mesh The mesh to highlight
  106634. */
  106635. HighlightLayer.prototype.removeMesh = function (mesh) {
  106636. if (!this._meshes) {
  106637. return;
  106638. }
  106639. var meshHighlight = this._meshes[mesh.uniqueId];
  106640. if (meshHighlight) {
  106641. if (meshHighlight.observerHighlight) {
  106642. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  106643. }
  106644. if (meshHighlight.observerDefault) {
  106645. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  106646. }
  106647. delete this._meshes[mesh.uniqueId];
  106648. }
  106649. this._shouldRender = false;
  106650. for (var meshHighlightToCheck in this._meshes) {
  106651. if (this._meshes[meshHighlightToCheck]) {
  106652. this._shouldRender = true;
  106653. break;
  106654. }
  106655. }
  106656. };
  106657. /**
  106658. * Force the stencil to the normal expected value for none glowing parts
  106659. */
  106660. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  106661. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  106662. };
  106663. /**
  106664. * Free any resources and references associated to a mesh.
  106665. * Internal use
  106666. * @param mesh The mesh to free.
  106667. * @hidden
  106668. */
  106669. HighlightLayer.prototype._disposeMesh = function (mesh) {
  106670. this.removeMesh(mesh);
  106671. this.removeExcludedMesh(mesh);
  106672. };
  106673. /**
  106674. * Dispose the highlight layer and free resources.
  106675. */
  106676. HighlightLayer.prototype.dispose = function () {
  106677. if (this._meshes) {
  106678. // Clean mesh references
  106679. for (var id in this._meshes) {
  106680. var meshHighlight = this._meshes[id];
  106681. if (meshHighlight && meshHighlight.mesh) {
  106682. if (meshHighlight.observerHighlight) {
  106683. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  106684. }
  106685. if (meshHighlight.observerDefault) {
  106686. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  106687. }
  106688. }
  106689. }
  106690. this._meshes = null;
  106691. }
  106692. if (this._excludedMeshes) {
  106693. for (var id in this._excludedMeshes) {
  106694. var meshHighlight = this._excludedMeshes[id];
  106695. if (meshHighlight) {
  106696. if (meshHighlight.beforeRender) {
  106697. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  106698. }
  106699. if (meshHighlight.afterRender) {
  106700. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  106701. }
  106702. }
  106703. }
  106704. this._excludedMeshes = null;
  106705. }
  106706. _super.prototype.dispose.call(this);
  106707. };
  106708. /**
  106709. * Gets the class name of the effect layer
  106710. * @returns the string with the class name of the effect layer
  106711. */
  106712. HighlightLayer.prototype.getClassName = function () {
  106713. return "HighlightLayer";
  106714. };
  106715. /**
  106716. * Serializes this Highlight layer
  106717. * @returns a serialized Highlight layer object
  106718. */
  106719. HighlightLayer.prototype.serialize = function () {
  106720. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  106721. serializationObject.customType = "BABYLON.HighlightLayer";
  106722. // Highlighted meshes
  106723. serializationObject.meshes = [];
  106724. if (this._meshes) {
  106725. for (var m in this._meshes) {
  106726. var mesh = this._meshes[m];
  106727. if (mesh) {
  106728. serializationObject.meshes.push({
  106729. glowEmissiveOnly: mesh.glowEmissiveOnly,
  106730. color: mesh.color.asArray(),
  106731. meshId: mesh.mesh.id
  106732. });
  106733. }
  106734. }
  106735. }
  106736. // Excluded meshes
  106737. serializationObject.excludedMeshes = [];
  106738. if (this._excludedMeshes) {
  106739. for (var e in this._excludedMeshes) {
  106740. var excludedMesh = this._excludedMeshes[e];
  106741. if (excludedMesh) {
  106742. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  106743. }
  106744. }
  106745. }
  106746. return serializationObject;
  106747. };
  106748. /**
  106749. * Creates a Highlight layer from parsed Highlight layer data
  106750. * @param parsedHightlightLayer defines the Highlight layer data
  106751. * @param scene defines the current scene
  106752. * @param rootUrl defines the root URL containing the Highlight layer information
  106753. * @returns a parsed Highlight layer
  106754. */
  106755. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  106756. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  106757. var index;
  106758. // Excluded meshes
  106759. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  106760. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  106761. if (mesh) {
  106762. hl.addExcludedMesh(mesh);
  106763. }
  106764. }
  106765. // Included meshes
  106766. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  106767. var highlightedMesh = parsedHightlightLayer.meshes[index];
  106768. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  106769. if (mesh) {
  106770. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  106771. }
  106772. }
  106773. return hl;
  106774. };
  106775. /**
  106776. * Effect Name of the highlight layer.
  106777. */
  106778. HighlightLayer.EffectName = "HighlightLayer";
  106779. /**
  106780. * The neutral color used during the preparation of the glow effect.
  106781. * This is black by default as the blend operation is a blend operation.
  106782. */
  106783. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  106784. /**
  106785. * Stencil value used for glowing meshes.
  106786. */
  106787. HighlightLayer.GlowingMeshStencilReference = 0x02;
  106788. /**
  106789. * Stencil value used for the other meshes in the scene.
  106790. */
  106791. HighlightLayer.NormalMeshStencilReference = 0x01;
  106792. __decorate([
  106793. BABYLON.serialize()
  106794. ], HighlightLayer.prototype, "innerGlow", void 0);
  106795. __decorate([
  106796. BABYLON.serialize()
  106797. ], HighlightLayer.prototype, "outerGlow", void 0);
  106798. __decorate([
  106799. BABYLON.serialize()
  106800. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  106801. __decorate([
  106802. BABYLON.serialize()
  106803. ], HighlightLayer.prototype, "blurVerticalSize", null);
  106804. __decorate([
  106805. BABYLON.serialize("options")
  106806. ], HighlightLayer.prototype, "_options", void 0);
  106807. return HighlightLayer;
  106808. }(BABYLON.EffectLayer));
  106809. BABYLON.HighlightLayer = HighlightLayer;
  106810. })(BABYLON || (BABYLON = {}));
  106811. //# sourceMappingURL=babylon.highlightLayer.js.map
  106812. var BABYLON;
  106813. (function (BABYLON) {
  106814. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  106815. for (var index = 0; index < this.effectLayers.length; index++) {
  106816. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  106817. return this.effectLayers[index];
  106818. }
  106819. }
  106820. return null;
  106821. };
  106822. /**
  106823. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  106824. *
  106825. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  106826. * glowy meshes to your scene.
  106827. *
  106828. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  106829. */
  106830. var GlowLayer = /** @class */ (function (_super) {
  106831. __extends(GlowLayer, _super);
  106832. /**
  106833. * Instantiates a new glow Layer and references it to the scene.
  106834. * @param name The name of the layer
  106835. * @param scene The scene to use the layer in
  106836. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  106837. */
  106838. function GlowLayer(name, scene, options) {
  106839. var _this = _super.call(this, name, scene) || this;
  106840. _this._intensity = 1.0;
  106841. _this._includedOnlyMeshes = [];
  106842. _this._excludedMeshes = [];
  106843. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  106844. // Adapt options
  106845. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  106846. // Initialize the layer
  106847. _this._init({
  106848. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  106849. camera: _this._options.camera,
  106850. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  106851. mainTextureRatio: _this._options.mainTextureRatio,
  106852. renderingGroupId: _this._options.renderingGroupId
  106853. });
  106854. return _this;
  106855. }
  106856. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  106857. /**
  106858. * Gets the kernel size of the blur.
  106859. */
  106860. get: function () {
  106861. return this._horizontalBlurPostprocess1.kernel;
  106862. },
  106863. /**
  106864. * Sets the kernel size of the blur.
  106865. */
  106866. set: function (value) {
  106867. this._horizontalBlurPostprocess1.kernel = value;
  106868. this._verticalBlurPostprocess1.kernel = value;
  106869. this._horizontalBlurPostprocess2.kernel = value;
  106870. this._verticalBlurPostprocess2.kernel = value;
  106871. },
  106872. enumerable: true,
  106873. configurable: true
  106874. });
  106875. Object.defineProperty(GlowLayer.prototype, "intensity", {
  106876. /**
  106877. * Gets the glow intensity.
  106878. */
  106879. get: function () {
  106880. return this._intensity;
  106881. },
  106882. /**
  106883. * Sets the glow intensity.
  106884. */
  106885. set: function (value) {
  106886. this._intensity = value;
  106887. },
  106888. enumerable: true,
  106889. configurable: true
  106890. });
  106891. /**
  106892. * Get the effect name of the layer.
  106893. * @return The effect name
  106894. */
  106895. GlowLayer.prototype.getEffectName = function () {
  106896. return GlowLayer.EffectName;
  106897. };
  106898. /**
  106899. * Create the merge effect. This is the shader use to blit the information back
  106900. * to the main canvas at the end of the scene rendering.
  106901. */
  106902. GlowLayer.prototype._createMergeEffect = function () {
  106903. // Effect
  106904. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  106905. };
  106906. /**
  106907. * Creates the render target textures and post processes used in the glow layer.
  106908. */
  106909. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  106910. var _this = this;
  106911. var blurTextureWidth = this._mainTextureDesiredSize.width;
  106912. var blurTextureHeight = this._mainTextureDesiredSize.height;
  106913. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  106914. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  106915. var textureType = 0;
  106916. if (this._engine.getCaps().textureHalfFloatRender) {
  106917. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  106918. }
  106919. else {
  106920. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  106921. }
  106922. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  106923. width: blurTextureWidth,
  106924. height: blurTextureHeight
  106925. }, this._scene, false, true, textureType);
  106926. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106927. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106928. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  106929. this._blurTexture1.renderParticles = false;
  106930. this._blurTexture1.ignoreCameraViewport = true;
  106931. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  106932. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  106933. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  106934. width: blurTextureWidth2,
  106935. height: blurTextureHeight2
  106936. }, this._scene, false, true, textureType);
  106937. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106938. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106939. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  106940. this._blurTexture2.renderParticles = false;
  106941. this._blurTexture2.ignoreCameraViewport = true;
  106942. this._textures = [this._blurTexture1, this._blurTexture2];
  106943. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  106944. width: blurTextureWidth,
  106945. height: blurTextureHeight
  106946. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106947. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  106948. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  106949. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  106950. effect.setTexture("textureSampler", _this._mainTexture);
  106951. });
  106952. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  106953. width: blurTextureWidth,
  106954. height: blurTextureHeight
  106955. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106956. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  106957. width: blurTextureWidth2,
  106958. height: blurTextureHeight2
  106959. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106960. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  106961. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  106962. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  106963. effect.setTexture("textureSampler", _this._blurTexture1);
  106964. });
  106965. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  106966. width: blurTextureWidth2,
  106967. height: blurTextureHeight2
  106968. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106969. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  106970. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  106971. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  106972. this._mainTexture.samples = this._options.mainTextureSamples;
  106973. this._mainTexture.onAfterUnbindObservable.add(function () {
  106974. var internalTexture = _this._blurTexture1.getInternalTexture();
  106975. if (internalTexture) {
  106976. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  106977. internalTexture = _this._blurTexture2.getInternalTexture();
  106978. if (internalTexture) {
  106979. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  106980. }
  106981. }
  106982. });
  106983. // Prevent autoClear.
  106984. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  106985. };
  106986. /**
  106987. * Checks for the readiness of the element composing the layer.
  106988. * @param subMesh the mesh to check for
  106989. * @param useInstances specify wether or not to use instances to render the mesh
  106990. * @param emissiveTexture the associated emissive texture used to generate the glow
  106991. * @return true if ready otherwise, false
  106992. */
  106993. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  106994. var material = subMesh.getMaterial();
  106995. var mesh = subMesh.getRenderingMesh();
  106996. if (!material || !mesh) {
  106997. return false;
  106998. }
  106999. var emissiveTexture = material.emissiveTexture;
  107000. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  107001. };
  107002. /**
  107003. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  107004. */
  107005. GlowLayer.prototype.needStencil = function () {
  107006. return false;
  107007. };
  107008. /**
  107009. * Implementation specific of rendering the generating effect on the main canvas.
  107010. * @param effect The effect used to render through
  107011. */
  107012. GlowLayer.prototype._internalRender = function (effect) {
  107013. // Texture
  107014. effect.setTexture("textureSampler", this._blurTexture1);
  107015. effect.setTexture("textureSampler2", this._blurTexture2);
  107016. effect.setFloat("offset", this._intensity);
  107017. // Cache
  107018. var engine = this._engine;
  107019. var previousStencilBuffer = engine.getStencilBuffer();
  107020. // Draw order
  107021. engine.setStencilBuffer(false);
  107022. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  107023. // Draw order
  107024. engine.setStencilBuffer(previousStencilBuffer);
  107025. };
  107026. /**
  107027. * Sets the required values for both the emissive texture and and the main color.
  107028. */
  107029. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  107030. var textureLevel = 1.0;
  107031. if (this.customEmissiveTextureSelector) {
  107032. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  107033. }
  107034. else {
  107035. if (material) {
  107036. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  107037. if (this._emissiveTextureAndColor.texture) {
  107038. textureLevel = this._emissiveTextureAndColor.texture.level;
  107039. }
  107040. }
  107041. else {
  107042. this._emissiveTextureAndColor.texture = null;
  107043. }
  107044. }
  107045. if (this.customEmissiveColorSelector) {
  107046. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  107047. }
  107048. else {
  107049. if (material.emissiveColor) {
  107050. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  107051. }
  107052. else {
  107053. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  107054. }
  107055. }
  107056. };
  107057. /**
  107058. * Returns true if the mesh should render, otherwise false.
  107059. * @param mesh The mesh to render
  107060. * @returns true if it should render otherwise false
  107061. */
  107062. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  107063. return this.hasMesh(mesh);
  107064. };
  107065. /**
  107066. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  107067. * @param mesh The mesh to exclude from the glow layer
  107068. */
  107069. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  107070. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  107071. this._excludedMeshes.push(mesh.uniqueId);
  107072. }
  107073. };
  107074. /**
  107075. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  107076. * @param mesh The mesh to remove
  107077. */
  107078. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  107079. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  107080. if (index !== -1) {
  107081. this._excludedMeshes.splice(index, 1);
  107082. }
  107083. };
  107084. /**
  107085. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  107086. * @param mesh The mesh to include in the glow layer
  107087. */
  107088. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  107089. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  107090. this._includedOnlyMeshes.push(mesh.uniqueId);
  107091. }
  107092. };
  107093. /**
  107094. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  107095. * @param mesh The mesh to remove
  107096. */
  107097. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  107098. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  107099. if (index !== -1) {
  107100. this._includedOnlyMeshes.splice(index, 1);
  107101. }
  107102. };
  107103. /**
  107104. * Determine if a given mesh will be used in the glow layer
  107105. * @param mesh The mesh to test
  107106. * @returns true if the mesh will be highlighted by the current glow layer
  107107. */
  107108. GlowLayer.prototype.hasMesh = function (mesh) {
  107109. if (!_super.prototype.hasMesh.call(this, mesh)) {
  107110. return false;
  107111. }
  107112. // Included Mesh
  107113. if (this._includedOnlyMeshes.length) {
  107114. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  107115. }
  107116. ;
  107117. // Excluded Mesh
  107118. if (this._excludedMeshes.length) {
  107119. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  107120. }
  107121. ;
  107122. return true;
  107123. };
  107124. /**
  107125. * Free any resources and references associated to a mesh.
  107126. * Internal use
  107127. * @param mesh The mesh to free.
  107128. * @hidden
  107129. */
  107130. GlowLayer.prototype._disposeMesh = function (mesh) {
  107131. this.removeIncludedOnlyMesh(mesh);
  107132. this.removeExcludedMesh(mesh);
  107133. };
  107134. /**
  107135. * Gets the class name of the effect layer
  107136. * @returns the string with the class name of the effect layer
  107137. */
  107138. GlowLayer.prototype.getClassName = function () {
  107139. return "GlowLayer";
  107140. };
  107141. /**
  107142. * Serializes this glow layer
  107143. * @returns a serialized glow layer object
  107144. */
  107145. GlowLayer.prototype.serialize = function () {
  107146. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  107147. serializationObject.customType = "BABYLON.GlowLayer";
  107148. var index;
  107149. // Included meshes
  107150. serializationObject.includedMeshes = [];
  107151. if (this._includedOnlyMeshes.length) {
  107152. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  107153. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  107154. if (mesh) {
  107155. serializationObject.includedMeshes.push(mesh.id);
  107156. }
  107157. }
  107158. }
  107159. // Excluded meshes
  107160. serializationObject.excludedMeshes = [];
  107161. if (this._excludedMeshes.length) {
  107162. for (index = 0; index < this._excludedMeshes.length; index++) {
  107163. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  107164. if (mesh) {
  107165. serializationObject.excludedMeshes.push(mesh.id);
  107166. }
  107167. }
  107168. }
  107169. return serializationObject;
  107170. };
  107171. /**
  107172. * Creates a Glow Layer from parsed glow layer data
  107173. * @param parsedGlowLayer defines glow layer data
  107174. * @param scene defines the current scene
  107175. * @param rootUrl defines the root URL containing the glow layer information
  107176. * @returns a parsed Glow Layer
  107177. */
  107178. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  107179. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  107180. var index;
  107181. // Excluded meshes
  107182. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  107183. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  107184. if (mesh) {
  107185. gl.addExcludedMesh(mesh);
  107186. }
  107187. }
  107188. // Included meshes
  107189. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  107190. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  107191. if (mesh) {
  107192. gl.addIncludedOnlyMesh(mesh);
  107193. }
  107194. }
  107195. return gl;
  107196. };
  107197. /**
  107198. * Effect Name of the layer.
  107199. */
  107200. GlowLayer.EffectName = "GlowLayer";
  107201. /**
  107202. * The default blur kernel size used for the glow.
  107203. */
  107204. GlowLayer.DefaultBlurKernelSize = 32;
  107205. /**
  107206. * The default texture size ratio used for the glow.
  107207. */
  107208. GlowLayer.DefaultTextureRatio = 0.5;
  107209. __decorate([
  107210. BABYLON.serialize()
  107211. ], GlowLayer.prototype, "blurKernelSize", null);
  107212. __decorate([
  107213. BABYLON.serialize()
  107214. ], GlowLayer.prototype, "intensity", null);
  107215. __decorate([
  107216. BABYLON.serialize("options")
  107217. ], GlowLayer.prototype, "_options", void 0);
  107218. return GlowLayer;
  107219. }(BABYLON.EffectLayer));
  107220. BABYLON.GlowLayer = GlowLayer;
  107221. })(BABYLON || (BABYLON = {}));
  107222. //# sourceMappingURL=babylon.glowLayer.js.map
  107223. var BABYLON;
  107224. (function (BABYLON) {
  107225. /**
  107226. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  107227. */
  107228. var AssetTaskState;
  107229. (function (AssetTaskState) {
  107230. /**
  107231. * Initialization
  107232. */
  107233. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  107234. /**
  107235. * Running
  107236. */
  107237. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  107238. /**
  107239. * Done
  107240. */
  107241. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  107242. /**
  107243. * Error
  107244. */
  107245. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  107246. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  107247. /**
  107248. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  107249. */
  107250. var AbstractAssetTask = /** @class */ (function () {
  107251. /**
  107252. * Creates a new {BABYLON.AssetsManager}
  107253. * @param name defines the name of the task
  107254. */
  107255. function AbstractAssetTask(
  107256. /**
  107257. * Task name
  107258. */ name) {
  107259. this.name = name;
  107260. this._isCompleted = false;
  107261. this._taskState = AssetTaskState.INIT;
  107262. }
  107263. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  107264. /**
  107265. * Get if the task is completed
  107266. */
  107267. get: function () {
  107268. return this._isCompleted;
  107269. },
  107270. enumerable: true,
  107271. configurable: true
  107272. });
  107273. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  107274. /**
  107275. * Gets the current state of the task
  107276. */
  107277. get: function () {
  107278. return this._taskState;
  107279. },
  107280. enumerable: true,
  107281. configurable: true
  107282. });
  107283. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  107284. /**
  107285. * Gets the current error object (if task is in error)
  107286. */
  107287. get: function () {
  107288. return this._errorObject;
  107289. },
  107290. enumerable: true,
  107291. configurable: true
  107292. });
  107293. /**
  107294. * Internal only
  107295. * @hidden
  107296. */
  107297. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  107298. if (this._errorObject) {
  107299. return;
  107300. }
  107301. this._errorObject = {
  107302. message: message,
  107303. exception: exception
  107304. };
  107305. };
  107306. /**
  107307. * Execute the current task
  107308. * @param scene defines the scene where you want your assets to be loaded
  107309. * @param onSuccess is a callback called when the task is successfully executed
  107310. * @param onError is a callback called if an error occurs
  107311. */
  107312. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  107313. var _this = this;
  107314. this._taskState = AssetTaskState.RUNNING;
  107315. this.runTask(scene, function () {
  107316. _this.onDoneCallback(onSuccess, onError);
  107317. }, function (msg, exception) {
  107318. _this.onErrorCallback(onError, msg, exception);
  107319. });
  107320. };
  107321. /**
  107322. * Execute the current task
  107323. * @param scene defines the scene where you want your assets to be loaded
  107324. * @param onSuccess is a callback called when the task is successfully executed
  107325. * @param onError is a callback called if an error occurs
  107326. */
  107327. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107328. throw new Error("runTask is not implemented");
  107329. };
  107330. /**
  107331. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  107332. * This can be used with failed tasks that have the reason for failure fixed.
  107333. */
  107334. AbstractAssetTask.prototype.reset = function () {
  107335. this._taskState = AssetTaskState.INIT;
  107336. };
  107337. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  107338. this._taskState = AssetTaskState.ERROR;
  107339. this._errorObject = {
  107340. message: message,
  107341. exception: exception
  107342. };
  107343. if (this.onError) {
  107344. this.onError(this, message, exception);
  107345. }
  107346. onError();
  107347. };
  107348. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  107349. try {
  107350. this._taskState = AssetTaskState.DONE;
  107351. this._isCompleted = true;
  107352. if (this.onSuccess) {
  107353. this.onSuccess(this);
  107354. }
  107355. onSuccess();
  107356. }
  107357. catch (e) {
  107358. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  107359. }
  107360. };
  107361. return AbstractAssetTask;
  107362. }());
  107363. BABYLON.AbstractAssetTask = AbstractAssetTask;
  107364. /**
  107365. * Class used to share progress information about assets loading
  107366. */
  107367. var AssetsProgressEvent = /** @class */ (function () {
  107368. /**
  107369. * Creates a {BABYLON.AssetsProgressEvent}
  107370. * @param remainingCount defines the number of remaining tasks to process
  107371. * @param totalCount defines the total number of tasks
  107372. * @param task defines the task that was just processed
  107373. */
  107374. function AssetsProgressEvent(remainingCount, totalCount, task) {
  107375. this.remainingCount = remainingCount;
  107376. this.totalCount = totalCount;
  107377. this.task = task;
  107378. }
  107379. return AssetsProgressEvent;
  107380. }());
  107381. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  107382. /**
  107383. * Define a task used by {BABYLON.AssetsManager} to load meshes
  107384. */
  107385. var MeshAssetTask = /** @class */ (function (_super) {
  107386. __extends(MeshAssetTask, _super);
  107387. /**
  107388. * Creates a new {BABYLON.MeshAssetTask}
  107389. * @param name defines the name of the task
  107390. * @param meshesNames defines the list of mesh's names you want to load
  107391. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  107392. * @param sceneFilename defines the filename of the scene to load from
  107393. */
  107394. function MeshAssetTask(
  107395. /**
  107396. * Defines the name of the task
  107397. */
  107398. name,
  107399. /**
  107400. * Defines the list of mesh's names you want to load
  107401. */
  107402. meshesNames,
  107403. /**
  107404. * Defines the root url to use as a base to load your meshes and associated resources
  107405. */
  107406. rootUrl,
  107407. /**
  107408. * Defines the filename of the scene to load from
  107409. */
  107410. sceneFilename) {
  107411. var _this = _super.call(this, name) || this;
  107412. _this.name = name;
  107413. _this.meshesNames = meshesNames;
  107414. _this.rootUrl = rootUrl;
  107415. _this.sceneFilename = sceneFilename;
  107416. return _this;
  107417. }
  107418. /**
  107419. * Execute the current task
  107420. * @param scene defines the scene where you want your assets to be loaded
  107421. * @param onSuccess is a callback called when the task is successfully executed
  107422. * @param onError is a callback called if an error occurs
  107423. */
  107424. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107425. var _this = this;
  107426. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  107427. _this.loadedMeshes = meshes;
  107428. _this.loadedParticleSystems = particleSystems;
  107429. _this.loadedSkeletons = skeletons;
  107430. onSuccess();
  107431. }, null, function (scene, message, exception) {
  107432. onError(message, exception);
  107433. });
  107434. };
  107435. return MeshAssetTask;
  107436. }(AbstractAssetTask));
  107437. BABYLON.MeshAssetTask = MeshAssetTask;
  107438. /**
  107439. * Define a task used by {BABYLON.AssetsManager} to load text content
  107440. */
  107441. var TextFileAssetTask = /** @class */ (function (_super) {
  107442. __extends(TextFileAssetTask, _super);
  107443. /**
  107444. * Creates a new TextFileAssetTask object
  107445. * @param name defines the name of the task
  107446. * @param url defines the location of the file to load
  107447. */
  107448. function TextFileAssetTask(
  107449. /**
  107450. * Defines the name of the task
  107451. */
  107452. name,
  107453. /**
  107454. * Defines the location of the file to load
  107455. */
  107456. url) {
  107457. var _this = _super.call(this, name) || this;
  107458. _this.name = name;
  107459. _this.url = url;
  107460. return _this;
  107461. }
  107462. /**
  107463. * Execute the current task
  107464. * @param scene defines the scene where you want your assets to be loaded
  107465. * @param onSuccess is a callback called when the task is successfully executed
  107466. * @param onError is a callback called if an error occurs
  107467. */
  107468. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107469. var _this = this;
  107470. scene._loadFile(this.url, function (data) {
  107471. _this.text = data;
  107472. onSuccess();
  107473. }, undefined, false, false, function (request, exception) {
  107474. if (request) {
  107475. onError(request.status + " " + request.statusText, exception);
  107476. }
  107477. });
  107478. };
  107479. return TextFileAssetTask;
  107480. }(AbstractAssetTask));
  107481. BABYLON.TextFileAssetTask = TextFileAssetTask;
  107482. /**
  107483. * Define a task used by {BABYLON.AssetsManager} to load binary data
  107484. */
  107485. var BinaryFileAssetTask = /** @class */ (function (_super) {
  107486. __extends(BinaryFileAssetTask, _super);
  107487. /**
  107488. * Creates a new BinaryFileAssetTask object
  107489. * @param name defines the name of the new task
  107490. * @param url defines the location of the file to load
  107491. */
  107492. function BinaryFileAssetTask(
  107493. /**
  107494. * Defines the name of the task
  107495. */
  107496. name,
  107497. /**
  107498. * Defines the location of the file to load
  107499. */
  107500. url) {
  107501. var _this = _super.call(this, name) || this;
  107502. _this.name = name;
  107503. _this.url = url;
  107504. return _this;
  107505. }
  107506. /**
  107507. * Execute the current task
  107508. * @param scene defines the scene where you want your assets to be loaded
  107509. * @param onSuccess is a callback called when the task is successfully executed
  107510. * @param onError is a callback called if an error occurs
  107511. */
  107512. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107513. var _this = this;
  107514. scene._loadFile(this.url, function (data) {
  107515. _this.data = data;
  107516. onSuccess();
  107517. }, undefined, true, true, function (request, exception) {
  107518. if (request) {
  107519. onError(request.status + " " + request.statusText, exception);
  107520. }
  107521. });
  107522. };
  107523. return BinaryFileAssetTask;
  107524. }(AbstractAssetTask));
  107525. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  107526. /**
  107527. * Define a task used by {BABYLON.AssetsManager} to load images
  107528. */
  107529. var ImageAssetTask = /** @class */ (function (_super) {
  107530. __extends(ImageAssetTask, _super);
  107531. /**
  107532. * Creates a new ImageAssetTask
  107533. * @param name defines the name of the task
  107534. * @param url defines the location of the image to load
  107535. */
  107536. function ImageAssetTask(
  107537. /**
  107538. * Defines the name of the task
  107539. */
  107540. name,
  107541. /**
  107542. * Defines the location of the image to load
  107543. */
  107544. url) {
  107545. var _this = _super.call(this, name) || this;
  107546. _this.name = name;
  107547. _this.url = url;
  107548. return _this;
  107549. }
  107550. /**
  107551. * Execute the current task
  107552. * @param scene defines the scene where you want your assets to be loaded
  107553. * @param onSuccess is a callback called when the task is successfully executed
  107554. * @param onError is a callback called if an error occurs
  107555. */
  107556. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107557. var _this = this;
  107558. var img = new Image();
  107559. BABYLON.Tools.SetCorsBehavior(this.url, img);
  107560. img.onload = function () {
  107561. _this.image = img;
  107562. onSuccess();
  107563. };
  107564. img.onerror = function (err) {
  107565. onError("Error loading image", err);
  107566. };
  107567. img.src = this.url;
  107568. };
  107569. return ImageAssetTask;
  107570. }(AbstractAssetTask));
  107571. BABYLON.ImageAssetTask = ImageAssetTask;
  107572. /**
  107573. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  107574. */
  107575. var TextureAssetTask = /** @class */ (function (_super) {
  107576. __extends(TextureAssetTask, _super);
  107577. /**
  107578. * Creates a new TextureAssetTask object
  107579. * @param name defines the name of the task
  107580. * @param url defines the location of the file to load
  107581. * @param noMipmap defines if mipmap should not be generated (default is false)
  107582. * @param invertY defines if texture must be inverted on Y axis (default is false)
  107583. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  107584. */
  107585. function TextureAssetTask(
  107586. /**
  107587. * Defines the name of the task
  107588. */
  107589. name,
  107590. /**
  107591. * Defines the location of the file to load
  107592. */
  107593. url,
  107594. /**
  107595. * Defines if mipmap should not be generated (default is false)
  107596. */
  107597. noMipmap,
  107598. /**
  107599. * Defines if texture must be inverted on Y axis (default is false)
  107600. */
  107601. invertY,
  107602. /**
  107603. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  107604. */
  107605. samplingMode) {
  107606. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  107607. var _this = _super.call(this, name) || this;
  107608. _this.name = name;
  107609. _this.url = url;
  107610. _this.noMipmap = noMipmap;
  107611. _this.invertY = invertY;
  107612. _this.samplingMode = samplingMode;
  107613. return _this;
  107614. }
  107615. /**
  107616. * Execute the current task
  107617. * @param scene defines the scene where you want your assets to be loaded
  107618. * @param onSuccess is a callback called when the task is successfully executed
  107619. * @param onError is a callback called if an error occurs
  107620. */
  107621. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107622. var onload = function () {
  107623. onSuccess();
  107624. };
  107625. var onerror = function (message, exception) {
  107626. onError(message, exception);
  107627. };
  107628. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  107629. };
  107630. return TextureAssetTask;
  107631. }(AbstractAssetTask));
  107632. BABYLON.TextureAssetTask = TextureAssetTask;
  107633. /**
  107634. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  107635. */
  107636. var CubeTextureAssetTask = /** @class */ (function (_super) {
  107637. __extends(CubeTextureAssetTask, _super);
  107638. /**
  107639. * Creates a new CubeTextureAssetTask
  107640. * @param name defines the name of the task
  107641. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  107642. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  107643. * @param noMipmap defines if mipmaps should not be generated (default is false)
  107644. * @param files defines the explicit list of files (undefined by default)
  107645. */
  107646. function CubeTextureAssetTask(
  107647. /**
  107648. * Defines the name of the task
  107649. */
  107650. name,
  107651. /**
  107652. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  107653. */
  107654. url,
  107655. /**
  107656. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  107657. */
  107658. extensions,
  107659. /**
  107660. * Defines if mipmaps should not be generated (default is false)
  107661. */
  107662. noMipmap,
  107663. /**
  107664. * Defines the explicit list of files (undefined by default)
  107665. */
  107666. files) {
  107667. var _this = _super.call(this, name) || this;
  107668. _this.name = name;
  107669. _this.url = url;
  107670. _this.extensions = extensions;
  107671. _this.noMipmap = noMipmap;
  107672. _this.files = files;
  107673. return _this;
  107674. }
  107675. /**
  107676. * Execute the current task
  107677. * @param scene defines the scene where you want your assets to be loaded
  107678. * @param onSuccess is a callback called when the task is successfully executed
  107679. * @param onError is a callback called if an error occurs
  107680. */
  107681. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107682. var onload = function () {
  107683. onSuccess();
  107684. };
  107685. var onerror = function (message, exception) {
  107686. onError(message, exception);
  107687. };
  107688. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  107689. };
  107690. return CubeTextureAssetTask;
  107691. }(AbstractAssetTask));
  107692. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  107693. /**
  107694. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  107695. */
  107696. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  107697. __extends(HDRCubeTextureAssetTask, _super);
  107698. /**
  107699. * Creates a new HDRCubeTextureAssetTask object
  107700. * @param name defines the name of the task
  107701. * @param url defines the location of the file to load
  107702. * @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.
  107703. * @param noMipmap defines if mipmaps should not be generated (default is false)
  107704. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  107705. * @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)
  107706. * @param reserved Internal use only
  107707. */
  107708. function HDRCubeTextureAssetTask(
  107709. /**
  107710. * Defines the name of the task
  107711. */
  107712. name,
  107713. /**
  107714. * Defines the location of the file to load
  107715. */
  107716. url,
  107717. /**
  107718. * Defines the desired size (the more it increases the longer the generation will be)
  107719. */
  107720. size,
  107721. /**
  107722. * Defines if mipmaps should not be generated (default is false)
  107723. */
  107724. noMipmap,
  107725. /**
  107726. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  107727. */
  107728. generateHarmonics,
  107729. /**
  107730. * 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)
  107731. */
  107732. gammaSpace,
  107733. /**
  107734. * Internal Use Only
  107735. */
  107736. reserved) {
  107737. if (noMipmap === void 0) { noMipmap = false; }
  107738. if (generateHarmonics === void 0) { generateHarmonics = true; }
  107739. if (gammaSpace === void 0) { gammaSpace = false; }
  107740. if (reserved === void 0) { reserved = false; }
  107741. var _this = _super.call(this, name) || this;
  107742. _this.name = name;
  107743. _this.url = url;
  107744. _this.size = size;
  107745. _this.noMipmap = noMipmap;
  107746. _this.generateHarmonics = generateHarmonics;
  107747. _this.gammaSpace = gammaSpace;
  107748. _this.reserved = reserved;
  107749. return _this;
  107750. }
  107751. /**
  107752. * Execute the current task
  107753. * @param scene defines the scene where you want your assets to be loaded
  107754. * @param onSuccess is a callback called when the task is successfully executed
  107755. * @param onError is a callback called if an error occurs
  107756. */
  107757. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  107758. var onload = function () {
  107759. onSuccess();
  107760. };
  107761. var onerror = function (message, exception) {
  107762. onError(message, exception);
  107763. };
  107764. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  107765. };
  107766. return HDRCubeTextureAssetTask;
  107767. }(AbstractAssetTask));
  107768. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  107769. /**
  107770. * This class can be used to easily import assets into a scene
  107771. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  107772. */
  107773. var AssetsManager = /** @class */ (function () {
  107774. /**
  107775. * Creates a new AssetsManager
  107776. * @param scene defines the scene to work on
  107777. */
  107778. function AssetsManager(scene) {
  107779. this._isLoading = false;
  107780. this._tasks = new Array();
  107781. this._waitingTasksCount = 0;
  107782. this._totalTasksCount = 0;
  107783. /**
  107784. * Observable called when all tasks are processed
  107785. */
  107786. this.onTaskSuccessObservable = new BABYLON.Observable();
  107787. /**
  107788. * Observable called when a task had an error
  107789. */
  107790. this.onTaskErrorObservable = new BABYLON.Observable();
  107791. /**
  107792. * Observable called when a task is successful
  107793. */
  107794. this.onTasksDoneObservable = new BABYLON.Observable();
  107795. /**
  107796. * Observable called when a task is done (whatever the result is)
  107797. */
  107798. this.onProgressObservable = new BABYLON.Observable();
  107799. /**
  107800. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  107801. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  107802. */
  107803. this.useDefaultLoadingScreen = true;
  107804. this._scene = scene;
  107805. }
  107806. /**
  107807. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  107808. * @param taskName defines the name of the new task
  107809. * @param meshesNames defines the name of meshes to load
  107810. * @param rootUrl defines the root url to use to locate files
  107811. * @param sceneFilename defines the filename of the scene file
  107812. * @returns a new {BABYLON.MeshAssetTask} object
  107813. */
  107814. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  107815. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  107816. this._tasks.push(task);
  107817. return task;
  107818. };
  107819. /**
  107820. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  107821. * @param taskName defines the name of the new task
  107822. * @param url defines the url of the file to load
  107823. * @returns a new {BABYLON.TextFileAssetTask} object
  107824. */
  107825. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  107826. var task = new TextFileAssetTask(taskName, url);
  107827. this._tasks.push(task);
  107828. return task;
  107829. };
  107830. /**
  107831. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  107832. * @param taskName defines the name of the new task
  107833. * @param url defines the url of the file to load
  107834. * @returns a new {BABYLON.BinaryFileAssetTask} object
  107835. */
  107836. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  107837. var task = new BinaryFileAssetTask(taskName, url);
  107838. this._tasks.push(task);
  107839. return task;
  107840. };
  107841. /**
  107842. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  107843. * @param taskName defines the name of the new task
  107844. * @param url defines the url of the file to load
  107845. * @returns a new {BABYLON.ImageAssetTask} object
  107846. */
  107847. AssetsManager.prototype.addImageTask = function (taskName, url) {
  107848. var task = new ImageAssetTask(taskName, url);
  107849. this._tasks.push(task);
  107850. return task;
  107851. };
  107852. /**
  107853. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  107854. * @param taskName defines the name of the new task
  107855. * @param url defines the url of the file to load
  107856. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  107857. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  107858. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  107859. * @returns a new {BABYLON.TextureAssetTask} object
  107860. */
  107861. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  107862. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  107863. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  107864. this._tasks.push(task);
  107865. return task;
  107866. };
  107867. /**
  107868. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  107869. * @param taskName defines the name of the new task
  107870. * @param url defines the url of the file to load
  107871. * @param extensions defines the extension to use to load the cube map (can be null)
  107872. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  107873. * @param files defines the list of files to load (can be null)
  107874. * @returns a new {BABYLON.CubeTextureAssetTask} object
  107875. */
  107876. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  107877. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  107878. this._tasks.push(task);
  107879. return task;
  107880. };
  107881. /**
  107882. *
  107883. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  107884. * @param taskName defines the name of the new task
  107885. * @param url defines the url of the file to load
  107886. * @param size defines the size you want for the cubemap (can be null)
  107887. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  107888. * @param generateHarmonics defines if you want to automatically generate (true by default)
  107889. * @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)
  107890. * @param reserved Internal use only
  107891. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  107892. */
  107893. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  107894. if (noMipmap === void 0) { noMipmap = false; }
  107895. if (generateHarmonics === void 0) { generateHarmonics = true; }
  107896. if (gammaSpace === void 0) { gammaSpace = false; }
  107897. if (reserved === void 0) { reserved = false; }
  107898. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  107899. this._tasks.push(task);
  107900. return task;
  107901. };
  107902. /**
  107903. * Remove a task from the assets manager.
  107904. * @param task the task to remove
  107905. */
  107906. AssetsManager.prototype.removeTask = function (task) {
  107907. var index = this._tasks.indexOf(task);
  107908. if (index > -1) {
  107909. this._tasks.splice(index, 1);
  107910. }
  107911. };
  107912. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  107913. this._waitingTasksCount--;
  107914. try {
  107915. if (this.onProgress) {
  107916. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  107917. }
  107918. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  107919. }
  107920. catch (e) {
  107921. BABYLON.Tools.Error("Error running progress callbacks.");
  107922. console.log(e);
  107923. }
  107924. if (this._waitingTasksCount === 0) {
  107925. try {
  107926. if (this.onFinish) {
  107927. this.onFinish(this._tasks);
  107928. }
  107929. // Let's remove successfull tasks
  107930. var currentTasks = this._tasks.slice();
  107931. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  107932. var task = currentTasks_1[_i];
  107933. if (task.taskState === AssetTaskState.DONE) {
  107934. var index = this._tasks.indexOf(task);
  107935. if (index > -1) {
  107936. this._tasks.splice(index, 1);
  107937. }
  107938. }
  107939. }
  107940. this.onTasksDoneObservable.notifyObservers(this._tasks);
  107941. }
  107942. catch (e) {
  107943. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  107944. console.log(e);
  107945. }
  107946. this._isLoading = false;
  107947. this._scene.getEngine().hideLoadingUI();
  107948. }
  107949. };
  107950. AssetsManager.prototype._runTask = function (task) {
  107951. var _this = this;
  107952. var done = function () {
  107953. try {
  107954. if (_this.onTaskSuccess) {
  107955. _this.onTaskSuccess(task);
  107956. }
  107957. _this.onTaskSuccessObservable.notifyObservers(task);
  107958. _this._decreaseWaitingTasksCount(task);
  107959. }
  107960. catch (e) {
  107961. error("Error executing task success callbacks", e);
  107962. }
  107963. };
  107964. var error = function (message, exception) {
  107965. task._setErrorObject(message, exception);
  107966. if (_this.onTaskError) {
  107967. _this.onTaskError(task);
  107968. }
  107969. _this.onTaskErrorObservable.notifyObservers(task);
  107970. _this._decreaseWaitingTasksCount(task);
  107971. };
  107972. task.run(this._scene, done, error);
  107973. };
  107974. /**
  107975. * Reset the {BABYLON.AssetsManager} and remove all tasks
  107976. * @return the current instance of the {BABYLON.AssetsManager}
  107977. */
  107978. AssetsManager.prototype.reset = function () {
  107979. this._isLoading = false;
  107980. this._tasks = new Array();
  107981. return this;
  107982. };
  107983. /**
  107984. * Start the loading process
  107985. * @return the current instance of the {BABYLON.AssetsManager}
  107986. */
  107987. AssetsManager.prototype.load = function () {
  107988. if (this._isLoading) {
  107989. return this;
  107990. }
  107991. this._isLoading = true;
  107992. this._waitingTasksCount = this._tasks.length;
  107993. this._totalTasksCount = this._tasks.length;
  107994. if (this._waitingTasksCount === 0) {
  107995. this._isLoading = false;
  107996. if (this.onFinish) {
  107997. this.onFinish(this._tasks);
  107998. }
  107999. this.onTasksDoneObservable.notifyObservers(this._tasks);
  108000. return this;
  108001. }
  108002. if (this.useDefaultLoadingScreen) {
  108003. this._scene.getEngine().displayLoadingUI();
  108004. }
  108005. for (var index = 0; index < this._tasks.length; index++) {
  108006. var task = this._tasks[index];
  108007. if (task.taskState === AssetTaskState.INIT) {
  108008. this._runTask(task);
  108009. }
  108010. }
  108011. return this;
  108012. };
  108013. return AssetsManager;
  108014. }());
  108015. BABYLON.AssetsManager = AssetsManager;
  108016. })(BABYLON || (BABYLON = {}));
  108017. //# sourceMappingURL=babylon.assetsManager.js.map
  108018. var BABYLON;
  108019. (function (BABYLON) {
  108020. var serializedGeometries = [];
  108021. var serializeGeometry = function (geometry, serializationGeometries) {
  108022. if (serializedGeometries[geometry.id]) {
  108023. return;
  108024. }
  108025. if (geometry.doNotSerialize) {
  108026. return;
  108027. }
  108028. if (geometry instanceof BABYLON.BoxGeometry) {
  108029. serializationGeometries.boxes.push(geometry.serialize());
  108030. }
  108031. else if (geometry instanceof BABYLON.SphereGeometry) {
  108032. serializationGeometries.spheres.push(geometry.serialize());
  108033. }
  108034. else if (geometry instanceof BABYLON.CylinderGeometry) {
  108035. serializationGeometries.cylinders.push(geometry.serialize());
  108036. }
  108037. else if (geometry instanceof BABYLON.TorusGeometry) {
  108038. serializationGeometries.toruses.push(geometry.serialize());
  108039. }
  108040. else if (geometry instanceof BABYLON.GroundGeometry) {
  108041. serializationGeometries.grounds.push(geometry.serialize());
  108042. }
  108043. else if (geometry instanceof BABYLON.Plane) {
  108044. serializationGeometries.planes.push(geometry.serialize());
  108045. }
  108046. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  108047. serializationGeometries.torusKnots.push(geometry.serialize());
  108048. }
  108049. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  108050. throw new Error("Unknown primitive type");
  108051. }
  108052. else {
  108053. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  108054. }
  108055. serializedGeometries[geometry.id] = true;
  108056. };
  108057. var serializeMesh = function (mesh, serializationScene) {
  108058. var serializationObject = {};
  108059. // Geometry
  108060. var geometry = mesh._geometry;
  108061. if (geometry) {
  108062. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  108063. // 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
  108064. serializeGeometry(geometry, serializationScene.geometries);
  108065. }
  108066. }
  108067. // Custom
  108068. if (mesh.serialize) {
  108069. mesh.serialize(serializationObject);
  108070. }
  108071. return serializationObject;
  108072. };
  108073. var finalizeSingleMesh = function (mesh, serializationObject) {
  108074. //only works if the mesh is already loaded
  108075. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  108076. //serialize material
  108077. if (mesh.material) {
  108078. if (mesh.material instanceof BABYLON.MultiMaterial) {
  108079. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  108080. serializationObject.materials = serializationObject.materials || [];
  108081. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  108082. serializationObject.multiMaterials.push(mesh.material.serialize());
  108083. var _loop_1 = function (submaterial) {
  108084. if (submaterial) {
  108085. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  108086. serializationObject.materials.push(submaterial.serialize());
  108087. }
  108088. }
  108089. };
  108090. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  108091. var submaterial = _a[_i];
  108092. _loop_1(submaterial);
  108093. }
  108094. }
  108095. }
  108096. else {
  108097. serializationObject.materials = serializationObject.materials || [];
  108098. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  108099. serializationObject.materials.push(mesh.material.serialize());
  108100. }
  108101. }
  108102. }
  108103. //serialize geometry
  108104. var geometry = mesh._geometry;
  108105. if (geometry) {
  108106. if (!serializationObject.geometries) {
  108107. serializationObject.geometries = {};
  108108. serializationObject.geometries.boxes = [];
  108109. serializationObject.geometries.spheres = [];
  108110. serializationObject.geometries.cylinders = [];
  108111. serializationObject.geometries.toruses = [];
  108112. serializationObject.geometries.grounds = [];
  108113. serializationObject.geometries.planes = [];
  108114. serializationObject.geometries.torusKnots = [];
  108115. serializationObject.geometries.vertexData = [];
  108116. }
  108117. serializeGeometry(geometry, serializationObject.geometries);
  108118. }
  108119. // Skeletons
  108120. if (mesh.skeleton) {
  108121. serializationObject.skeletons = serializationObject.skeletons || [];
  108122. serializationObject.skeletons.push(mesh.skeleton.serialize());
  108123. }
  108124. //serialize the actual mesh
  108125. serializationObject.meshes = serializationObject.meshes || [];
  108126. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  108127. }
  108128. };
  108129. /**
  108130. * Class used to serialize a scene into a string
  108131. */
  108132. var SceneSerializer = /** @class */ (function () {
  108133. function SceneSerializer() {
  108134. }
  108135. /**
  108136. * Clear cache used by a previous serialization
  108137. */
  108138. SceneSerializer.ClearCache = function () {
  108139. serializedGeometries = [];
  108140. };
  108141. /**
  108142. * Serialize a scene into a JSON compatible object
  108143. * @param scene defines the scene to serialize
  108144. * @returns a JSON compatible object
  108145. */
  108146. SceneSerializer.Serialize = function (scene) {
  108147. var serializationObject = {};
  108148. SceneSerializer.ClearCache();
  108149. // Scene
  108150. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  108151. serializationObject.autoClear = scene.autoClear;
  108152. serializationObject.clearColor = scene.clearColor.asArray();
  108153. serializationObject.ambientColor = scene.ambientColor.asArray();
  108154. serializationObject.gravity = scene.gravity.asArray();
  108155. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  108156. serializationObject.workerCollisions = scene.workerCollisions;
  108157. // Fog
  108158. if (scene.fogMode && scene.fogMode !== 0) {
  108159. serializationObject.fogMode = scene.fogMode;
  108160. serializationObject.fogColor = scene.fogColor.asArray();
  108161. serializationObject.fogStart = scene.fogStart;
  108162. serializationObject.fogEnd = scene.fogEnd;
  108163. serializationObject.fogDensity = scene.fogDensity;
  108164. }
  108165. //Physics
  108166. if (scene.isPhysicsEnabled()) {
  108167. var physicEngine = scene.getPhysicsEngine();
  108168. if (physicEngine) {
  108169. serializationObject.physicsEnabled = true;
  108170. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  108171. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  108172. }
  108173. }
  108174. // Metadata
  108175. if (scene.metadata) {
  108176. serializationObject.metadata = scene.metadata;
  108177. }
  108178. // Morph targets
  108179. serializationObject.morphTargetManagers = [];
  108180. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  108181. var abstractMesh = _a[_i];
  108182. var manager = abstractMesh.morphTargetManager;
  108183. if (manager) {
  108184. serializationObject.morphTargetManagers.push(manager.serialize());
  108185. }
  108186. }
  108187. // Lights
  108188. serializationObject.lights = [];
  108189. var index;
  108190. var light;
  108191. for (index = 0; index < scene.lights.length; index++) {
  108192. light = scene.lights[index];
  108193. if (!light.doNotSerialize) {
  108194. serializationObject.lights.push(light.serialize());
  108195. }
  108196. }
  108197. // Cameras
  108198. serializationObject.cameras = [];
  108199. for (index = 0; index < scene.cameras.length; index++) {
  108200. var camera = scene.cameras[index];
  108201. if (!camera.doNotSerialize) {
  108202. serializationObject.cameras.push(camera.serialize());
  108203. }
  108204. }
  108205. if (scene.activeCamera) {
  108206. serializationObject.activeCameraID = scene.activeCamera.id;
  108207. }
  108208. // Animations
  108209. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  108210. // Materials
  108211. serializationObject.materials = [];
  108212. serializationObject.multiMaterials = [];
  108213. var material;
  108214. for (index = 0; index < scene.materials.length; index++) {
  108215. material = scene.materials[index];
  108216. if (!material.doNotSerialize) {
  108217. serializationObject.materials.push(material.serialize());
  108218. }
  108219. }
  108220. // MultiMaterials
  108221. serializationObject.multiMaterials = [];
  108222. for (index = 0; index < scene.multiMaterials.length; index++) {
  108223. var multiMaterial = scene.multiMaterials[index];
  108224. serializationObject.multiMaterials.push(multiMaterial.serialize());
  108225. }
  108226. // Environment texture
  108227. if (scene.environmentTexture) {
  108228. serializationObject.environmentTexture = scene.environmentTexture.name;
  108229. }
  108230. // Skeletons
  108231. serializationObject.skeletons = [];
  108232. for (index = 0; index < scene.skeletons.length; index++) {
  108233. var skeleton = scene.skeletons[index];
  108234. if (!skeleton.doNotSerialize) {
  108235. serializationObject.skeletons.push(skeleton.serialize());
  108236. }
  108237. }
  108238. // Transform nodes
  108239. serializationObject.transformNodes = [];
  108240. for (index = 0; index < scene.transformNodes.length; index++) {
  108241. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  108242. }
  108243. // Geometries
  108244. serializationObject.geometries = {};
  108245. serializationObject.geometries.boxes = [];
  108246. serializationObject.geometries.spheres = [];
  108247. serializationObject.geometries.cylinders = [];
  108248. serializationObject.geometries.toruses = [];
  108249. serializationObject.geometries.grounds = [];
  108250. serializationObject.geometries.planes = [];
  108251. serializationObject.geometries.torusKnots = [];
  108252. serializationObject.geometries.vertexData = [];
  108253. serializedGeometries = [];
  108254. var geometries = scene.getGeometries();
  108255. for (index = 0; index < geometries.length; index++) {
  108256. var geometry = geometries[index];
  108257. if (geometry.isReady()) {
  108258. serializeGeometry(geometry, serializationObject.geometries);
  108259. }
  108260. }
  108261. // Meshes
  108262. serializationObject.meshes = [];
  108263. for (index = 0; index < scene.meshes.length; index++) {
  108264. var abstractMesh = scene.meshes[index];
  108265. if (abstractMesh instanceof BABYLON.Mesh) {
  108266. var mesh = abstractMesh;
  108267. if (!mesh.doNotSerialize) {
  108268. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  108269. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  108270. }
  108271. }
  108272. }
  108273. }
  108274. // Particles Systems
  108275. serializationObject.particleSystems = [];
  108276. for (index = 0; index < scene.particleSystems.length; index++) {
  108277. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  108278. }
  108279. // Action Manager
  108280. if (scene.actionManager) {
  108281. serializationObject.actions = scene.actionManager.serialize("scene");
  108282. }
  108283. // Components
  108284. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  108285. var component = _c[_b];
  108286. component.serialize(serializationObject);
  108287. }
  108288. return serializationObject;
  108289. };
  108290. /**
  108291. * Serialize a mesh into a JSON compatible object
  108292. * @param toSerialize defines the mesh to serialize
  108293. * @param withParents defines if parents must be serialized as well
  108294. * @param withChildren defines if children must be serialized as well
  108295. * @returns a JSON compatible object
  108296. */
  108297. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  108298. if (withParents === void 0) { withParents = false; }
  108299. if (withChildren === void 0) { withChildren = false; }
  108300. var serializationObject = {};
  108301. SceneSerializer.ClearCache();
  108302. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  108303. if (withParents || withChildren) {
  108304. //deliberate for loop! not for each, appended should be processed as well.
  108305. for (var i = 0; i < toSerialize.length; ++i) {
  108306. if (withChildren) {
  108307. toSerialize[i].getDescendants().forEach(function (node) {
  108308. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  108309. toSerialize.push(node);
  108310. }
  108311. });
  108312. }
  108313. //make sure the array doesn't contain the object already
  108314. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  108315. toSerialize.push(toSerialize[i].parent);
  108316. }
  108317. }
  108318. }
  108319. toSerialize.forEach(function (mesh) {
  108320. finalizeSingleMesh(mesh, serializationObject);
  108321. });
  108322. return serializationObject;
  108323. };
  108324. return SceneSerializer;
  108325. }());
  108326. BABYLON.SceneSerializer = SceneSerializer;
  108327. })(BABYLON || (BABYLON = {}));
  108328. //# sourceMappingURL=babylon.sceneSerializer.js.map
  108329. var BABYLON;
  108330. (function (BABYLON) {
  108331. /**
  108332. * Class used to generate realtime reflection / refraction cube textures
  108333. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  108334. */
  108335. var ReflectionProbe = /** @class */ (function () {
  108336. /**
  108337. * Creates a new reflection probe
  108338. * @param name defines the name of the probe
  108339. * @param size defines the texture resolution (for each face)
  108340. * @param scene defines the hosting scene
  108341. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  108342. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  108343. */
  108344. function ReflectionProbe(
  108345. /** defines the name of the probe */
  108346. name, size, scene, generateMipMaps, useFloat) {
  108347. if (generateMipMaps === void 0) { generateMipMaps = true; }
  108348. if (useFloat === void 0) { useFloat = false; }
  108349. var _this = this;
  108350. this.name = name;
  108351. this._viewMatrix = BABYLON.Matrix.Identity();
  108352. this._target = BABYLON.Vector3.Zero();
  108353. this._add = BABYLON.Vector3.Zero();
  108354. this._invertYAxis = false;
  108355. /** Gets or sets probe position (center of the cube map) */
  108356. this.position = BABYLON.Vector3.Zero();
  108357. this._scene = scene;
  108358. // Create the scene field if not exist.
  108359. if (!this._scene.reflectionProbes) {
  108360. this._scene.reflectionProbes = new Array();
  108361. }
  108362. this._scene.reflectionProbes.push(this);
  108363. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  108364. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  108365. switch (faceIndex) {
  108366. case 0:
  108367. _this._add.copyFromFloats(1, 0, 0);
  108368. break;
  108369. case 1:
  108370. _this._add.copyFromFloats(-1, 0, 0);
  108371. break;
  108372. case 2:
  108373. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  108374. break;
  108375. case 3:
  108376. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  108377. break;
  108378. case 4:
  108379. _this._add.copyFromFloats(0, 0, 1);
  108380. break;
  108381. case 5:
  108382. _this._add.copyFromFloats(0, 0, -1);
  108383. break;
  108384. }
  108385. if (_this._attachedMesh) {
  108386. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  108387. }
  108388. _this.position.addToRef(_this._add, _this._target);
  108389. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  108390. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  108391. scene._forcedViewPosition = _this.position;
  108392. });
  108393. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  108394. scene._forcedViewPosition = null;
  108395. scene.updateTransformMatrix(true);
  108396. });
  108397. if (scene.activeCamera) {
  108398. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  108399. }
  108400. }
  108401. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  108402. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  108403. get: function () {
  108404. return this._renderTargetTexture.samples;
  108405. },
  108406. set: function (value) {
  108407. this._renderTargetTexture.samples = value;
  108408. },
  108409. enumerable: true,
  108410. configurable: true
  108411. });
  108412. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  108413. /** Gets or sets the refresh rate to use (on every frame by default) */
  108414. get: function () {
  108415. return this._renderTargetTexture.refreshRate;
  108416. },
  108417. set: function (value) {
  108418. this._renderTargetTexture.refreshRate = value;
  108419. },
  108420. enumerable: true,
  108421. configurable: true
  108422. });
  108423. /**
  108424. * Gets the hosting scene
  108425. * @returns a Scene
  108426. */
  108427. ReflectionProbe.prototype.getScene = function () {
  108428. return this._scene;
  108429. };
  108430. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  108431. /** Gets the internal CubeTexture used to render to */
  108432. get: function () {
  108433. return this._renderTargetTexture;
  108434. },
  108435. enumerable: true,
  108436. configurable: true
  108437. });
  108438. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  108439. /** Gets the list of meshes to render */
  108440. get: function () {
  108441. return this._renderTargetTexture.renderList;
  108442. },
  108443. enumerable: true,
  108444. configurable: true
  108445. });
  108446. /**
  108447. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  108448. * @param mesh defines the mesh to attach to
  108449. */
  108450. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  108451. this._attachedMesh = mesh;
  108452. };
  108453. /**
  108454. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  108455. * @param renderingGroupId The rendering group id corresponding to its index
  108456. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  108457. */
  108458. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  108459. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  108460. };
  108461. /**
  108462. * Clean all associated resources
  108463. */
  108464. ReflectionProbe.prototype.dispose = function () {
  108465. var index = this._scene.reflectionProbes.indexOf(this);
  108466. if (index !== -1) {
  108467. // Remove from the scene if found
  108468. this._scene.reflectionProbes.splice(index, 1);
  108469. }
  108470. if (this._renderTargetTexture) {
  108471. this._renderTargetTexture.dispose();
  108472. this._renderTargetTexture = null;
  108473. }
  108474. };
  108475. return ReflectionProbe;
  108476. }());
  108477. BABYLON.ReflectionProbe = ReflectionProbe;
  108478. })(BABYLON || (BABYLON = {}));
  108479. //# sourceMappingURL=babylon.reflectionProbe.js.map
  108480. var BABYLON;
  108481. (function (BABYLON) {
  108482. /**
  108483. * Defines the layer scene component responsible to manage any layers
  108484. * in a given scene.
  108485. */
  108486. var LayerSceneComponent = /** @class */ (function () {
  108487. /**
  108488. * Creates a new instance of the component for the given scene
  108489. * @param scene Defines the scene to register the component in
  108490. */
  108491. function LayerSceneComponent(scene) {
  108492. /**
  108493. * The component name helpfull to identify the component in the list of scene components.
  108494. */
  108495. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  108496. this.scene = scene;
  108497. this._engine = scene.getEngine();
  108498. scene.layers = new Array();
  108499. }
  108500. /**
  108501. * Registers the component in a given scene
  108502. */
  108503. LayerSceneComponent.prototype.register = function () {
  108504. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  108505. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  108506. };
  108507. /**
  108508. * Rebuilds the elements related to this component in case of
  108509. * context lost for instance.
  108510. */
  108511. LayerSceneComponent.prototype.rebuild = function () {
  108512. var layers = this.scene.layers;
  108513. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  108514. var layer = layers_1[_i];
  108515. layer._rebuild();
  108516. }
  108517. };
  108518. /**
  108519. * Disposes the component and the associated ressources.
  108520. */
  108521. LayerSceneComponent.prototype.dispose = function () {
  108522. var layers = this.scene.layers;
  108523. while (layers.length) {
  108524. layers[0].dispose();
  108525. }
  108526. };
  108527. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  108528. var layers = this.scene.layers;
  108529. if (layers.length) {
  108530. this._engine.setDepthBuffer(false);
  108531. var cameraLayerMask = camera.layerMask;
  108532. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  108533. var layer = layers_2[_i];
  108534. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  108535. layer.render();
  108536. }
  108537. }
  108538. this._engine.setDepthBuffer(true);
  108539. }
  108540. };
  108541. LayerSceneComponent.prototype._drawBackground = function (camera) {
  108542. this._draw(camera, true);
  108543. };
  108544. LayerSceneComponent.prototype._drawForeground = function (camera) {
  108545. this._draw(camera, false);
  108546. };
  108547. return LayerSceneComponent;
  108548. }());
  108549. BABYLON.LayerSceneComponent = LayerSceneComponent;
  108550. })(BABYLON || (BABYLON = {}));
  108551. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  108552. var BABYLON;
  108553. (function (BABYLON) {
  108554. /**
  108555. * This represents a full screen 2d layer.
  108556. * This can be usefull to display a picture in the background of your scene for instance.
  108557. * @see https://www.babylonjs-playground.com/#08A2BS#1
  108558. */
  108559. var Layer = /** @class */ (function () {
  108560. /**
  108561. * Instantiates a new layer.
  108562. * This represents a full screen 2d layer.
  108563. * This can be usefull to display a picture in the background of your scene for instance.
  108564. * @see https://www.babylonjs-playground.com/#08A2BS#1
  108565. * @param name Define the name of the layer in the scene
  108566. * @param imgUrl Define the url of the texture to display in the layer
  108567. * @param scene Define the scene the layer belongs to
  108568. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  108569. * @param color Defines a color for the layer
  108570. */
  108571. function Layer(
  108572. /**
  108573. * Define the name of the layer.
  108574. */
  108575. name, imgUrl, scene, isBackground, color) {
  108576. this.name = name;
  108577. /**
  108578. * Define the scale of the layer in order to zoom in out of the texture.
  108579. */
  108580. this.scale = new BABYLON.Vector2(1, 1);
  108581. /**
  108582. * Define an offset for the layer in order to shift the texture.
  108583. */
  108584. this.offset = new BABYLON.Vector2(0, 0);
  108585. /**
  108586. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  108587. */
  108588. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  108589. /**
  108590. * Define a mask to restrict the layer to only some of the scene cameras.
  108591. */
  108592. this.layerMask = 0x0FFFFFFF;
  108593. this._vertexBuffers = {};
  108594. /**
  108595. * An event triggered when the layer is disposed.
  108596. */
  108597. this.onDisposeObservable = new BABYLON.Observable();
  108598. /**
  108599. * An event triggered before rendering the scene
  108600. */
  108601. this.onBeforeRenderObservable = new BABYLON.Observable();
  108602. /**
  108603. * An event triggered after rendering the scene
  108604. */
  108605. this.onAfterRenderObservable = new BABYLON.Observable();
  108606. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  108607. this.isBackground = isBackground === undefined ? true : isBackground;
  108608. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  108609. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  108610. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  108611. if (!layerComponent) {
  108612. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  108613. this._scene._addComponent(layerComponent);
  108614. }
  108615. this._scene.layers.push(this);
  108616. var engine = this._scene.getEngine();
  108617. // VBO
  108618. var vertices = [];
  108619. vertices.push(1, 1);
  108620. vertices.push(-1, 1);
  108621. vertices.push(-1, -1);
  108622. vertices.push(1, -1);
  108623. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  108624. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  108625. this._createIndexBuffer();
  108626. // Effects
  108627. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  108628. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  108629. }
  108630. Object.defineProperty(Layer.prototype, "onDispose", {
  108631. /**
  108632. * Back compatibility with callback before the onDisposeObservable existed.
  108633. * The set callback will be triggered when the layer has been disposed.
  108634. */
  108635. set: function (callback) {
  108636. if (this._onDisposeObserver) {
  108637. this.onDisposeObservable.remove(this._onDisposeObserver);
  108638. }
  108639. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  108640. },
  108641. enumerable: true,
  108642. configurable: true
  108643. });
  108644. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  108645. /**
  108646. * Back compatibility with callback before the onBeforeRenderObservable existed.
  108647. * The set callback will be triggered just before rendering the layer.
  108648. */
  108649. set: function (callback) {
  108650. if (this._onBeforeRenderObserver) {
  108651. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  108652. }
  108653. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  108654. },
  108655. enumerable: true,
  108656. configurable: true
  108657. });
  108658. Object.defineProperty(Layer.prototype, "onAfterRender", {
  108659. /**
  108660. * Back compatibility with callback before the onAfterRenderObservable existed.
  108661. * The set callback will be triggered just after rendering the layer.
  108662. */
  108663. set: function (callback) {
  108664. if (this._onAfterRenderObserver) {
  108665. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  108666. }
  108667. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  108668. },
  108669. enumerable: true,
  108670. configurable: true
  108671. });
  108672. Layer.prototype._createIndexBuffer = function () {
  108673. var engine = this._scene.getEngine();
  108674. // Indices
  108675. var indices = [];
  108676. indices.push(0);
  108677. indices.push(1);
  108678. indices.push(2);
  108679. indices.push(0);
  108680. indices.push(2);
  108681. indices.push(3);
  108682. this._indexBuffer = engine.createIndexBuffer(indices);
  108683. };
  108684. /** @hidden */
  108685. Layer.prototype._rebuild = function () {
  108686. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  108687. if (vb) {
  108688. vb._rebuild();
  108689. }
  108690. this._createIndexBuffer();
  108691. };
  108692. /**
  108693. * Renders the layer in the scene.
  108694. */
  108695. Layer.prototype.render = function () {
  108696. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  108697. // Check
  108698. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  108699. return;
  108700. var engine = this._scene.getEngine();
  108701. this.onBeforeRenderObservable.notifyObservers(this);
  108702. // Render
  108703. engine.enableEffect(currentEffect);
  108704. engine.setState(false);
  108705. // Texture
  108706. currentEffect.setTexture("textureSampler", this.texture);
  108707. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  108708. // Color
  108709. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  108710. // Scale / offset
  108711. currentEffect.setVector2("offset", this.offset);
  108712. currentEffect.setVector2("scale", this.scale);
  108713. // VBOs
  108714. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  108715. // Draw order
  108716. if (!this.alphaTest) {
  108717. engine.setAlphaMode(this.alphaBlendingMode);
  108718. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108719. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  108720. }
  108721. else {
  108722. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108723. }
  108724. this.onAfterRenderObservable.notifyObservers(this);
  108725. };
  108726. /**
  108727. * Disposes and releases the associated ressources.
  108728. */
  108729. Layer.prototype.dispose = function () {
  108730. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  108731. if (vertexBuffer) {
  108732. vertexBuffer.dispose();
  108733. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  108734. }
  108735. if (this._indexBuffer) {
  108736. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  108737. this._indexBuffer = null;
  108738. }
  108739. if (this.texture) {
  108740. this.texture.dispose();
  108741. this.texture = null;
  108742. }
  108743. // Remove from scene
  108744. var index = this._scene.layers.indexOf(this);
  108745. this._scene.layers.splice(index, 1);
  108746. // Callback
  108747. this.onDisposeObservable.notifyObservers(this);
  108748. this.onDisposeObservable.clear();
  108749. this.onAfterRenderObservable.clear();
  108750. this.onBeforeRenderObservable.clear();
  108751. };
  108752. return Layer;
  108753. }());
  108754. BABYLON.Layer = Layer;
  108755. })(BABYLON || (BABYLON = {}));
  108756. //# sourceMappingURL=babylon.layer.js.map
  108757. var BABYLON;
  108758. (function (BABYLON) {
  108759. /**
  108760. * Class used to host texture specific utilities
  108761. */
  108762. var TextureTools = /** @class */ (function () {
  108763. function TextureTools() {
  108764. }
  108765. /**
  108766. * Uses the GPU to create a copy texture rescaled at a given size
  108767. * @param texture Texture to copy from
  108768. * @param width defines the desired width
  108769. * @param height defines the desired height
  108770. * @param useBilinearMode defines if bilinear mode has to be used
  108771. * @return the generated texture
  108772. */
  108773. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  108774. if (useBilinearMode === void 0) { useBilinearMode = true; }
  108775. var scene = texture.getScene();
  108776. var engine = scene.getEngine();
  108777. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  108778. rtt.wrapU = texture.wrapU;
  108779. rtt.wrapV = texture.wrapV;
  108780. rtt.uOffset = texture.uOffset;
  108781. rtt.vOffset = texture.vOffset;
  108782. rtt.uScale = texture.uScale;
  108783. rtt.vScale = texture.vScale;
  108784. rtt.uAng = texture.uAng;
  108785. rtt.vAng = texture.vAng;
  108786. rtt.wAng = texture.wAng;
  108787. rtt.coordinatesIndex = texture.coordinatesIndex;
  108788. rtt.level = texture.level;
  108789. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  108790. rtt._texture.isReady = false;
  108791. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108792. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108793. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  108794. passPostProcess.getEffect().executeWhenCompiled(function () {
  108795. passPostProcess.onApply = function (effect) {
  108796. effect.setTexture("textureSampler", texture);
  108797. };
  108798. var internalTexture = rtt.getInternalTexture();
  108799. if (internalTexture) {
  108800. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  108801. engine.unBindFramebuffer(internalTexture);
  108802. rtt.disposeFramebufferObjects();
  108803. passPostProcess.dispose();
  108804. internalTexture.isReady = true;
  108805. }
  108806. });
  108807. return rtt;
  108808. };
  108809. /**
  108810. * Gets an environment BRDF texture for a given scene
  108811. * @param scene defines the hosting scene
  108812. * @returns the environment BRDF texture
  108813. */
  108814. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  108815. if (!scene._environmentBRDFTexture) {
  108816. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  108817. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108818. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108819. scene._environmentBRDFTexture = texture;
  108820. }
  108821. return scene._environmentBRDFTexture;
  108822. };
  108823. 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=";
  108824. return TextureTools;
  108825. }());
  108826. BABYLON.TextureTools = TextureTools;
  108827. })(BABYLON || (BABYLON = {}));
  108828. //# sourceMappingURL=babylon.textureTools.js.map
  108829. var BABYLON;
  108830. (function (BABYLON) {
  108831. /**
  108832. * 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.
  108833. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  108834. */
  108835. var FramingBehavior = /** @class */ (function () {
  108836. function FramingBehavior() {
  108837. this._mode = FramingBehavior.FitFrustumSidesMode;
  108838. this._radiusScale = 1.0;
  108839. this._positionScale = 0.5;
  108840. this._defaultElevation = 0.3;
  108841. this._elevationReturnTime = 1500;
  108842. this._elevationReturnWaitTime = 1000;
  108843. this._zoomStopsAnimation = false;
  108844. this._framingTime = 1500;
  108845. /**
  108846. * Define if the behavior should automatically change the configured
  108847. * camera limits and sensibilities.
  108848. */
  108849. this.autoCorrectCameraLimitsAndSensibility = true;
  108850. this._isPointerDown = false;
  108851. this._lastInteractionTime = -Infinity;
  108852. // Framing control
  108853. this._animatables = new Array();
  108854. this._betaIsAnimating = false;
  108855. }
  108856. Object.defineProperty(FramingBehavior.prototype, "name", {
  108857. /**
  108858. * Gets the name of the behavior.
  108859. */
  108860. get: function () {
  108861. return "Framing";
  108862. },
  108863. enumerable: true,
  108864. configurable: true
  108865. });
  108866. Object.defineProperty(FramingBehavior.prototype, "mode", {
  108867. /**
  108868. * Gets current mode used by the behavior.
  108869. */
  108870. get: function () {
  108871. return this._mode;
  108872. },
  108873. /**
  108874. * Sets the current mode used by the behavior
  108875. */
  108876. set: function (mode) {
  108877. this._mode = mode;
  108878. },
  108879. enumerable: true,
  108880. configurable: true
  108881. });
  108882. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  108883. /**
  108884. * Gets the scale applied to the radius
  108885. */
  108886. get: function () {
  108887. return this._radiusScale;
  108888. },
  108889. /**
  108890. * Sets the scale applied to the radius (1 by default)
  108891. */
  108892. set: function (radius) {
  108893. this._radiusScale = radius;
  108894. },
  108895. enumerable: true,
  108896. configurable: true
  108897. });
  108898. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  108899. /**
  108900. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  108901. */
  108902. get: function () {
  108903. return this._positionScale;
  108904. },
  108905. /**
  108906. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  108907. */
  108908. set: function (scale) {
  108909. this._positionScale = scale;
  108910. },
  108911. enumerable: true,
  108912. configurable: true
  108913. });
  108914. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  108915. /**
  108916. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  108917. * behaviour is triggered, in radians.
  108918. */
  108919. get: function () {
  108920. return this._defaultElevation;
  108921. },
  108922. /**
  108923. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  108924. * behaviour is triggered, in radians.
  108925. */
  108926. set: function (elevation) {
  108927. this._defaultElevation = elevation;
  108928. },
  108929. enumerable: true,
  108930. configurable: true
  108931. });
  108932. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  108933. /**
  108934. * Gets the time (in milliseconds) taken to return to the default beta position.
  108935. * Negative value indicates camera should not return to default.
  108936. */
  108937. get: function () {
  108938. return this._elevationReturnTime;
  108939. },
  108940. /**
  108941. * Sets the time (in milliseconds) taken to return to the default beta position.
  108942. * Negative value indicates camera should not return to default.
  108943. */
  108944. set: function (speed) {
  108945. this._elevationReturnTime = speed;
  108946. },
  108947. enumerable: true,
  108948. configurable: true
  108949. });
  108950. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  108951. /**
  108952. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  108953. */
  108954. get: function () {
  108955. return this._elevationReturnWaitTime;
  108956. },
  108957. /**
  108958. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  108959. */
  108960. set: function (time) {
  108961. this._elevationReturnWaitTime = time;
  108962. },
  108963. enumerable: true,
  108964. configurable: true
  108965. });
  108966. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  108967. /**
  108968. * Gets the flag that indicates if user zooming should stop animation.
  108969. */
  108970. get: function () {
  108971. return this._zoomStopsAnimation;
  108972. },
  108973. /**
  108974. * Sets the flag that indicates if user zooming should stop animation.
  108975. */
  108976. set: function (flag) {
  108977. this._zoomStopsAnimation = flag;
  108978. },
  108979. enumerable: true,
  108980. configurable: true
  108981. });
  108982. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  108983. /**
  108984. * Gets the transition time when framing the mesh, in milliseconds
  108985. */
  108986. get: function () {
  108987. return this._framingTime;
  108988. },
  108989. /**
  108990. * Sets the transition time when framing the mesh, in milliseconds
  108991. */
  108992. set: function (time) {
  108993. this._framingTime = time;
  108994. },
  108995. enumerable: true,
  108996. configurable: true
  108997. });
  108998. /**
  108999. * Initializes the behavior.
  109000. */
  109001. FramingBehavior.prototype.init = function () {
  109002. // Do notihng
  109003. };
  109004. /**
  109005. * Attaches the behavior to its arc rotate camera.
  109006. * @param camera Defines the camera to attach the behavior to
  109007. */
  109008. FramingBehavior.prototype.attach = function (camera) {
  109009. var _this = this;
  109010. this._attachedCamera = camera;
  109011. var scene = this._attachedCamera.getScene();
  109012. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  109013. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  109014. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  109015. _this._isPointerDown = true;
  109016. return;
  109017. }
  109018. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  109019. _this._isPointerDown = false;
  109020. }
  109021. });
  109022. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  109023. if (mesh) {
  109024. _this.zoomOnMesh(mesh);
  109025. }
  109026. });
  109027. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  109028. // Stop the animation if there is user interaction and the animation should stop for this interaction
  109029. _this._applyUserInteraction();
  109030. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  109031. // back to the default position after a given timeout
  109032. _this._maintainCameraAboveGround();
  109033. });
  109034. };
  109035. /**
  109036. * Detaches the behavior from its current arc rotate camera.
  109037. */
  109038. FramingBehavior.prototype.detach = function () {
  109039. if (!this._attachedCamera) {
  109040. return;
  109041. }
  109042. var scene = this._attachedCamera.getScene();
  109043. if (this._onPrePointerObservableObserver) {
  109044. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  109045. }
  109046. if (this._onAfterCheckInputsObserver) {
  109047. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  109048. }
  109049. if (this._onMeshTargetChangedObserver) {
  109050. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  109051. }
  109052. this._attachedCamera = null;
  109053. };
  109054. /**
  109055. * Targets the given mesh and updates zoom level accordingly.
  109056. * @param mesh The mesh to target.
  109057. * @param radius Optional. If a cached radius position already exists, overrides default.
  109058. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  109059. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  109060. * @param onAnimationEnd Callback triggered at the end of the framing animation
  109061. */
  109062. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  109063. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  109064. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  109065. mesh.computeWorldMatrix(true);
  109066. var boundingBox = mesh.getBoundingInfo().boundingBox;
  109067. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  109068. };
  109069. /**
  109070. * Targets the given mesh with its children and updates zoom level accordingly.
  109071. * @param mesh The mesh to target.
  109072. * @param radius Optional. If a cached radius position already exists, overrides default.
  109073. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  109074. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  109075. * @param onAnimationEnd Callback triggered at the end of the framing animation
  109076. */
  109077. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  109078. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  109079. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  109080. mesh.computeWorldMatrix(true);
  109081. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  109082. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  109083. };
  109084. /**
  109085. * Targets the given meshes with their children and updates zoom level accordingly.
  109086. * @param meshes The mesh to target.
  109087. * @param radius Optional. If a cached radius position already exists, overrides default.
  109088. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  109089. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  109090. * @param onAnimationEnd Callback triggered at the end of the framing animation
  109091. */
  109092. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  109093. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  109094. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  109095. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  109096. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  109097. for (var i = 0; i < meshes.length; i++) {
  109098. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  109099. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  109100. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  109101. }
  109102. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  109103. };
  109104. /**
  109105. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  109106. * @param minimumWorld Determines the smaller position of the bounding box extend
  109107. * @param maximumWorld Determines the bigger position of the bounding box extend
  109108. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  109109. * @param onAnimationEnd Callback triggered at the end of the framing animation
  109110. */
  109111. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  109112. var _this = this;
  109113. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  109114. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  109115. var zoomTarget;
  109116. if (!this._attachedCamera) {
  109117. return;
  109118. }
  109119. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  109120. var bottom = minimumWorld.y;
  109121. var top = maximumWorld.y;
  109122. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  109123. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  109124. if (focusOnOriginXZ) {
  109125. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  109126. }
  109127. else {
  109128. var centerWorld = minimumWorld.add(radiusWorld);
  109129. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  109130. }
  109131. if (!this._vectorTransition) {
  109132. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  109133. }
  109134. this._betaIsAnimating = true;
  109135. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  109136. if (animatable) {
  109137. this._animatables.push(animatable);
  109138. }
  109139. // sets the radius and lower radius bounds
  109140. // Small delta ensures camera is not always at lower zoom limit.
  109141. var radius = 0;
  109142. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  109143. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  109144. if (this.autoCorrectCameraLimitsAndSensibility) {
  109145. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  109146. }
  109147. radius = position;
  109148. }
  109149. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  109150. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  109151. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  109152. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  109153. }
  109154. }
  109155. // Set sensibilities
  109156. if (this.autoCorrectCameraLimitsAndSensibility) {
  109157. var extend = maximumWorld.subtract(minimumWorld).length();
  109158. this._attachedCamera.panningSensibility = 5000 / extend;
  109159. this._attachedCamera.wheelPrecision = 100 / radius;
  109160. }
  109161. // transition to new radius
  109162. if (!this._radiusTransition) {
  109163. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  109164. }
  109165. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  109166. _this.stopAllAnimations();
  109167. if (onAnimationEnd) {
  109168. onAnimationEnd();
  109169. }
  109170. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  109171. _this._attachedCamera.storeState();
  109172. }
  109173. });
  109174. if (animatable) {
  109175. this._animatables.push(animatable);
  109176. }
  109177. };
  109178. /**
  109179. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  109180. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  109181. * frustum width.
  109182. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  109183. * to fully enclose the mesh in the viewing frustum.
  109184. */
  109185. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  109186. var size = maximumWorld.subtract(minimumWorld);
  109187. var boxVectorGlobalDiagonal = size.length();
  109188. var frustumSlope = this._getFrustumSlope();
  109189. // Formula for setting distance
  109190. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  109191. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  109192. // Horizon distance
  109193. var radius = radiusWithoutFraming * this._radiusScale;
  109194. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  109195. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  109196. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  109197. var camera = this._attachedCamera;
  109198. if (!camera) {
  109199. return 0;
  109200. }
  109201. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  109202. // Don't exceed the requested limit
  109203. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  109204. }
  109205. // Don't exceed the upper radius limit
  109206. if (camera.upperRadiusLimit) {
  109207. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  109208. }
  109209. return distance;
  109210. };
  109211. /**
  109212. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  109213. * is automatically returned to its default position (expected to be above ground plane).
  109214. */
  109215. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  109216. var _this = this;
  109217. if (this._elevationReturnTime < 0) {
  109218. return;
  109219. }
  109220. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  109221. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  109222. var limitBeta = Math.PI * 0.5;
  109223. // Bring the camera back up if below the ground plane
  109224. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  109225. this._betaIsAnimating = true;
  109226. //Transition to new position
  109227. this.stopAllAnimations();
  109228. if (!this._betaTransition) {
  109229. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  109230. }
  109231. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  109232. _this._clearAnimationLocks();
  109233. _this.stopAllAnimations();
  109234. });
  109235. if (animatabe) {
  109236. this._animatables.push(animatabe);
  109237. }
  109238. }
  109239. };
  109240. /**
  109241. * Returns the frustum slope based on the canvas ratio and camera FOV
  109242. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  109243. */
  109244. FramingBehavior.prototype._getFrustumSlope = function () {
  109245. // Calculate the viewport ratio
  109246. // Aspect Ratio is Height/Width.
  109247. var camera = this._attachedCamera;
  109248. if (!camera) {
  109249. return BABYLON.Vector2.Zero();
  109250. }
  109251. var engine = camera.getScene().getEngine();
  109252. var aspectRatio = engine.getAspectRatio(camera);
  109253. // Camera FOV is the vertical field of view (top-bottom) in radians.
  109254. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  109255. var frustumSlopeY = Math.tan(camera.fov / 2);
  109256. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  109257. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  109258. // along the forward vector.
  109259. var frustumSlopeX = frustumSlopeY * aspectRatio;
  109260. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  109261. };
  109262. /**
  109263. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  109264. */
  109265. FramingBehavior.prototype._clearAnimationLocks = function () {
  109266. this._betaIsAnimating = false;
  109267. };
  109268. /**
  109269. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  109270. */
  109271. FramingBehavior.prototype._applyUserInteraction = function () {
  109272. if (this.isUserIsMoving) {
  109273. this._lastInteractionTime = BABYLON.Tools.Now;
  109274. this.stopAllAnimations();
  109275. this._clearAnimationLocks();
  109276. }
  109277. };
  109278. /**
  109279. * Stops and removes all animations that have been applied to the camera
  109280. */
  109281. FramingBehavior.prototype.stopAllAnimations = function () {
  109282. if (this._attachedCamera) {
  109283. this._attachedCamera.animations = [];
  109284. }
  109285. while (this._animatables.length) {
  109286. if (this._animatables[0]) {
  109287. this._animatables[0].onAnimationEnd = null;
  109288. this._animatables[0].stop();
  109289. }
  109290. this._animatables.shift();
  109291. }
  109292. };
  109293. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  109294. /**
  109295. * Gets a value indicating if the user is moving the camera
  109296. */
  109297. get: function () {
  109298. if (!this._attachedCamera) {
  109299. return false;
  109300. }
  109301. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  109302. this._attachedCamera.inertialBetaOffset !== 0 ||
  109303. this._attachedCamera.inertialRadiusOffset !== 0 ||
  109304. this._attachedCamera.inertialPanningX !== 0 ||
  109305. this._attachedCamera.inertialPanningY !== 0 ||
  109306. this._isPointerDown;
  109307. },
  109308. enumerable: true,
  109309. configurable: true
  109310. });
  109311. /**
  109312. * The easing function used by animations
  109313. */
  109314. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  109315. /**
  109316. * The easing mode used by animations
  109317. */
  109318. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  109319. // Statics
  109320. /**
  109321. * The camera can move all the way towards the mesh.
  109322. */
  109323. FramingBehavior.IgnoreBoundsSizeMode = 0;
  109324. /**
  109325. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  109326. */
  109327. FramingBehavior.FitFrustumSidesMode = 1;
  109328. return FramingBehavior;
  109329. }());
  109330. BABYLON.FramingBehavior = FramingBehavior;
  109331. })(BABYLON || (BABYLON = {}));
  109332. //# sourceMappingURL=babylon.framingBehavior.js.map
  109333. var BABYLON;
  109334. (function (BABYLON) {
  109335. /**
  109336. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  109337. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  109338. */
  109339. var BouncingBehavior = /** @class */ (function () {
  109340. function BouncingBehavior() {
  109341. /**
  109342. * The duration of the animation, in milliseconds
  109343. */
  109344. this.transitionDuration = 450;
  109345. /**
  109346. * Length of the distance animated by the transition when lower radius is reached
  109347. */
  109348. this.lowerRadiusTransitionRange = 2;
  109349. /**
  109350. * Length of the distance animated by the transition when upper radius is reached
  109351. */
  109352. this.upperRadiusTransitionRange = -2;
  109353. this._autoTransitionRange = false;
  109354. // Animations
  109355. this._radiusIsAnimating = false;
  109356. this._radiusBounceTransition = null;
  109357. this._animatables = new Array();
  109358. }
  109359. Object.defineProperty(BouncingBehavior.prototype, "name", {
  109360. /**
  109361. * Gets the name of the behavior.
  109362. */
  109363. get: function () {
  109364. return "Bouncing";
  109365. },
  109366. enumerable: true,
  109367. configurable: true
  109368. });
  109369. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  109370. /**
  109371. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  109372. */
  109373. get: function () {
  109374. return this._autoTransitionRange;
  109375. },
  109376. /**
  109377. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  109378. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  109379. */
  109380. set: function (value) {
  109381. var _this = this;
  109382. if (this._autoTransitionRange === value) {
  109383. return;
  109384. }
  109385. this._autoTransitionRange = value;
  109386. var camera = this._attachedCamera;
  109387. if (!camera) {
  109388. return;
  109389. }
  109390. if (value) {
  109391. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  109392. if (!mesh) {
  109393. return;
  109394. }
  109395. mesh.computeWorldMatrix(true);
  109396. var diagonal = mesh.getBoundingInfo().diagonalLength;
  109397. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  109398. _this.upperRadiusTransitionRange = diagonal * 0.05;
  109399. });
  109400. }
  109401. else if (this._onMeshTargetChangedObserver) {
  109402. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  109403. }
  109404. },
  109405. enumerable: true,
  109406. configurable: true
  109407. });
  109408. /**
  109409. * Initializes the behavior.
  109410. */
  109411. BouncingBehavior.prototype.init = function () {
  109412. // Do notihng
  109413. };
  109414. /**
  109415. * Attaches the behavior to its arc rotate camera.
  109416. * @param camera Defines the camera to attach the behavior to
  109417. */
  109418. BouncingBehavior.prototype.attach = function (camera) {
  109419. var _this = this;
  109420. this._attachedCamera = camera;
  109421. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  109422. if (!_this._attachedCamera) {
  109423. return;
  109424. }
  109425. // Add the bounce animation to the lower radius limit
  109426. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  109427. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  109428. }
  109429. // Add the bounce animation to the upper radius limit
  109430. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  109431. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  109432. }
  109433. });
  109434. };
  109435. /**
  109436. * Detaches the behavior from its current arc rotate camera.
  109437. */
  109438. BouncingBehavior.prototype.detach = function () {
  109439. if (!this._attachedCamera) {
  109440. return;
  109441. }
  109442. if (this._onAfterCheckInputsObserver) {
  109443. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  109444. }
  109445. if (this._onMeshTargetChangedObserver) {
  109446. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  109447. }
  109448. this._attachedCamera = null;
  109449. };
  109450. /**
  109451. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  109452. * @param radiusLimit The limit to check against.
  109453. * @return Bool to indicate if at limit.
  109454. */
  109455. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  109456. if (!this._attachedCamera) {
  109457. return false;
  109458. }
  109459. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  109460. return true;
  109461. }
  109462. return false;
  109463. };
  109464. /**
  109465. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  109466. * @param radiusDelta The delta by which to animate to. Can be negative.
  109467. */
  109468. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  109469. var _this = this;
  109470. if (!this._attachedCamera) {
  109471. return;
  109472. }
  109473. if (!this._radiusBounceTransition) {
  109474. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  109475. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  109476. }
  109477. // Prevent zoom until bounce has completed
  109478. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  109479. this._attachedCamera.wheelPrecision = Infinity;
  109480. this._attachedCamera.inertialRadiusOffset = 0;
  109481. // Animate to the radius limit
  109482. this.stopAllAnimations();
  109483. this._radiusIsAnimating = true;
  109484. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  109485. if (animatable) {
  109486. this._animatables.push(animatable);
  109487. }
  109488. };
  109489. /**
  109490. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  109491. */
  109492. BouncingBehavior.prototype._clearAnimationLocks = function () {
  109493. this._radiusIsAnimating = false;
  109494. if (this._attachedCamera) {
  109495. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  109496. }
  109497. };
  109498. /**
  109499. * Stops and removes all animations that have been applied to the camera
  109500. */
  109501. BouncingBehavior.prototype.stopAllAnimations = function () {
  109502. if (this._attachedCamera) {
  109503. this._attachedCamera.animations = [];
  109504. }
  109505. while (this._animatables.length) {
  109506. this._animatables[0].onAnimationEnd = null;
  109507. this._animatables[0].stop();
  109508. this._animatables.shift();
  109509. }
  109510. };
  109511. /**
  109512. * The easing function used by animations
  109513. */
  109514. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  109515. /**
  109516. * The easing mode used by animations
  109517. */
  109518. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  109519. return BouncingBehavior;
  109520. }());
  109521. BABYLON.BouncingBehavior = BouncingBehavior;
  109522. })(BABYLON || (BABYLON = {}));
  109523. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  109524. var BABYLON;
  109525. (function (BABYLON) {
  109526. /**
  109527. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  109528. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  109529. */
  109530. var AutoRotationBehavior = /** @class */ (function () {
  109531. function AutoRotationBehavior() {
  109532. this._zoomStopsAnimation = false;
  109533. this._idleRotationSpeed = 0.05;
  109534. this._idleRotationWaitTime = 2000;
  109535. this._idleRotationSpinupTime = 2000;
  109536. this._isPointerDown = false;
  109537. this._lastFrameTime = null;
  109538. this._lastInteractionTime = -Infinity;
  109539. this._cameraRotationSpeed = 0;
  109540. this._lastFrameRadius = 0;
  109541. }
  109542. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  109543. /**
  109544. * Gets the name of the behavior.
  109545. */
  109546. get: function () {
  109547. return "AutoRotation";
  109548. },
  109549. enumerable: true,
  109550. configurable: true
  109551. });
  109552. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  109553. /**
  109554. * Gets the flag that indicates if user zooming should stop animation.
  109555. */
  109556. get: function () {
  109557. return this._zoomStopsAnimation;
  109558. },
  109559. /**
  109560. * Sets the flag that indicates if user zooming should stop animation.
  109561. */
  109562. set: function (flag) {
  109563. this._zoomStopsAnimation = flag;
  109564. },
  109565. enumerable: true,
  109566. configurable: true
  109567. });
  109568. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  109569. /**
  109570. * Gets the default speed at which the camera rotates around the model.
  109571. */
  109572. get: function () {
  109573. return this._idleRotationSpeed;
  109574. },
  109575. /**
  109576. * Sets the default speed at which the camera rotates around the model.
  109577. */
  109578. set: function (speed) {
  109579. this._idleRotationSpeed = speed;
  109580. },
  109581. enumerable: true,
  109582. configurable: true
  109583. });
  109584. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  109585. /**
  109586. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  109587. */
  109588. get: function () {
  109589. return this._idleRotationWaitTime;
  109590. },
  109591. /**
  109592. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  109593. */
  109594. set: function (time) {
  109595. this._idleRotationWaitTime = time;
  109596. },
  109597. enumerable: true,
  109598. configurable: true
  109599. });
  109600. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  109601. /**
  109602. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  109603. */
  109604. get: function () {
  109605. return this._idleRotationSpinupTime;
  109606. },
  109607. /**
  109608. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  109609. */
  109610. set: function (time) {
  109611. this._idleRotationSpinupTime = time;
  109612. },
  109613. enumerable: true,
  109614. configurable: true
  109615. });
  109616. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  109617. /**
  109618. * Gets a value indicating if the camera is currently rotating because of this behavior
  109619. */
  109620. get: function () {
  109621. return Math.abs(this._cameraRotationSpeed) > 0;
  109622. },
  109623. enumerable: true,
  109624. configurable: true
  109625. });
  109626. /**
  109627. * Initializes the behavior.
  109628. */
  109629. AutoRotationBehavior.prototype.init = function () {
  109630. // Do notihng
  109631. };
  109632. /**
  109633. * Attaches the behavior to its arc rotate camera.
  109634. * @param camera Defines the camera to attach the behavior to
  109635. */
  109636. AutoRotationBehavior.prototype.attach = function (camera) {
  109637. var _this = this;
  109638. this._attachedCamera = camera;
  109639. var scene = this._attachedCamera.getScene();
  109640. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  109641. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  109642. _this._isPointerDown = true;
  109643. return;
  109644. }
  109645. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  109646. _this._isPointerDown = false;
  109647. }
  109648. });
  109649. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  109650. var now = BABYLON.Tools.Now;
  109651. var dt = 0;
  109652. if (_this._lastFrameTime != null) {
  109653. dt = now - _this._lastFrameTime;
  109654. }
  109655. _this._lastFrameTime = now;
  109656. // Stop the animation if there is user interaction and the animation should stop for this interaction
  109657. _this._applyUserInteraction();
  109658. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  109659. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  109660. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  109661. // Step camera rotation by rotation speed
  109662. if (_this._attachedCamera) {
  109663. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  109664. }
  109665. });
  109666. };
  109667. /**
  109668. * Detaches the behavior from its current arc rotate camera.
  109669. */
  109670. AutoRotationBehavior.prototype.detach = function () {
  109671. if (!this._attachedCamera) {
  109672. return;
  109673. }
  109674. var scene = this._attachedCamera.getScene();
  109675. if (this._onPrePointerObservableObserver) {
  109676. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  109677. }
  109678. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  109679. this._attachedCamera = null;
  109680. };
  109681. /**
  109682. * Returns true if user is scrolling.
  109683. * @return true if user is scrolling.
  109684. */
  109685. AutoRotationBehavior.prototype._userIsZooming = function () {
  109686. if (!this._attachedCamera) {
  109687. return false;
  109688. }
  109689. return this._attachedCamera.inertialRadiusOffset !== 0;
  109690. };
  109691. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  109692. if (!this._attachedCamera) {
  109693. return false;
  109694. }
  109695. var zoomHasHitLimit = false;
  109696. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  109697. zoomHasHitLimit = true;
  109698. }
  109699. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  109700. this._lastFrameRadius = this._attachedCamera.radius;
  109701. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  109702. };
  109703. /**
  109704. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  109705. */
  109706. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  109707. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  109708. this._lastInteractionTime = BABYLON.Tools.Now;
  109709. }
  109710. };
  109711. // Tools
  109712. AutoRotationBehavior.prototype._userIsMoving = function () {
  109713. if (!this._attachedCamera) {
  109714. return false;
  109715. }
  109716. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  109717. this._attachedCamera.inertialBetaOffset !== 0 ||
  109718. this._attachedCamera.inertialRadiusOffset !== 0 ||
  109719. this._attachedCamera.inertialPanningX !== 0 ||
  109720. this._attachedCamera.inertialPanningY !== 0 ||
  109721. this._isPointerDown;
  109722. };
  109723. return AutoRotationBehavior;
  109724. }());
  109725. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  109726. })(BABYLON || (BABYLON = {}));
  109727. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  109728. var BABYLON;
  109729. (function (BABYLON) {
  109730. var NullEngineOptions = /** @class */ (function () {
  109731. function NullEngineOptions() {
  109732. this.renderWidth = 512;
  109733. this.renderHeight = 256;
  109734. this.textureSize = 512;
  109735. this.deterministicLockstep = false;
  109736. this.lockstepMaxSteps = 4;
  109737. }
  109738. return NullEngineOptions;
  109739. }());
  109740. BABYLON.NullEngineOptions = NullEngineOptions;
  109741. /**
  109742. * The null engine class provides support for headless version of babylon.js.
  109743. * This can be used in server side scenario or for testing purposes
  109744. */
  109745. var NullEngine = /** @class */ (function (_super) {
  109746. __extends(NullEngine, _super);
  109747. function NullEngine(options) {
  109748. if (options === void 0) { options = new NullEngineOptions(); }
  109749. var _this = _super.call(this, null) || this;
  109750. if (options.deterministicLockstep === undefined) {
  109751. options.deterministicLockstep = false;
  109752. }
  109753. if (options.lockstepMaxSteps === undefined) {
  109754. options.lockstepMaxSteps = 4;
  109755. }
  109756. _this._options = options;
  109757. // Init caps
  109758. // We consider we are on a webgl1 capable device
  109759. _this._caps = new BABYLON.EngineCapabilities();
  109760. _this._caps.maxTexturesImageUnits = 16;
  109761. _this._caps.maxVertexTextureImageUnits = 16;
  109762. _this._caps.maxTextureSize = 512;
  109763. _this._caps.maxCubemapTextureSize = 512;
  109764. _this._caps.maxRenderTextureSize = 512;
  109765. _this._caps.maxVertexAttribs = 16;
  109766. _this._caps.maxVaryingVectors = 16;
  109767. _this._caps.maxFragmentUniformVectors = 16;
  109768. _this._caps.maxVertexUniformVectors = 16;
  109769. // Extensions
  109770. _this._caps.standardDerivatives = false;
  109771. _this._caps.astc = null;
  109772. _this._caps.s3tc = null;
  109773. _this._caps.pvrtc = null;
  109774. _this._caps.etc1 = null;
  109775. _this._caps.etc2 = null;
  109776. _this._caps.textureAnisotropicFilterExtension = null;
  109777. _this._caps.maxAnisotropy = 0;
  109778. _this._caps.uintIndices = false;
  109779. _this._caps.fragmentDepthSupported = false;
  109780. _this._caps.highPrecisionShaderSupported = true;
  109781. _this._caps.colorBufferFloat = false;
  109782. _this._caps.textureFloat = false;
  109783. _this._caps.textureFloatLinearFiltering = false;
  109784. _this._caps.textureFloatRender = false;
  109785. _this._caps.textureHalfFloat = false;
  109786. _this._caps.textureHalfFloatLinearFiltering = false;
  109787. _this._caps.textureHalfFloatRender = false;
  109788. _this._caps.textureLOD = false;
  109789. _this._caps.drawBuffersExtension = false;
  109790. _this._caps.depthTextureExtension = false;
  109791. _this._caps.vertexArrayObject = false;
  109792. _this._caps.instancedArrays = false;
  109793. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  109794. // Wrappers
  109795. if (typeof URL === "undefined") {
  109796. URL = {
  109797. createObjectURL: function () { },
  109798. revokeObjectURL: function () { }
  109799. };
  109800. }
  109801. if (typeof Blob === "undefined") {
  109802. Blob = function () { };
  109803. }
  109804. return _this;
  109805. }
  109806. NullEngine.prototype.isDeterministicLockStep = function () {
  109807. return this._options.deterministicLockstep;
  109808. };
  109809. NullEngine.prototype.getLockstepMaxSteps = function () {
  109810. return this._options.lockstepMaxSteps;
  109811. };
  109812. NullEngine.prototype.getHardwareScalingLevel = function () {
  109813. return 1.0;
  109814. };
  109815. NullEngine.prototype.createVertexBuffer = function (vertices) {
  109816. return {
  109817. capacity: 0,
  109818. references: 1,
  109819. is32Bits: false
  109820. };
  109821. };
  109822. NullEngine.prototype.createIndexBuffer = function (indices) {
  109823. return {
  109824. capacity: 0,
  109825. references: 1,
  109826. is32Bits: false
  109827. };
  109828. };
  109829. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  109830. if (stencil === void 0) { stencil = false; }
  109831. };
  109832. NullEngine.prototype.getRenderWidth = function (useScreen) {
  109833. if (useScreen === void 0) { useScreen = false; }
  109834. if (!useScreen && this._currentRenderTarget) {
  109835. return this._currentRenderTarget.width;
  109836. }
  109837. return this._options.renderWidth;
  109838. };
  109839. NullEngine.prototype.getRenderHeight = function (useScreen) {
  109840. if (useScreen === void 0) { useScreen = false; }
  109841. if (!useScreen && this._currentRenderTarget) {
  109842. return this._currentRenderTarget.height;
  109843. }
  109844. return this._options.renderHeight;
  109845. };
  109846. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  109847. this._cachedViewport = viewport;
  109848. };
  109849. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  109850. return {
  109851. transformFeedback: null,
  109852. __SPECTOR_rebuildProgram: null
  109853. };
  109854. };
  109855. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  109856. return [];
  109857. };
  109858. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  109859. return [];
  109860. };
  109861. NullEngine.prototype.bindSamplers = function (effect) {
  109862. this._currentEffect = null;
  109863. };
  109864. NullEngine.prototype.enableEffect = function (effect) {
  109865. this._currentEffect = effect;
  109866. if (effect.onBind) {
  109867. effect.onBind(effect);
  109868. }
  109869. if (effect._onBindObservable) {
  109870. effect._onBindObservable.notifyObservers(effect);
  109871. }
  109872. };
  109873. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  109874. if (zOffset === void 0) { zOffset = 0; }
  109875. if (reverseSide === void 0) { reverseSide = false; }
  109876. };
  109877. NullEngine.prototype.setIntArray = function (uniform, array) {
  109878. };
  109879. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  109880. };
  109881. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  109882. };
  109883. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  109884. };
  109885. NullEngine.prototype.setFloatArray = function (uniform, array) {
  109886. };
  109887. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  109888. };
  109889. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  109890. };
  109891. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  109892. };
  109893. NullEngine.prototype.setArray = function (uniform, array) {
  109894. };
  109895. NullEngine.prototype.setArray2 = function (uniform, array) {
  109896. };
  109897. NullEngine.prototype.setArray3 = function (uniform, array) {
  109898. };
  109899. NullEngine.prototype.setArray4 = function (uniform, array) {
  109900. };
  109901. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  109902. };
  109903. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  109904. };
  109905. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  109906. };
  109907. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  109908. };
  109909. NullEngine.prototype.setFloat = function (uniform, value) {
  109910. };
  109911. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  109912. };
  109913. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  109914. };
  109915. NullEngine.prototype.setBool = function (uniform, bool) {
  109916. };
  109917. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  109918. };
  109919. NullEngine.prototype.setColor3 = function (uniform, color3) {
  109920. };
  109921. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  109922. };
  109923. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  109924. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  109925. if (this._alphaMode === mode) {
  109926. return;
  109927. }
  109928. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  109929. if (!noDepthWriteChange) {
  109930. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  109931. }
  109932. this._alphaMode = mode;
  109933. };
  109934. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  109935. };
  109936. NullEngine.prototype.wipeCaches = function (bruteForce) {
  109937. if (this.preventCacheWipeBetweenFrames) {
  109938. return;
  109939. }
  109940. this.resetTextureCache();
  109941. this._currentEffect = null;
  109942. if (bruteForce) {
  109943. this._currentProgram = null;
  109944. this._stencilState.reset();
  109945. this._depthCullingState.reset();
  109946. this._alphaState.reset();
  109947. }
  109948. this._cachedVertexBuffers = null;
  109949. this._cachedIndexBuffer = null;
  109950. this._cachedEffectForVertexBuffers = null;
  109951. };
  109952. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  109953. };
  109954. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  109955. };
  109956. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  109957. };
  109958. /** @hidden */
  109959. NullEngine.prototype._createTexture = function () {
  109960. return {};
  109961. };
  109962. /** @hidden */
  109963. NullEngine.prototype._releaseTexture = function (texture) {
  109964. };
  109965. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  109966. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  109967. if (onLoad === void 0) { onLoad = null; }
  109968. if (onError === void 0) { onError = null; }
  109969. if (buffer === void 0) { buffer = null; }
  109970. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  109971. var url = String(urlArg);
  109972. texture.url = url;
  109973. texture.generateMipMaps = !noMipmap;
  109974. texture.samplingMode = samplingMode;
  109975. texture.invertY = invertY;
  109976. texture.baseWidth = this._options.textureSize;
  109977. texture.baseHeight = this._options.textureSize;
  109978. texture.width = this._options.textureSize;
  109979. texture.height = this._options.textureSize;
  109980. if (format) {
  109981. texture.format = format;
  109982. }
  109983. texture.isReady = true;
  109984. if (onLoad) {
  109985. onLoad();
  109986. }
  109987. this._internalTexturesCache.push(texture);
  109988. return texture;
  109989. };
  109990. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  109991. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  109992. if (options !== undefined && typeof options === "object") {
  109993. fullOptions.generateMipMaps = options.generateMipMaps;
  109994. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  109995. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  109996. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  109997. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  109998. }
  109999. else {
  110000. fullOptions.generateMipMaps = options;
  110001. fullOptions.generateDepthBuffer = true;
  110002. fullOptions.generateStencilBuffer = false;
  110003. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  110004. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  110005. }
  110006. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  110007. var width = size.width || size;
  110008. var height = size.height || size;
  110009. texture._depthStencilBuffer = {};
  110010. texture._framebuffer = {};
  110011. texture.baseWidth = width;
  110012. texture.baseHeight = height;
  110013. texture.width = width;
  110014. texture.height = height;
  110015. texture.isReady = true;
  110016. texture.samples = 1;
  110017. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  110018. texture.samplingMode = fullOptions.samplingMode;
  110019. texture.type = fullOptions.type;
  110020. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  110021. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  110022. this._internalTexturesCache.push(texture);
  110023. return texture;
  110024. };
  110025. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  110026. texture.samplingMode = samplingMode;
  110027. };
  110028. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  110029. if (this._currentRenderTarget) {
  110030. this.unBindFramebuffer(this._currentRenderTarget);
  110031. }
  110032. this._currentRenderTarget = texture;
  110033. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  110034. if (this._cachedViewport && !forceFullscreenViewport) {
  110035. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  110036. }
  110037. };
  110038. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  110039. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  110040. this._currentRenderTarget = null;
  110041. if (onBeforeUnbind) {
  110042. if (texture._MSAAFramebuffer) {
  110043. this._currentFramebuffer = texture._framebuffer;
  110044. }
  110045. onBeforeUnbind();
  110046. }
  110047. this._currentFramebuffer = null;
  110048. };
  110049. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  110050. var vbo = {
  110051. capacity: 1,
  110052. references: 1,
  110053. is32Bits: false
  110054. };
  110055. return vbo;
  110056. };
  110057. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  110058. if (premulAlpha === void 0) { premulAlpha = false; }
  110059. };
  110060. /**
  110061. * @hidden
  110062. * Get the current error code of the webGL context
  110063. * @returns the error code
  110064. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  110065. */
  110066. NullEngine.prototype.getError = function () {
  110067. return 0;
  110068. };
  110069. /** @hidden */
  110070. NullEngine.prototype._getUnpackAlignement = function () {
  110071. return 1;
  110072. };
  110073. /** @hidden */
  110074. NullEngine.prototype._unpackFlipY = function (value) {
  110075. };
  110076. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  110077. if (offset === void 0) { offset = 0; }
  110078. };
  110079. /**
  110080. * Updates a dynamic vertex buffer.
  110081. * @param vertexBuffer the vertex buffer to update
  110082. * @param data the data used to update the vertex buffer
  110083. * @param byteOffset the byte offset of the data (optional)
  110084. * @param byteLength the byte length of the data (optional)
  110085. */
  110086. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  110087. };
  110088. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  110089. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  110090. this._boundTexturesCache[this._activeChannel] = texture;
  110091. return true;
  110092. }
  110093. return false;
  110094. };
  110095. /** @hidden */
  110096. NullEngine.prototype._bindTexture = function (channel, texture) {
  110097. if (channel < 0) {
  110098. return;
  110099. }
  110100. this._bindTextureDirectly(0, texture);
  110101. };
  110102. /** @hidden */
  110103. NullEngine.prototype._releaseBuffer = function (buffer) {
  110104. buffer.references--;
  110105. if (buffer.references === 0) {
  110106. return true;
  110107. }
  110108. return false;
  110109. };
  110110. NullEngine.prototype.releaseEffects = function () {
  110111. };
  110112. NullEngine.prototype.displayLoadingUI = function () {
  110113. };
  110114. NullEngine.prototype.hideLoadingUI = function () {
  110115. };
  110116. /** @hidden */
  110117. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  110118. if (faceIndex === void 0) { faceIndex = 0; }
  110119. if (lod === void 0) { lod = 0; }
  110120. };
  110121. /** @hidden */
  110122. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  110123. if (faceIndex === void 0) { faceIndex = 0; }
  110124. if (lod === void 0) { lod = 0; }
  110125. };
  110126. /** @hidden */
  110127. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  110128. if (faceIndex === void 0) { faceIndex = 0; }
  110129. if (lod === void 0) { lod = 0; }
  110130. };
  110131. /** @hidden */
  110132. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  110133. if (faceIndex === void 0) { faceIndex = 0; }
  110134. if (lod === void 0) { lod = 0; }
  110135. };
  110136. return NullEngine;
  110137. }(BABYLON.Engine));
  110138. BABYLON.NullEngine = NullEngine;
  110139. })(BABYLON || (BABYLON = {}));
  110140. //# sourceMappingURL=babylon.nullEngine.js.map
  110141. var BABYLON;
  110142. (function (BABYLON) {
  110143. /**
  110144. * This class can be used to get instrumentation data from a Babylon engine
  110145. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  110146. */
  110147. var EngineInstrumentation = /** @class */ (function () {
  110148. /**
  110149. * Instantiates a new engine instrumentation.
  110150. * This class can be used to get instrumentation data from a Babylon engine
  110151. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  110152. * @param engine Defines the engine to instrument
  110153. */
  110154. function EngineInstrumentation(
  110155. /**
  110156. * Define the instrumented engine.
  110157. */
  110158. engine) {
  110159. this.engine = engine;
  110160. this._captureGPUFrameTime = false;
  110161. this._gpuFrameTime = new BABYLON.PerfCounter();
  110162. this._captureShaderCompilationTime = false;
  110163. this._shaderCompilationTime = new BABYLON.PerfCounter();
  110164. // Observers
  110165. this._onBeginFrameObserver = null;
  110166. this._onEndFrameObserver = null;
  110167. this._onBeforeShaderCompilationObserver = null;
  110168. this._onAfterShaderCompilationObserver = null;
  110169. }
  110170. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  110171. // Properties
  110172. /**
  110173. * Gets the perf counter used for GPU frame time
  110174. */
  110175. get: function () {
  110176. return this._gpuFrameTime;
  110177. },
  110178. enumerable: true,
  110179. configurable: true
  110180. });
  110181. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  110182. /**
  110183. * Gets the GPU frame time capture status
  110184. */
  110185. get: function () {
  110186. return this._captureGPUFrameTime;
  110187. },
  110188. /**
  110189. * Enable or disable the GPU frame time capture
  110190. */
  110191. set: function (value) {
  110192. var _this = this;
  110193. if (value === this._captureGPUFrameTime) {
  110194. return;
  110195. }
  110196. this._captureGPUFrameTime = value;
  110197. if (value) {
  110198. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  110199. if (!_this._gpuFrameTimeToken) {
  110200. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  110201. }
  110202. });
  110203. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  110204. if (!_this._gpuFrameTimeToken) {
  110205. return;
  110206. }
  110207. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  110208. if (time > -1) {
  110209. _this._gpuFrameTimeToken = null;
  110210. _this._gpuFrameTime.fetchNewFrame();
  110211. _this._gpuFrameTime.addCount(time, true);
  110212. }
  110213. });
  110214. }
  110215. else {
  110216. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  110217. this._onBeginFrameObserver = null;
  110218. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  110219. this._onEndFrameObserver = null;
  110220. }
  110221. },
  110222. enumerable: true,
  110223. configurable: true
  110224. });
  110225. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  110226. /**
  110227. * Gets the perf counter used for shader compilation time
  110228. */
  110229. get: function () {
  110230. return this._shaderCompilationTime;
  110231. },
  110232. enumerable: true,
  110233. configurable: true
  110234. });
  110235. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  110236. /**
  110237. * Gets the shader compilation time capture status
  110238. */
  110239. get: function () {
  110240. return this._captureShaderCompilationTime;
  110241. },
  110242. /**
  110243. * Enable or disable the shader compilation time capture
  110244. */
  110245. set: function (value) {
  110246. var _this = this;
  110247. if (value === this._captureShaderCompilationTime) {
  110248. return;
  110249. }
  110250. this._captureShaderCompilationTime = value;
  110251. if (value) {
  110252. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  110253. _this._shaderCompilationTime.fetchNewFrame();
  110254. _this._shaderCompilationTime.beginMonitoring();
  110255. });
  110256. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  110257. _this._shaderCompilationTime.endMonitoring();
  110258. });
  110259. }
  110260. else {
  110261. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  110262. this._onBeforeShaderCompilationObserver = null;
  110263. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  110264. this._onAfterShaderCompilationObserver = null;
  110265. }
  110266. },
  110267. enumerable: true,
  110268. configurable: true
  110269. });
  110270. /**
  110271. * Dispose and release associated resources.
  110272. */
  110273. EngineInstrumentation.prototype.dispose = function () {
  110274. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  110275. this._onBeginFrameObserver = null;
  110276. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  110277. this._onEndFrameObserver = null;
  110278. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  110279. this._onBeforeShaderCompilationObserver = null;
  110280. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  110281. this._onAfterShaderCompilationObserver = null;
  110282. this.engine = null;
  110283. };
  110284. return EngineInstrumentation;
  110285. }());
  110286. BABYLON.EngineInstrumentation = EngineInstrumentation;
  110287. })(BABYLON || (BABYLON = {}));
  110288. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  110289. var BABYLON;
  110290. (function (BABYLON) {
  110291. /**
  110292. * This class can be used to get instrumentation data from a Babylon engine
  110293. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  110294. */
  110295. var SceneInstrumentation = /** @class */ (function () {
  110296. /**
  110297. * Instantiates a new scene instrumentation.
  110298. * This class can be used to get instrumentation data from a Babylon engine
  110299. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  110300. * @param scene Defines the scene to instrument
  110301. */
  110302. function SceneInstrumentation(
  110303. /**
  110304. * Defines the scene to instrument
  110305. */
  110306. scene) {
  110307. var _this = this;
  110308. this.scene = scene;
  110309. this._captureActiveMeshesEvaluationTime = false;
  110310. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  110311. this._captureRenderTargetsRenderTime = false;
  110312. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  110313. this._captureFrameTime = false;
  110314. this._frameTime = new BABYLON.PerfCounter();
  110315. this._captureRenderTime = false;
  110316. this._renderTime = new BABYLON.PerfCounter();
  110317. this._captureInterFrameTime = false;
  110318. this._interFrameTime = new BABYLON.PerfCounter();
  110319. this._captureParticlesRenderTime = false;
  110320. this._particlesRenderTime = new BABYLON.PerfCounter();
  110321. this._captureSpritesRenderTime = false;
  110322. this._spritesRenderTime = new BABYLON.PerfCounter();
  110323. this._capturePhysicsTime = false;
  110324. this._physicsTime = new BABYLON.PerfCounter();
  110325. this._captureAnimationsTime = false;
  110326. this._animationsTime = new BABYLON.PerfCounter();
  110327. this._captureCameraRenderTime = false;
  110328. this._cameraRenderTime = new BABYLON.PerfCounter();
  110329. // Observers
  110330. this._onBeforeActiveMeshesEvaluationObserver = null;
  110331. this._onAfterActiveMeshesEvaluationObserver = null;
  110332. this._onBeforeRenderTargetsRenderObserver = null;
  110333. this._onAfterRenderTargetsRenderObserver = null;
  110334. this._onAfterRenderObserver = null;
  110335. this._onBeforeDrawPhaseObserver = null;
  110336. this._onAfterDrawPhaseObserver = null;
  110337. this._onBeforeAnimationsObserver = null;
  110338. this._onBeforeParticlesRenderingObserver = null;
  110339. this._onAfterParticlesRenderingObserver = null;
  110340. this._onBeforeSpritesRenderingObserver = null;
  110341. this._onAfterSpritesRenderingObserver = null;
  110342. this._onBeforePhysicsObserver = null;
  110343. this._onAfterPhysicsObserver = null;
  110344. this._onAfterAnimationsObserver = null;
  110345. this._onBeforeCameraRenderObserver = null;
  110346. this._onAfterCameraRenderObserver = null;
  110347. // Before render
  110348. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  110349. if (_this._captureActiveMeshesEvaluationTime) {
  110350. _this._activeMeshesEvaluationTime.fetchNewFrame();
  110351. }
  110352. if (_this._captureRenderTargetsRenderTime) {
  110353. _this._renderTargetsRenderTime.fetchNewFrame();
  110354. }
  110355. if (_this._captureFrameTime) {
  110356. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  110357. _this._frameTime.beginMonitoring();
  110358. }
  110359. if (_this._captureInterFrameTime) {
  110360. _this._interFrameTime.endMonitoring();
  110361. }
  110362. if (_this._captureParticlesRenderTime) {
  110363. _this._particlesRenderTime.fetchNewFrame();
  110364. }
  110365. if (_this._captureSpritesRenderTime) {
  110366. _this._spritesRenderTime.fetchNewFrame();
  110367. }
  110368. if (_this._captureAnimationsTime) {
  110369. _this._animationsTime.beginMonitoring();
  110370. }
  110371. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  110372. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  110373. });
  110374. // After render
  110375. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  110376. if (_this._captureFrameTime) {
  110377. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  110378. _this._frameTime.endMonitoring();
  110379. }
  110380. if (_this._captureRenderTime) {
  110381. _this._renderTime.endMonitoring(false);
  110382. }
  110383. if (_this._captureInterFrameTime) {
  110384. _this._interFrameTime.beginMonitoring();
  110385. }
  110386. });
  110387. }
  110388. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  110389. // Properties
  110390. /**
  110391. * Gets the perf counter used for active meshes evaluation time
  110392. */
  110393. get: function () {
  110394. return this._activeMeshesEvaluationTime;
  110395. },
  110396. enumerable: true,
  110397. configurable: true
  110398. });
  110399. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  110400. /**
  110401. * Gets the active meshes evaluation time capture status
  110402. */
  110403. get: function () {
  110404. return this._captureActiveMeshesEvaluationTime;
  110405. },
  110406. /**
  110407. * Enable or disable the active meshes evaluation time capture
  110408. */
  110409. set: function (value) {
  110410. var _this = this;
  110411. if (value === this._captureActiveMeshesEvaluationTime) {
  110412. return;
  110413. }
  110414. this._captureActiveMeshesEvaluationTime = value;
  110415. if (value) {
  110416. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  110417. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  110418. _this._activeMeshesEvaluationTime.beginMonitoring();
  110419. });
  110420. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  110421. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  110422. _this._activeMeshesEvaluationTime.endMonitoring();
  110423. });
  110424. }
  110425. else {
  110426. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  110427. this._onBeforeActiveMeshesEvaluationObserver = null;
  110428. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  110429. this._onAfterActiveMeshesEvaluationObserver = null;
  110430. }
  110431. },
  110432. enumerable: true,
  110433. configurable: true
  110434. });
  110435. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  110436. /**
  110437. * Gets the perf counter used for render targets render time
  110438. */
  110439. get: function () {
  110440. return this._renderTargetsRenderTime;
  110441. },
  110442. enumerable: true,
  110443. configurable: true
  110444. });
  110445. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  110446. /**
  110447. * Gets the render targets render time capture status
  110448. */
  110449. get: function () {
  110450. return this._captureRenderTargetsRenderTime;
  110451. },
  110452. /**
  110453. * Enable or disable the render targets render time capture
  110454. */
  110455. set: function (value) {
  110456. var _this = this;
  110457. if (value === this._captureRenderTargetsRenderTime) {
  110458. return;
  110459. }
  110460. this._captureRenderTargetsRenderTime = value;
  110461. if (value) {
  110462. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  110463. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  110464. _this._renderTargetsRenderTime.beginMonitoring();
  110465. });
  110466. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  110467. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  110468. _this._renderTargetsRenderTime.endMonitoring(false);
  110469. });
  110470. }
  110471. else {
  110472. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  110473. this._onBeforeRenderTargetsRenderObserver = null;
  110474. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  110475. this._onAfterRenderTargetsRenderObserver = null;
  110476. }
  110477. },
  110478. enumerable: true,
  110479. configurable: true
  110480. });
  110481. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  110482. /**
  110483. * Gets the perf counter used for particles render time
  110484. */
  110485. get: function () {
  110486. return this._particlesRenderTime;
  110487. },
  110488. enumerable: true,
  110489. configurable: true
  110490. });
  110491. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  110492. /**
  110493. * Gets the particles render time capture status
  110494. */
  110495. get: function () {
  110496. return this._captureParticlesRenderTime;
  110497. },
  110498. /**
  110499. * Enable or disable the particles render time capture
  110500. */
  110501. set: function (value) {
  110502. var _this = this;
  110503. if (value === this._captureParticlesRenderTime) {
  110504. return;
  110505. }
  110506. this._captureParticlesRenderTime = value;
  110507. if (value) {
  110508. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  110509. BABYLON.Tools.StartPerformanceCounter("Particles");
  110510. _this._particlesRenderTime.beginMonitoring();
  110511. });
  110512. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  110513. BABYLON.Tools.EndPerformanceCounter("Particles");
  110514. _this._particlesRenderTime.endMonitoring(false);
  110515. });
  110516. }
  110517. else {
  110518. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  110519. this._onBeforeParticlesRenderingObserver = null;
  110520. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  110521. this._onAfterParticlesRenderingObserver = null;
  110522. }
  110523. },
  110524. enumerable: true,
  110525. configurable: true
  110526. });
  110527. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  110528. /**
  110529. * Gets the perf counter used for sprites render time
  110530. */
  110531. get: function () {
  110532. return this._spritesRenderTime;
  110533. },
  110534. enumerable: true,
  110535. configurable: true
  110536. });
  110537. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  110538. /**
  110539. * Gets the sprites render time capture status
  110540. */
  110541. get: function () {
  110542. return this._captureSpritesRenderTime;
  110543. },
  110544. /**
  110545. * Enable or disable the sprites render time capture
  110546. */
  110547. set: function (value) {
  110548. var _this = this;
  110549. if (value === this._captureSpritesRenderTime) {
  110550. return;
  110551. }
  110552. this._captureSpritesRenderTime = value;
  110553. if (!this.scene.spriteManagers) {
  110554. return;
  110555. }
  110556. if (value) {
  110557. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  110558. BABYLON.Tools.StartPerformanceCounter("Sprites");
  110559. _this._spritesRenderTime.beginMonitoring();
  110560. });
  110561. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  110562. BABYLON.Tools.EndPerformanceCounter("Sprites");
  110563. _this._spritesRenderTime.endMonitoring(false);
  110564. });
  110565. }
  110566. else {
  110567. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  110568. this._onBeforeSpritesRenderingObserver = null;
  110569. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  110570. this._onAfterSpritesRenderingObserver = null;
  110571. }
  110572. },
  110573. enumerable: true,
  110574. configurable: true
  110575. });
  110576. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  110577. /**
  110578. * Gets the perf counter used for physics time
  110579. */
  110580. get: function () {
  110581. return this._physicsTime;
  110582. },
  110583. enumerable: true,
  110584. configurable: true
  110585. });
  110586. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  110587. /**
  110588. * Gets the physics time capture status
  110589. */
  110590. get: function () {
  110591. return this._capturePhysicsTime;
  110592. },
  110593. /**
  110594. * Enable or disable the physics time capture
  110595. */
  110596. set: function (value) {
  110597. var _this = this;
  110598. if (value === this._capturePhysicsTime) {
  110599. return;
  110600. }
  110601. if (!this.scene.onBeforePhysicsObservable) {
  110602. return;
  110603. }
  110604. this._capturePhysicsTime = value;
  110605. if (value) {
  110606. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  110607. BABYLON.Tools.StartPerformanceCounter("Physics");
  110608. _this._physicsTime.beginMonitoring();
  110609. });
  110610. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  110611. BABYLON.Tools.EndPerformanceCounter("Physics");
  110612. _this._physicsTime.endMonitoring();
  110613. });
  110614. }
  110615. else {
  110616. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  110617. this._onBeforePhysicsObserver = null;
  110618. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  110619. this._onAfterPhysicsObserver = null;
  110620. }
  110621. },
  110622. enumerable: true,
  110623. configurable: true
  110624. });
  110625. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  110626. /**
  110627. * Gets the perf counter used for animations time
  110628. */
  110629. get: function () {
  110630. return this._animationsTime;
  110631. },
  110632. enumerable: true,
  110633. configurable: true
  110634. });
  110635. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  110636. /**
  110637. * Gets the animations time capture status
  110638. */
  110639. get: function () {
  110640. return this._captureAnimationsTime;
  110641. },
  110642. /**
  110643. * Enable or disable the animations time capture
  110644. */
  110645. set: function (value) {
  110646. var _this = this;
  110647. if (value === this._captureAnimationsTime) {
  110648. return;
  110649. }
  110650. this._captureAnimationsTime = value;
  110651. if (value) {
  110652. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  110653. _this._animationsTime.endMonitoring();
  110654. });
  110655. }
  110656. else {
  110657. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  110658. this._onAfterAnimationsObserver = null;
  110659. }
  110660. },
  110661. enumerable: true,
  110662. configurable: true
  110663. });
  110664. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  110665. /**
  110666. * Gets the perf counter used for frame time capture
  110667. */
  110668. get: function () {
  110669. return this._frameTime;
  110670. },
  110671. enumerable: true,
  110672. configurable: true
  110673. });
  110674. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  110675. /**
  110676. * Gets the frame time capture status
  110677. */
  110678. get: function () {
  110679. return this._captureFrameTime;
  110680. },
  110681. /**
  110682. * Enable or disable the frame time capture
  110683. */
  110684. set: function (value) {
  110685. this._captureFrameTime = value;
  110686. },
  110687. enumerable: true,
  110688. configurable: true
  110689. });
  110690. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  110691. /**
  110692. * Gets the perf counter used for inter-frames time capture
  110693. */
  110694. get: function () {
  110695. return this._interFrameTime;
  110696. },
  110697. enumerable: true,
  110698. configurable: true
  110699. });
  110700. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  110701. /**
  110702. * Gets the inter-frames time capture status
  110703. */
  110704. get: function () {
  110705. return this._captureInterFrameTime;
  110706. },
  110707. /**
  110708. * Enable or disable the inter-frames time capture
  110709. */
  110710. set: function (value) {
  110711. this._captureInterFrameTime = value;
  110712. },
  110713. enumerable: true,
  110714. configurable: true
  110715. });
  110716. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  110717. /**
  110718. * Gets the perf counter used for render time capture
  110719. */
  110720. get: function () {
  110721. return this._renderTime;
  110722. },
  110723. enumerable: true,
  110724. configurable: true
  110725. });
  110726. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  110727. /**
  110728. * Gets the render time capture status
  110729. */
  110730. get: function () {
  110731. return this._captureRenderTime;
  110732. },
  110733. /**
  110734. * Enable or disable the render time capture
  110735. */
  110736. set: function (value) {
  110737. var _this = this;
  110738. if (value === this._captureRenderTime) {
  110739. return;
  110740. }
  110741. this._captureRenderTime = value;
  110742. if (value) {
  110743. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  110744. _this._renderTime.beginMonitoring();
  110745. BABYLON.Tools.StartPerformanceCounter("Main render");
  110746. });
  110747. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  110748. _this._renderTime.endMonitoring(false);
  110749. BABYLON.Tools.EndPerformanceCounter("Main render");
  110750. });
  110751. }
  110752. else {
  110753. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  110754. this._onBeforeDrawPhaseObserver = null;
  110755. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  110756. this._onAfterDrawPhaseObserver = null;
  110757. }
  110758. },
  110759. enumerable: true,
  110760. configurable: true
  110761. });
  110762. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  110763. /**
  110764. * Gets the perf counter used for camera render time capture
  110765. */
  110766. get: function () {
  110767. return this._cameraRenderTime;
  110768. },
  110769. enumerable: true,
  110770. configurable: true
  110771. });
  110772. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  110773. /**
  110774. * Gets the camera render time capture status
  110775. */
  110776. get: function () {
  110777. return this._captureCameraRenderTime;
  110778. },
  110779. /**
  110780. * Enable or disable the camera render time capture
  110781. */
  110782. set: function (value) {
  110783. var _this = this;
  110784. if (value === this._captureCameraRenderTime) {
  110785. return;
  110786. }
  110787. this._captureCameraRenderTime = value;
  110788. if (value) {
  110789. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  110790. _this._cameraRenderTime.beginMonitoring();
  110791. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  110792. });
  110793. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  110794. _this._cameraRenderTime.endMonitoring(false);
  110795. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  110796. });
  110797. }
  110798. else {
  110799. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  110800. this._onBeforeCameraRenderObserver = null;
  110801. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  110802. this._onAfterCameraRenderObserver = null;
  110803. }
  110804. },
  110805. enumerable: true,
  110806. configurable: true
  110807. });
  110808. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  110809. /**
  110810. * Gets the perf counter used for draw calls
  110811. */
  110812. get: function () {
  110813. return this.scene.getEngine()._drawCalls;
  110814. },
  110815. enumerable: true,
  110816. configurable: true
  110817. });
  110818. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  110819. /**
  110820. * Gets the perf counter used for texture collisions
  110821. */
  110822. get: function () {
  110823. return this.scene.getEngine()._textureCollisions;
  110824. },
  110825. enumerable: true,
  110826. configurable: true
  110827. });
  110828. /**
  110829. * Dispose and release associated resources.
  110830. */
  110831. SceneInstrumentation.prototype.dispose = function () {
  110832. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  110833. this._onAfterRenderObserver = null;
  110834. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  110835. this._onBeforeActiveMeshesEvaluationObserver = null;
  110836. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  110837. this._onAfterActiveMeshesEvaluationObserver = null;
  110838. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  110839. this._onBeforeRenderTargetsRenderObserver = null;
  110840. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  110841. this._onAfterRenderTargetsRenderObserver = null;
  110842. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  110843. this._onBeforeAnimationsObserver = null;
  110844. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  110845. this._onBeforeParticlesRenderingObserver = null;
  110846. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  110847. this._onAfterParticlesRenderingObserver = null;
  110848. if (this._onBeforeSpritesRenderingObserver) {
  110849. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  110850. this._onBeforeSpritesRenderingObserver = null;
  110851. }
  110852. if (this._onAfterSpritesRenderingObserver) {
  110853. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  110854. this._onAfterSpritesRenderingObserver = null;
  110855. }
  110856. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  110857. this._onBeforeDrawPhaseObserver = null;
  110858. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  110859. this._onAfterDrawPhaseObserver = null;
  110860. if (this._onBeforePhysicsObserver) {
  110861. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  110862. this._onBeforePhysicsObserver = null;
  110863. }
  110864. if (this._onAfterPhysicsObserver) {
  110865. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  110866. this._onAfterPhysicsObserver = null;
  110867. }
  110868. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  110869. this._onAfterAnimationsObserver = null;
  110870. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  110871. this._onBeforeCameraRenderObserver = null;
  110872. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  110873. this._onAfterCameraRenderObserver = null;
  110874. this.scene = null;
  110875. };
  110876. return SceneInstrumentation;
  110877. }());
  110878. BABYLON.SceneInstrumentation = SceneInstrumentation;
  110879. })(BABYLON || (BABYLON = {}));
  110880. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  110881. var BABYLON;
  110882. (function (BABYLON) {
  110883. /**
  110884. * @hidden
  110885. **/
  110886. var _TimeToken = /** @class */ (function () {
  110887. function _TimeToken() {
  110888. this._timeElapsedQueryEnded = false;
  110889. }
  110890. return _TimeToken;
  110891. }());
  110892. BABYLON._TimeToken = _TimeToken;
  110893. })(BABYLON || (BABYLON = {}));
  110894. //# sourceMappingURL=babylon.timeToken.js.map
  110895. var BABYLON;
  110896. (function (BABYLON) {
  110897. /**
  110898. * Background material defines definition.
  110899. * @hidden Mainly internal Use
  110900. */
  110901. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  110902. __extends(BackgroundMaterialDefines, _super);
  110903. /**
  110904. * Constructor of the defines.
  110905. */
  110906. function BackgroundMaterialDefines() {
  110907. var _this = _super.call(this) || this;
  110908. /**
  110909. * True if the diffuse texture is in use.
  110910. */
  110911. _this.DIFFUSE = false;
  110912. /**
  110913. * The direct UV channel to use.
  110914. */
  110915. _this.DIFFUSEDIRECTUV = 0;
  110916. /**
  110917. * True if the diffuse texture is in gamma space.
  110918. */
  110919. _this.GAMMADIFFUSE = false;
  110920. /**
  110921. * True if the diffuse texture has opacity in the alpha channel.
  110922. */
  110923. _this.DIFFUSEHASALPHA = false;
  110924. /**
  110925. * True if you want the material to fade to transparent at grazing angle.
  110926. */
  110927. _this.OPACITYFRESNEL = false;
  110928. /**
  110929. * True if an extra blur needs to be added in the reflection.
  110930. */
  110931. _this.REFLECTIONBLUR = false;
  110932. /**
  110933. * True if you want the material to fade to reflection at grazing angle.
  110934. */
  110935. _this.REFLECTIONFRESNEL = false;
  110936. /**
  110937. * True if you want the material to falloff as far as you move away from the scene center.
  110938. */
  110939. _this.REFLECTIONFALLOFF = false;
  110940. /**
  110941. * False if the current Webgl implementation does not support the texture lod extension.
  110942. */
  110943. _this.TEXTURELODSUPPORT = false;
  110944. /**
  110945. * True to ensure the data are premultiplied.
  110946. */
  110947. _this.PREMULTIPLYALPHA = false;
  110948. /**
  110949. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  110950. */
  110951. _this.USERGBCOLOR = false;
  110952. /**
  110953. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  110954. * stays aligned with the desired configuration.
  110955. */
  110956. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  110957. /**
  110958. * True to add noise in order to reduce the banding effect.
  110959. */
  110960. _this.NOISE = false;
  110961. /**
  110962. * is the reflection texture in BGR color scheme?
  110963. * Mainly used to solve a bug in ios10 video tag
  110964. */
  110965. _this.REFLECTIONBGR = false;
  110966. _this.IMAGEPROCESSING = false;
  110967. _this.VIGNETTE = false;
  110968. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  110969. _this.VIGNETTEBLENDMODEOPAQUE = false;
  110970. _this.TONEMAPPING = false;
  110971. _this.TONEMAPPING_ACES = false;
  110972. _this.CONTRAST = false;
  110973. _this.COLORCURVES = false;
  110974. _this.COLORGRADING = false;
  110975. _this.COLORGRADING3D = false;
  110976. _this.SAMPLER3DGREENDEPTH = false;
  110977. _this.SAMPLER3DBGRMAP = false;
  110978. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  110979. _this.EXPOSURE = false;
  110980. // Reflection.
  110981. _this.REFLECTION = false;
  110982. _this.REFLECTIONMAP_3D = false;
  110983. _this.REFLECTIONMAP_SPHERICAL = false;
  110984. _this.REFLECTIONMAP_PLANAR = false;
  110985. _this.REFLECTIONMAP_CUBIC = false;
  110986. _this.REFLECTIONMAP_PROJECTION = false;
  110987. _this.REFLECTIONMAP_SKYBOX = false;
  110988. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  110989. _this.REFLECTIONMAP_EXPLICIT = false;
  110990. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  110991. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  110992. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  110993. _this.INVERTCUBICMAP = false;
  110994. _this.REFLECTIONMAP_OPPOSITEZ = false;
  110995. _this.LODINREFLECTIONALPHA = false;
  110996. _this.GAMMAREFLECTION = false;
  110997. _this.RGBDREFLECTION = false;
  110998. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  110999. // Default BJS.
  111000. _this.MAINUV1 = false;
  111001. _this.MAINUV2 = false;
  111002. _this.UV1 = false;
  111003. _this.UV2 = false;
  111004. _this.CLIPPLANE = false;
  111005. _this.CLIPPLANE2 = false;
  111006. _this.CLIPPLANE3 = false;
  111007. _this.CLIPPLANE4 = false;
  111008. _this.POINTSIZE = false;
  111009. _this.FOG = false;
  111010. _this.NORMAL = false;
  111011. _this.NUM_BONE_INFLUENCERS = 0;
  111012. _this.BonesPerMesh = 0;
  111013. _this.INSTANCES = false;
  111014. _this.SHADOWFLOAT = false;
  111015. _this.rebuild();
  111016. return _this;
  111017. }
  111018. return BackgroundMaterialDefines;
  111019. }(BABYLON.MaterialDefines));
  111020. /**
  111021. * Background material used to create an efficient environement around your scene.
  111022. */
  111023. var BackgroundMaterial = /** @class */ (function (_super) {
  111024. __extends(BackgroundMaterial, _super);
  111025. /**
  111026. * Instantiates a Background Material in the given scene
  111027. * @param name The friendly name of the material
  111028. * @param scene The scene to add the material to
  111029. */
  111030. function BackgroundMaterial(name, scene) {
  111031. var _this = _super.call(this, name, scene) || this;
  111032. /**
  111033. * Key light Color (multiply against the environement texture)
  111034. */
  111035. _this.primaryColor = BABYLON.Color3.White();
  111036. _this._primaryColorShadowLevel = 0;
  111037. _this._primaryColorHighlightLevel = 0;
  111038. /**
  111039. * Reflection Texture used in the material.
  111040. * Should be author in a specific way for the best result (refer to the documentation).
  111041. */
  111042. _this.reflectionTexture = null;
  111043. /**
  111044. * Reflection Texture level of blur.
  111045. *
  111046. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  111047. * texture twice.
  111048. */
  111049. _this.reflectionBlur = 0;
  111050. /**
  111051. * Diffuse Texture used in the material.
  111052. * Should be author in a specific way for the best result (refer to the documentation).
  111053. */
  111054. _this.diffuseTexture = null;
  111055. _this._shadowLights = null;
  111056. /**
  111057. * Specify the list of lights casting shadow on the material.
  111058. * All scene shadow lights will be included if null.
  111059. */
  111060. _this.shadowLights = null;
  111061. /**
  111062. * Helps adjusting the shadow to a softer level if required.
  111063. * 0 means black shadows and 1 means no shadows.
  111064. */
  111065. _this.shadowLevel = 0;
  111066. /**
  111067. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  111068. * It is usually zero but might be interesting to modify according to your setup.
  111069. */
  111070. _this.sceneCenter = BABYLON.Vector3.Zero();
  111071. /**
  111072. * This helps specifying that the material is falling off to the sky box at grazing angle.
  111073. * This helps ensuring a nice transition when the camera goes under the ground.
  111074. */
  111075. _this.opacityFresnel = true;
  111076. /**
  111077. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  111078. * This helps adding a mirror texture on the ground.
  111079. */
  111080. _this.reflectionFresnel = false;
  111081. /**
  111082. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  111083. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  111084. */
  111085. _this.reflectionFalloffDistance = 0.0;
  111086. /**
  111087. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  111088. */
  111089. _this.reflectionAmount = 1.0;
  111090. /**
  111091. * This specifies the weight of the reflection at grazing angle.
  111092. */
  111093. _this.reflectionReflectance0 = 0.05;
  111094. /**
  111095. * This specifies the weight of the reflection at a perpendicular point of view.
  111096. */
  111097. _this.reflectionReflectance90 = 0.5;
  111098. /**
  111099. * Helps to directly use the maps channels instead of their level.
  111100. */
  111101. _this.useRGBColor = true;
  111102. /**
  111103. * This helps reducing the banding effect that could occur on the background.
  111104. */
  111105. _this.enableNoise = false;
  111106. _this._fovMultiplier = 1.0;
  111107. /**
  111108. * Enable the FOV adjustment feature controlled by fovMultiplier.
  111109. */
  111110. _this.useEquirectangularFOV = false;
  111111. _this._maxSimultaneousLights = 4;
  111112. /**
  111113. * Number of Simultaneous lights allowed on the material.
  111114. */
  111115. _this.maxSimultaneousLights = 4;
  111116. /**
  111117. * Keep track of the image processing observer to allow dispose and replace.
  111118. */
  111119. _this._imageProcessingObserver = null;
  111120. /**
  111121. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  111122. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  111123. */
  111124. _this.switchToBGR = false;
  111125. // Temp values kept as cache in the material.
  111126. _this._renderTargets = new BABYLON.SmartArray(16);
  111127. _this._reflectionControls = BABYLON.Vector4.Zero();
  111128. _this._white = BABYLON.Color3.White();
  111129. _this._primaryShadowColor = BABYLON.Color3.Black();
  111130. _this._primaryHighlightColor = BABYLON.Color3.Black();
  111131. // Setup the default processing configuration to the scene.
  111132. _this._attachImageProcessingConfiguration(null);
  111133. _this.getRenderTargetTextures = function () {
  111134. _this._renderTargets.reset();
  111135. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  111136. _this._renderTargets.push(_this._diffuseTexture);
  111137. }
  111138. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  111139. _this._renderTargets.push(_this._reflectionTexture);
  111140. }
  111141. return _this._renderTargets;
  111142. };
  111143. return _this;
  111144. }
  111145. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  111146. /**
  111147. * Experimental Internal Use Only.
  111148. *
  111149. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  111150. * This acts as a helper to set the primary color to a more "human friendly" value.
  111151. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  111152. * output color as close as possible from the chosen value.
  111153. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  111154. * part of lighting setup.)
  111155. */
  111156. get: function () {
  111157. return this.__perceptualColor;
  111158. },
  111159. set: function (value) {
  111160. this.__perceptualColor = value;
  111161. this._computePrimaryColorFromPerceptualColor();
  111162. this._markAllSubMeshesAsLightsDirty();
  111163. },
  111164. enumerable: true,
  111165. configurable: true
  111166. });
  111167. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  111168. /**
  111169. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  111170. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  111171. */
  111172. get: function () {
  111173. return this._primaryColorShadowLevel;
  111174. },
  111175. set: function (value) {
  111176. this._primaryColorShadowLevel = value;
  111177. this._computePrimaryColors();
  111178. this._markAllSubMeshesAsLightsDirty();
  111179. },
  111180. enumerable: true,
  111181. configurable: true
  111182. });
  111183. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  111184. /**
  111185. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  111186. * The primary color is used at the level chosen to define what the white area would look.
  111187. */
  111188. get: function () {
  111189. return this._primaryColorHighlightLevel;
  111190. },
  111191. set: function (value) {
  111192. this._primaryColorHighlightLevel = value;
  111193. this._computePrimaryColors();
  111194. this._markAllSubMeshesAsLightsDirty();
  111195. },
  111196. enumerable: true,
  111197. configurable: true
  111198. });
  111199. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  111200. /**
  111201. * Sets the reflection reflectance fresnel values according to the default standard
  111202. * empirically know to work well :-)
  111203. */
  111204. set: function (value) {
  111205. var reflectionWeight = value;
  111206. if (reflectionWeight < 0.5) {
  111207. reflectionWeight = reflectionWeight * 2.0;
  111208. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  111209. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  111210. }
  111211. else {
  111212. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  111213. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  111214. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  111215. }
  111216. },
  111217. enumerable: true,
  111218. configurable: true
  111219. });
  111220. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  111221. /**
  111222. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  111223. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  111224. * Recommended to be keep at 1.0 except for special cases.
  111225. */
  111226. get: function () {
  111227. return this._fovMultiplier;
  111228. },
  111229. set: function (value) {
  111230. if (isNaN(value)) {
  111231. value = 1.0;
  111232. }
  111233. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  111234. },
  111235. enumerable: true,
  111236. configurable: true
  111237. });
  111238. /**
  111239. * Attaches a new image processing configuration to the PBR Material.
  111240. * @param configuration (if null the scene configuration will be use)
  111241. */
  111242. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  111243. var _this = this;
  111244. if (configuration === this._imageProcessingConfiguration) {
  111245. return;
  111246. }
  111247. // Detaches observer.
  111248. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  111249. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  111250. }
  111251. // Pick the scene configuration if needed.
  111252. if (!configuration) {
  111253. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  111254. }
  111255. else {
  111256. this._imageProcessingConfiguration = configuration;
  111257. }
  111258. // Attaches observer.
  111259. if (this._imageProcessingConfiguration) {
  111260. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  111261. _this._computePrimaryColorFromPerceptualColor();
  111262. _this._markAllSubMeshesAsImageProcessingDirty();
  111263. });
  111264. }
  111265. };
  111266. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  111267. /**
  111268. * Gets the image processing configuration used either in this material.
  111269. */
  111270. get: function () {
  111271. return this._imageProcessingConfiguration;
  111272. },
  111273. /**
  111274. * Sets the Default image processing configuration used either in the this material.
  111275. *
  111276. * If sets to null, the scene one is in use.
  111277. */
  111278. set: function (value) {
  111279. this._attachImageProcessingConfiguration(value);
  111280. // Ensure the effect will be rebuilt.
  111281. this._markAllSubMeshesAsTexturesDirty();
  111282. },
  111283. enumerable: true,
  111284. configurable: true
  111285. });
  111286. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  111287. /**
  111288. * Gets wether the color curves effect is enabled.
  111289. */
  111290. get: function () {
  111291. return this.imageProcessingConfiguration.colorCurvesEnabled;
  111292. },
  111293. /**
  111294. * Sets wether the color curves effect is enabled.
  111295. */
  111296. set: function (value) {
  111297. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  111298. },
  111299. enumerable: true,
  111300. configurable: true
  111301. });
  111302. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  111303. /**
  111304. * Gets wether the color grading effect is enabled.
  111305. */
  111306. get: function () {
  111307. return this.imageProcessingConfiguration.colorGradingEnabled;
  111308. },
  111309. /**
  111310. * Gets wether the color grading effect is enabled.
  111311. */
  111312. set: function (value) {
  111313. this.imageProcessingConfiguration.colorGradingEnabled = value;
  111314. },
  111315. enumerable: true,
  111316. configurable: true
  111317. });
  111318. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  111319. /**
  111320. * Gets wether tonemapping is enabled or not.
  111321. */
  111322. get: function () {
  111323. return this._imageProcessingConfiguration.toneMappingEnabled;
  111324. },
  111325. /**
  111326. * Sets wether tonemapping is enabled or not
  111327. */
  111328. set: function (value) {
  111329. this._imageProcessingConfiguration.toneMappingEnabled = value;
  111330. },
  111331. enumerable: true,
  111332. configurable: true
  111333. });
  111334. ;
  111335. ;
  111336. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  111337. /**
  111338. * The camera exposure used on this material.
  111339. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  111340. * This corresponds to a photographic exposure.
  111341. */
  111342. get: function () {
  111343. return this._imageProcessingConfiguration.exposure;
  111344. },
  111345. /**
  111346. * The camera exposure used on this material.
  111347. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  111348. * This corresponds to a photographic exposure.
  111349. */
  111350. set: function (value) {
  111351. this._imageProcessingConfiguration.exposure = value;
  111352. },
  111353. enumerable: true,
  111354. configurable: true
  111355. });
  111356. ;
  111357. ;
  111358. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  111359. /**
  111360. * Gets The camera contrast used on this material.
  111361. */
  111362. get: function () {
  111363. return this._imageProcessingConfiguration.contrast;
  111364. },
  111365. /**
  111366. * Sets The camera contrast used on this material.
  111367. */
  111368. set: function (value) {
  111369. this._imageProcessingConfiguration.contrast = value;
  111370. },
  111371. enumerable: true,
  111372. configurable: true
  111373. });
  111374. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  111375. /**
  111376. * Gets the Color Grading 2D Lookup Texture.
  111377. */
  111378. get: function () {
  111379. return this._imageProcessingConfiguration.colorGradingTexture;
  111380. },
  111381. /**
  111382. * Sets the Color Grading 2D Lookup Texture.
  111383. */
  111384. set: function (value) {
  111385. this.imageProcessingConfiguration.colorGradingTexture = value;
  111386. },
  111387. enumerable: true,
  111388. configurable: true
  111389. });
  111390. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  111391. /**
  111392. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  111393. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  111394. * 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;
  111395. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  111396. */
  111397. get: function () {
  111398. return this.imageProcessingConfiguration.colorCurves;
  111399. },
  111400. /**
  111401. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  111402. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  111403. * 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;
  111404. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  111405. */
  111406. set: function (value) {
  111407. this.imageProcessingConfiguration.colorCurves = value;
  111408. },
  111409. enumerable: true,
  111410. configurable: true
  111411. });
  111412. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  111413. /**
  111414. * Gets a boolean indicating that current material needs to register RTT
  111415. */
  111416. get: function () {
  111417. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  111418. return true;
  111419. }
  111420. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  111421. return true;
  111422. }
  111423. return false;
  111424. },
  111425. enumerable: true,
  111426. configurable: true
  111427. });
  111428. /**
  111429. * The entire material has been created in order to prevent overdraw.
  111430. * @returns false
  111431. */
  111432. BackgroundMaterial.prototype.needAlphaTesting = function () {
  111433. return true;
  111434. };
  111435. /**
  111436. * The entire material has been created in order to prevent overdraw.
  111437. * @returns true if blending is enable
  111438. */
  111439. BackgroundMaterial.prototype.needAlphaBlending = function () {
  111440. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  111441. };
  111442. /**
  111443. * Checks wether the material is ready to be rendered for a given mesh.
  111444. * @param mesh The mesh to render
  111445. * @param subMesh The submesh to check against
  111446. * @param useInstances Specify wether or not the material is used with instances
  111447. * @returns true if all the dependencies are ready (Textures, Effects...)
  111448. */
  111449. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  111450. var _this = this;
  111451. if (useInstances === void 0) { useInstances = false; }
  111452. if (subMesh.effect && this.isFrozen) {
  111453. if (this._wasPreviouslyReady) {
  111454. return true;
  111455. }
  111456. }
  111457. if (!subMesh._materialDefines) {
  111458. subMesh._materialDefines = new BackgroundMaterialDefines();
  111459. }
  111460. var scene = this.getScene();
  111461. var defines = subMesh._materialDefines;
  111462. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  111463. if (defines._renderId === scene.getRenderId()) {
  111464. return true;
  111465. }
  111466. }
  111467. var engine = scene.getEngine();
  111468. // Lights
  111469. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  111470. defines._needNormals = true;
  111471. // Textures
  111472. if (defines._areTexturesDirty) {
  111473. defines._needUVs = false;
  111474. if (scene.texturesEnabled) {
  111475. if (scene.getEngine().getCaps().textureLOD) {
  111476. defines.TEXTURELODSUPPORT = true;
  111477. }
  111478. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  111479. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  111480. return false;
  111481. }
  111482. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  111483. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  111484. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  111485. defines.OPACITYFRESNEL = this._opacityFresnel;
  111486. }
  111487. else {
  111488. defines.DIFFUSE = false;
  111489. defines.DIFFUSEHASALPHA = false;
  111490. defines.GAMMADIFFUSE = false;
  111491. defines.OPACITYFRESNEL = false;
  111492. }
  111493. var reflectionTexture = this._reflectionTexture;
  111494. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  111495. if (!reflectionTexture.isReadyOrNotBlocking()) {
  111496. return false;
  111497. }
  111498. defines.REFLECTION = true;
  111499. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  111500. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  111501. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  111502. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  111503. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  111504. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  111505. defines.REFLECTIONBGR = this.switchToBGR;
  111506. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  111507. defines.INVERTCUBICMAP = true;
  111508. }
  111509. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  111510. switch (reflectionTexture.coordinatesMode) {
  111511. case BABYLON.Texture.EXPLICIT_MODE:
  111512. defines.REFLECTIONMAP_EXPLICIT = true;
  111513. break;
  111514. case BABYLON.Texture.PLANAR_MODE:
  111515. defines.REFLECTIONMAP_PLANAR = true;
  111516. break;
  111517. case BABYLON.Texture.PROJECTION_MODE:
  111518. defines.REFLECTIONMAP_PROJECTION = true;
  111519. break;
  111520. case BABYLON.Texture.SKYBOX_MODE:
  111521. defines.REFLECTIONMAP_SKYBOX = true;
  111522. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  111523. break;
  111524. case BABYLON.Texture.SPHERICAL_MODE:
  111525. defines.REFLECTIONMAP_SPHERICAL = true;
  111526. break;
  111527. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  111528. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  111529. break;
  111530. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  111531. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  111532. break;
  111533. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  111534. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  111535. break;
  111536. case BABYLON.Texture.CUBIC_MODE:
  111537. case BABYLON.Texture.INVCUBIC_MODE:
  111538. default:
  111539. defines.REFLECTIONMAP_CUBIC = true;
  111540. break;
  111541. }
  111542. if (this.reflectionFresnel) {
  111543. defines.REFLECTIONFRESNEL = true;
  111544. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  111545. this._reflectionControls.x = this.reflectionAmount;
  111546. this._reflectionControls.y = this.reflectionReflectance0;
  111547. this._reflectionControls.z = this.reflectionReflectance90;
  111548. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  111549. }
  111550. else {
  111551. defines.REFLECTIONFRESNEL = false;
  111552. defines.REFLECTIONFALLOFF = false;
  111553. }
  111554. }
  111555. else {
  111556. defines.REFLECTION = false;
  111557. defines.REFLECTIONFRESNEL = false;
  111558. defines.REFLECTIONFALLOFF = false;
  111559. defines.REFLECTIONBLUR = false;
  111560. defines.REFLECTIONMAP_3D = false;
  111561. defines.REFLECTIONMAP_SPHERICAL = false;
  111562. defines.REFLECTIONMAP_PLANAR = false;
  111563. defines.REFLECTIONMAP_CUBIC = false;
  111564. defines.REFLECTIONMAP_PROJECTION = false;
  111565. defines.REFLECTIONMAP_SKYBOX = false;
  111566. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  111567. defines.REFLECTIONMAP_EXPLICIT = false;
  111568. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  111569. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  111570. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  111571. defines.INVERTCUBICMAP = false;
  111572. defines.REFLECTIONMAP_OPPOSITEZ = false;
  111573. defines.LODINREFLECTIONALPHA = false;
  111574. defines.GAMMAREFLECTION = false;
  111575. defines.RGBDREFLECTION = false;
  111576. }
  111577. }
  111578. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  111579. defines.USERGBCOLOR = this._useRGBColor;
  111580. defines.NOISE = this._enableNoise;
  111581. }
  111582. if (defines._areLightsDirty) {
  111583. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  111584. }
  111585. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  111586. if (!this._imageProcessingConfiguration.isReady()) {
  111587. return false;
  111588. }
  111589. this._imageProcessingConfiguration.prepareDefines(defines);
  111590. }
  111591. // Misc.
  111592. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  111593. // Values that need to be evaluated on every frame
  111594. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  111595. // Attribs
  111596. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  111597. if (mesh) {
  111598. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  111599. mesh.createNormals(true);
  111600. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  111601. }
  111602. }
  111603. }
  111604. // Get correct effect
  111605. if (defines.isDirty) {
  111606. defines.markAsProcessed();
  111607. scene.resetCachedMaterial();
  111608. // Fallbacks
  111609. var fallbacks = new BABYLON.EffectFallbacks();
  111610. if (defines.FOG) {
  111611. fallbacks.addFallback(0, "FOG");
  111612. }
  111613. if (defines.POINTSIZE) {
  111614. fallbacks.addFallback(1, "POINTSIZE");
  111615. }
  111616. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  111617. if (defines.NUM_BONE_INFLUENCERS > 0) {
  111618. fallbacks.addCPUSkinningFallback(0, mesh);
  111619. }
  111620. //Attributes
  111621. var attribs = [BABYLON.VertexBuffer.PositionKind];
  111622. if (defines.NORMAL) {
  111623. attribs.push(BABYLON.VertexBuffer.NormalKind);
  111624. }
  111625. if (defines.UV1) {
  111626. attribs.push(BABYLON.VertexBuffer.UVKind);
  111627. }
  111628. if (defines.UV2) {
  111629. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  111630. }
  111631. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  111632. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  111633. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  111634. "vFogInfos", "vFogColor", "pointSize",
  111635. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  111636. "vPrimaryColor", "vPrimaryColorShadow",
  111637. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  111638. "shadowLevel", "alpha",
  111639. "vBackgroundCenter", "vReflectionControl",
  111640. "vDiffuseInfos", "diffuseMatrix",
  111641. ];
  111642. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  111643. var uniformBuffers = ["Material", "Scene"];
  111644. if (BABYLON.ImageProcessingConfiguration) {
  111645. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  111646. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  111647. }
  111648. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  111649. uniformsNames: uniforms,
  111650. uniformBuffersNames: uniformBuffers,
  111651. samplers: samplers,
  111652. defines: defines,
  111653. maxSimultaneousLights: this._maxSimultaneousLights
  111654. });
  111655. var onCompiled = function (effect) {
  111656. if (_this.onCompiled) {
  111657. _this.onCompiled(effect);
  111658. }
  111659. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  111660. };
  111661. var join = defines.toString();
  111662. subMesh.setEffect(scene.getEngine().createEffect("background", {
  111663. attributes: attribs,
  111664. uniformsNames: uniforms,
  111665. uniformBuffersNames: uniformBuffers,
  111666. samplers: samplers,
  111667. defines: join,
  111668. fallbacks: fallbacks,
  111669. onCompiled: onCompiled,
  111670. onError: this.onError,
  111671. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  111672. }, engine), defines);
  111673. this.buildUniformLayout();
  111674. }
  111675. if (!subMesh.effect || !subMesh.effect.isReady()) {
  111676. return false;
  111677. }
  111678. defines._renderId = scene.getRenderId();
  111679. this._wasPreviouslyReady = true;
  111680. return true;
  111681. };
  111682. /**
  111683. * Compute the primary color according to the chosen perceptual color.
  111684. */
  111685. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  111686. if (!this.__perceptualColor) {
  111687. return;
  111688. }
  111689. this._primaryColor.copyFrom(this.__perceptualColor);
  111690. // Revert gamma space.
  111691. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  111692. // Revert image processing configuration.
  111693. if (this._imageProcessingConfiguration) {
  111694. // Revert Exposure.
  111695. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  111696. }
  111697. this._computePrimaryColors();
  111698. };
  111699. /**
  111700. * Compute the highlights and shadow colors according to their chosen levels.
  111701. */
  111702. BackgroundMaterial.prototype._computePrimaryColors = function () {
  111703. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  111704. return;
  111705. }
  111706. // Find the highlight color based on the configuration.
  111707. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  111708. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  111709. // Find the shadow color based on the configuration.
  111710. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  111711. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  111712. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  111713. };
  111714. /**
  111715. * Build the uniform buffer used in the material.
  111716. */
  111717. BackgroundMaterial.prototype.buildUniformLayout = function () {
  111718. // Order is important !
  111719. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  111720. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  111721. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  111722. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  111723. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  111724. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  111725. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  111726. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  111727. this._uniformBuffer.addUniform("pointSize", 1);
  111728. this._uniformBuffer.addUniform("shadowLevel", 1);
  111729. this._uniformBuffer.addUniform("alpha", 1);
  111730. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  111731. this._uniformBuffer.addUniform("vReflectionControl", 4);
  111732. this._uniformBuffer.create();
  111733. };
  111734. /**
  111735. * Unbind the material.
  111736. */
  111737. BackgroundMaterial.prototype.unbind = function () {
  111738. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  111739. this._uniformBuffer.setTexture("diffuseSampler", null);
  111740. }
  111741. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  111742. this._uniformBuffer.setTexture("reflectionSampler", null);
  111743. }
  111744. _super.prototype.unbind.call(this);
  111745. };
  111746. /**
  111747. * Bind only the world matrix to the material.
  111748. * @param world The world matrix to bind.
  111749. */
  111750. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  111751. this._activeEffect.setMatrix("world", world);
  111752. };
  111753. /**
  111754. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  111755. * @param world The world matrix to bind.
  111756. * @param subMesh The submesh to bind for.
  111757. */
  111758. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  111759. var scene = this.getScene();
  111760. var defines = subMesh._materialDefines;
  111761. if (!defines) {
  111762. return;
  111763. }
  111764. var effect = subMesh.effect;
  111765. if (!effect) {
  111766. return;
  111767. }
  111768. this._activeEffect = effect;
  111769. // Matrices
  111770. this.bindOnlyWorldMatrix(world);
  111771. // Bones
  111772. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  111773. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  111774. if (mustRebind) {
  111775. this._uniformBuffer.bindToEffect(effect, "Material");
  111776. this.bindViewProjection(effect);
  111777. var reflectionTexture = this._reflectionTexture;
  111778. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  111779. // Texture uniforms
  111780. if (scene.texturesEnabled) {
  111781. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  111782. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  111783. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  111784. }
  111785. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  111786. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  111787. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  111788. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  111789. }
  111790. }
  111791. if (this.shadowLevel > 0) {
  111792. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  111793. }
  111794. this._uniformBuffer.updateFloat("alpha", this.alpha);
  111795. // Point size
  111796. if (this.pointsCloud) {
  111797. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  111798. }
  111799. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  111800. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  111801. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  111802. }
  111803. else {
  111804. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  111805. }
  111806. }
  111807. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  111808. // Textures
  111809. if (scene.texturesEnabled) {
  111810. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  111811. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  111812. }
  111813. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  111814. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  111815. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  111816. }
  111817. else if (!defines.REFLECTIONBLUR) {
  111818. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  111819. }
  111820. else {
  111821. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  111822. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  111823. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  111824. }
  111825. if (defines.REFLECTIONFRESNEL) {
  111826. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  111827. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  111828. }
  111829. }
  111830. }
  111831. // Clip plane
  111832. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  111833. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  111834. }
  111835. if (mustRebind || !this.isFrozen) {
  111836. if (scene.lightsEnabled) {
  111837. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  111838. }
  111839. // View
  111840. this.bindView(effect);
  111841. // Fog
  111842. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  111843. // image processing
  111844. if (this._imageProcessingConfiguration) {
  111845. this._imageProcessingConfiguration.bind(this._activeEffect);
  111846. }
  111847. }
  111848. this._uniformBuffer.update();
  111849. this._afterBind(mesh, this._activeEffect);
  111850. };
  111851. /**
  111852. * Dispose the material.
  111853. * @param forceDisposeEffect Force disposal of the associated effect.
  111854. * @param forceDisposeTextures Force disposal of the associated textures.
  111855. */
  111856. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  111857. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  111858. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  111859. if (forceDisposeTextures) {
  111860. if (this.diffuseTexture) {
  111861. this.diffuseTexture.dispose();
  111862. }
  111863. if (this.reflectionTexture) {
  111864. this.reflectionTexture.dispose();
  111865. }
  111866. }
  111867. this._renderTargets.dispose();
  111868. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  111869. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  111870. }
  111871. _super.prototype.dispose.call(this, forceDisposeEffect);
  111872. };
  111873. /**
  111874. * Clones the material.
  111875. * @param name The cloned name.
  111876. * @returns The cloned material.
  111877. */
  111878. BackgroundMaterial.prototype.clone = function (name) {
  111879. var _this = this;
  111880. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  111881. };
  111882. /**
  111883. * Serializes the current material to its JSON representation.
  111884. * @returns The JSON representation.
  111885. */
  111886. BackgroundMaterial.prototype.serialize = function () {
  111887. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  111888. serializationObject.customType = "BABYLON.BackgroundMaterial";
  111889. return serializationObject;
  111890. };
  111891. /**
  111892. * Gets the class name of the material
  111893. * @returns "BackgroundMaterial"
  111894. */
  111895. BackgroundMaterial.prototype.getClassName = function () {
  111896. return "BackgroundMaterial";
  111897. };
  111898. /**
  111899. * Parse a JSON input to create back a background material.
  111900. * @param source The JSON data to parse
  111901. * @param scene The scene to create the parsed material in
  111902. * @param rootUrl The root url of the assets the material depends upon
  111903. * @returns the instantiated BackgroundMaterial.
  111904. */
  111905. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  111906. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  111907. };
  111908. /**
  111909. * Standard reflectance value at parallel view angle.
  111910. */
  111911. BackgroundMaterial.StandardReflectance0 = 0.05;
  111912. /**
  111913. * Standard reflectance value at grazing angle.
  111914. */
  111915. BackgroundMaterial.StandardReflectance90 = 0.5;
  111916. __decorate([
  111917. BABYLON.serializeAsColor3()
  111918. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  111919. __decorate([
  111920. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  111921. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  111922. __decorate([
  111923. BABYLON.serializeAsColor3()
  111924. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  111925. __decorate([
  111926. BABYLON.serialize()
  111927. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  111928. __decorate([
  111929. BABYLON.serialize()
  111930. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  111931. __decorate([
  111932. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  111933. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  111934. __decorate([
  111935. BABYLON.serializeAsTexture()
  111936. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  111937. __decorate([
  111938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111939. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  111940. __decorate([
  111941. BABYLON.serialize()
  111942. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  111943. __decorate([
  111944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111945. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  111946. __decorate([
  111947. BABYLON.serializeAsTexture()
  111948. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  111949. __decorate([
  111950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111951. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  111952. __decorate([
  111953. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111954. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  111955. __decorate([
  111956. BABYLON.serialize()
  111957. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  111958. __decorate([
  111959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111960. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  111961. __decorate([
  111962. BABYLON.serializeAsVector3()
  111963. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  111964. __decorate([
  111965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111966. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  111967. __decorate([
  111968. BABYLON.serialize()
  111969. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  111970. __decorate([
  111971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111972. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  111973. __decorate([
  111974. BABYLON.serialize()
  111975. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  111976. __decorate([
  111977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111978. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  111979. __decorate([
  111980. BABYLON.serialize()
  111981. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  111982. __decorate([
  111983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111984. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  111985. __decorate([
  111986. BABYLON.serialize()
  111987. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  111988. __decorate([
  111989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111990. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  111991. __decorate([
  111992. BABYLON.serialize()
  111993. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  111994. __decorate([
  111995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111996. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  111997. __decorate([
  111998. BABYLON.serialize()
  111999. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  112000. __decorate([
  112001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112002. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  112003. __decorate([
  112004. BABYLON.serialize()
  112005. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  112006. __decorate([
  112007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112008. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  112009. __decorate([
  112010. BABYLON.serialize()
  112011. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  112012. __decorate([
  112013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112014. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  112015. __decorate([
  112016. BABYLON.serialize()
  112017. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  112018. __decorate([
  112019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  112020. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  112021. __decorate([
  112022. BABYLON.serializeAsImageProcessingConfiguration()
  112023. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  112024. return BackgroundMaterial;
  112025. }(BABYLON.PushMaterial));
  112026. BABYLON.BackgroundMaterial = BackgroundMaterial;
  112027. })(BABYLON || (BABYLON = {}));
  112028. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  112029. var __assign = (this && this.__assign) || function () {
  112030. __assign = Object.assign || function(t) {
  112031. for (var s, i = 1, n = arguments.length; i < n; i++) {
  112032. s = arguments[i];
  112033. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  112034. t[p] = s[p];
  112035. }
  112036. return t;
  112037. };
  112038. return __assign.apply(this, arguments);
  112039. };
  112040. var BABYLON;
  112041. (function (BABYLON) {
  112042. /**
  112043. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  112044. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  112045. * It also helps with the default setup of your imageProcessing configuration.
  112046. */
  112047. var EnvironmentHelper = /** @class */ (function () {
  112048. /**
  112049. * constructor
  112050. * @param options
  112051. * @param scene The scene to add the material to
  112052. */
  112053. function EnvironmentHelper(options, scene) {
  112054. var _this = this;
  112055. this._errorHandler = function (message, exception) {
  112056. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  112057. };
  112058. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  112059. this._scene = scene;
  112060. this.onErrorObservable = new BABYLON.Observable();
  112061. this._setupBackground();
  112062. this._setupImageProcessing();
  112063. }
  112064. /**
  112065. * Creates the default options for the helper.
  112066. */
  112067. EnvironmentHelper._getDefaultOptions = function () {
  112068. return {
  112069. createGround: true,
  112070. groundSize: 15,
  112071. groundTexture: this._groundTextureCDNUrl,
  112072. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  112073. groundOpacity: 0.9,
  112074. enableGroundShadow: true,
  112075. groundShadowLevel: 0.5,
  112076. enableGroundMirror: false,
  112077. groundMirrorSizeRatio: 0.3,
  112078. groundMirrorBlurKernel: 64,
  112079. groundMirrorAmount: 1,
  112080. groundMirrorFresnelWeight: 1,
  112081. groundMirrorFallOffDistance: 0,
  112082. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  112083. groundYBias: 0.00001,
  112084. createSkybox: true,
  112085. skyboxSize: 20,
  112086. skyboxTexture: this._skyboxTextureCDNUrl,
  112087. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  112088. backgroundYRotation: 0,
  112089. sizeAuto: true,
  112090. rootPosition: BABYLON.Vector3.Zero(),
  112091. setupImageProcessing: true,
  112092. environmentTexture: this._environmentTextureCDNUrl,
  112093. cameraExposure: 0.8,
  112094. cameraContrast: 1.2,
  112095. toneMappingEnabled: true,
  112096. };
  112097. };
  112098. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  112099. /**
  112100. * Gets the root mesh created by the helper.
  112101. */
  112102. get: function () {
  112103. return this._rootMesh;
  112104. },
  112105. enumerable: true,
  112106. configurable: true
  112107. });
  112108. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  112109. /**
  112110. * Gets the skybox created by the helper.
  112111. */
  112112. get: function () {
  112113. return this._skybox;
  112114. },
  112115. enumerable: true,
  112116. configurable: true
  112117. });
  112118. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  112119. /**
  112120. * Gets the skybox texture created by the helper.
  112121. */
  112122. get: function () {
  112123. return this._skyboxTexture;
  112124. },
  112125. enumerable: true,
  112126. configurable: true
  112127. });
  112128. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  112129. /**
  112130. * Gets the skybox material created by the helper.
  112131. */
  112132. get: function () {
  112133. return this._skyboxMaterial;
  112134. },
  112135. enumerable: true,
  112136. configurable: true
  112137. });
  112138. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  112139. /**
  112140. * Gets the ground mesh created by the helper.
  112141. */
  112142. get: function () {
  112143. return this._ground;
  112144. },
  112145. enumerable: true,
  112146. configurable: true
  112147. });
  112148. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  112149. /**
  112150. * Gets the ground texture created by the helper.
  112151. */
  112152. get: function () {
  112153. return this._groundTexture;
  112154. },
  112155. enumerable: true,
  112156. configurable: true
  112157. });
  112158. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  112159. /**
  112160. * Gets the ground mirror created by the helper.
  112161. */
  112162. get: function () {
  112163. return this._groundMirror;
  112164. },
  112165. enumerable: true,
  112166. configurable: true
  112167. });
  112168. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  112169. /**
  112170. * Gets the ground mirror render list to helps pushing the meshes
  112171. * you wish in the ground reflection.
  112172. */
  112173. get: function () {
  112174. if (this._groundMirror) {
  112175. return this._groundMirror.renderList;
  112176. }
  112177. return null;
  112178. },
  112179. enumerable: true,
  112180. configurable: true
  112181. });
  112182. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  112183. /**
  112184. * Gets the ground material created by the helper.
  112185. */
  112186. get: function () {
  112187. return this._groundMaterial;
  112188. },
  112189. enumerable: true,
  112190. configurable: true
  112191. });
  112192. /**
  112193. * Updates the background according to the new options
  112194. * @param options
  112195. */
  112196. EnvironmentHelper.prototype.updateOptions = function (options) {
  112197. var newOptions = __assign({}, this._options, options);
  112198. if (this._ground && !newOptions.createGround) {
  112199. this._ground.dispose();
  112200. this._ground = null;
  112201. }
  112202. if (this._groundMaterial && !newOptions.createGround) {
  112203. this._groundMaterial.dispose();
  112204. this._groundMaterial = null;
  112205. }
  112206. if (this._groundTexture) {
  112207. if (this._options.groundTexture != newOptions.groundTexture) {
  112208. this._groundTexture.dispose();
  112209. this._groundTexture = null;
  112210. }
  112211. }
  112212. if (this._skybox && !newOptions.createSkybox) {
  112213. this._skybox.dispose();
  112214. this._skybox = null;
  112215. }
  112216. if (this._skyboxMaterial && !newOptions.createSkybox) {
  112217. this._skyboxMaterial.dispose();
  112218. this._skyboxMaterial = null;
  112219. }
  112220. if (this._skyboxTexture) {
  112221. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  112222. this._skyboxTexture.dispose();
  112223. this._skyboxTexture = null;
  112224. }
  112225. }
  112226. if (this._groundMirror && !newOptions.enableGroundMirror) {
  112227. this._groundMirror.dispose();
  112228. this._groundMirror = null;
  112229. }
  112230. if (this._scene.environmentTexture) {
  112231. if (this._options.environmentTexture != newOptions.environmentTexture) {
  112232. this._scene.environmentTexture.dispose();
  112233. }
  112234. }
  112235. this._options = newOptions;
  112236. this._setupBackground();
  112237. this._setupImageProcessing();
  112238. };
  112239. /**
  112240. * Sets the primary color of all the available elements.
  112241. * @param color the main color to affect to the ground and the background
  112242. */
  112243. EnvironmentHelper.prototype.setMainColor = function (color) {
  112244. if (this.groundMaterial) {
  112245. this.groundMaterial.primaryColor = color;
  112246. }
  112247. if (this.skyboxMaterial) {
  112248. this.skyboxMaterial.primaryColor = color;
  112249. }
  112250. if (this.groundMirror) {
  112251. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  112252. }
  112253. };
  112254. /**
  112255. * Setup the image processing according to the specified options.
  112256. */
  112257. EnvironmentHelper.prototype._setupImageProcessing = function () {
  112258. if (this._options.setupImageProcessing) {
  112259. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  112260. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  112261. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  112262. this._setupEnvironmentTexture();
  112263. }
  112264. };
  112265. /**
  112266. * Setup the environment texture according to the specified options.
  112267. */
  112268. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  112269. if (this._scene.environmentTexture) {
  112270. return;
  112271. }
  112272. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  112273. this._scene.environmentTexture = this._options.environmentTexture;
  112274. return;
  112275. }
  112276. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  112277. this._scene.environmentTexture = environmentTexture;
  112278. };
  112279. /**
  112280. * Setup the background according to the specified options.
  112281. */
  112282. EnvironmentHelper.prototype._setupBackground = function () {
  112283. if (!this._rootMesh) {
  112284. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  112285. }
  112286. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  112287. var sceneSize = this._getSceneSize();
  112288. if (this._options.createGround) {
  112289. this._setupGround(sceneSize);
  112290. this._setupGroundMaterial();
  112291. this._setupGroundDiffuseTexture();
  112292. if (this._options.enableGroundMirror) {
  112293. this._setupGroundMirrorTexture(sceneSize);
  112294. }
  112295. this._setupMirrorInGroundMaterial();
  112296. }
  112297. if (this._options.createSkybox) {
  112298. this._setupSkybox(sceneSize);
  112299. this._setupSkyboxMaterial();
  112300. this._setupSkyboxReflectionTexture();
  112301. }
  112302. this._rootMesh.position.x = sceneSize.rootPosition.x;
  112303. this._rootMesh.position.z = sceneSize.rootPosition.z;
  112304. this._rootMesh.position.y = sceneSize.rootPosition.y;
  112305. };
  112306. /**
  112307. * Get the scene sizes according to the setup.
  112308. */
  112309. EnvironmentHelper.prototype._getSceneSize = function () {
  112310. var _this = this;
  112311. var groundSize = this._options.groundSize;
  112312. var skyboxSize = this._options.skyboxSize;
  112313. var rootPosition = this._options.rootPosition;
  112314. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  112315. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  112316. }
  112317. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  112318. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  112319. });
  112320. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  112321. if (this._options.sizeAuto) {
  112322. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  112323. this._scene.activeCamera.upperRadiusLimit) {
  112324. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  112325. skyboxSize = groundSize;
  112326. }
  112327. var sceneDiagonalLenght = sceneDiagonal.length();
  112328. if (sceneDiagonalLenght > groundSize) {
  112329. groundSize = sceneDiagonalLenght * 2;
  112330. skyboxSize = groundSize;
  112331. }
  112332. // 10 % bigger.
  112333. groundSize *= 1.1;
  112334. skyboxSize *= 1.5;
  112335. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  112336. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  112337. }
  112338. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  112339. };
  112340. /**
  112341. * Setup the ground according to the specified options.
  112342. */
  112343. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  112344. var _this = this;
  112345. if (!this._ground || this._ground.isDisposed()) {
  112346. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  112347. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  112348. this._ground.parent = this._rootMesh;
  112349. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  112350. }
  112351. this._ground.receiveShadows = this._options.enableGroundShadow;
  112352. };
  112353. /**
  112354. * Setup the ground material according to the specified options.
  112355. */
  112356. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  112357. if (!this._groundMaterial) {
  112358. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  112359. }
  112360. this._groundMaterial.alpha = this._options.groundOpacity;
  112361. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  112362. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  112363. this._groundMaterial.primaryColor = this._options.groundColor;
  112364. this._groundMaterial.useRGBColor = false;
  112365. this._groundMaterial.enableNoise = true;
  112366. if (this._ground) {
  112367. this._ground.material = this._groundMaterial;
  112368. }
  112369. };
  112370. /**
  112371. * Setup the ground diffuse texture according to the specified options.
  112372. */
  112373. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  112374. if (!this._groundMaterial) {
  112375. return;
  112376. }
  112377. if (this._groundTexture) {
  112378. return;
  112379. }
  112380. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  112381. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  112382. return;
  112383. }
  112384. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  112385. diffuseTexture.gammaSpace = false;
  112386. diffuseTexture.hasAlpha = true;
  112387. this._groundMaterial.diffuseTexture = diffuseTexture;
  112388. };
  112389. /**
  112390. * Setup the ground mirror texture according to the specified options.
  112391. */
  112392. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  112393. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112394. if (!this._groundMirror) {
  112395. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  112396. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  112397. this._groundMirror.anisotropicFilteringLevel = 1;
  112398. this._groundMirror.wrapU = wrapping;
  112399. this._groundMirror.wrapV = wrapping;
  112400. this._groundMirror.gammaSpace = false;
  112401. if (this._groundMirror.renderList) {
  112402. for (var i = 0; i < this._scene.meshes.length; i++) {
  112403. var mesh = this._scene.meshes[i];
  112404. if (mesh !== this._ground &&
  112405. mesh !== this._skybox &&
  112406. mesh !== this._rootMesh) {
  112407. this._groundMirror.renderList.push(mesh);
  112408. }
  112409. }
  112410. }
  112411. }
  112412. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  112413. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  112414. };
  112415. /**
  112416. * Setup the ground to receive the mirror texture.
  112417. */
  112418. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  112419. if (this._groundMaterial) {
  112420. this._groundMaterial.reflectionTexture = this._groundMirror;
  112421. this._groundMaterial.reflectionFresnel = true;
  112422. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  112423. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  112424. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  112425. }
  112426. };
  112427. /**
  112428. * Setup the skybox according to the specified options.
  112429. */
  112430. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  112431. var _this = this;
  112432. if (!this._skybox || this._skybox.isDisposed()) {
  112433. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  112434. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  112435. }
  112436. this._skybox.parent = this._rootMesh;
  112437. };
  112438. /**
  112439. * Setup the skybox material according to the specified options.
  112440. */
  112441. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  112442. if (!this._skybox) {
  112443. return;
  112444. }
  112445. if (!this._skyboxMaterial) {
  112446. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  112447. }
  112448. this._skyboxMaterial.useRGBColor = false;
  112449. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  112450. this._skyboxMaterial.enableNoise = true;
  112451. this._skybox.material = this._skyboxMaterial;
  112452. };
  112453. /**
  112454. * Setup the skybox reflection texture according to the specified options.
  112455. */
  112456. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  112457. if (!this._skyboxMaterial) {
  112458. return;
  112459. }
  112460. if (this._skyboxTexture) {
  112461. return;
  112462. }
  112463. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  112464. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  112465. return;
  112466. }
  112467. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  112468. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  112469. this._skyboxTexture.gammaSpace = false;
  112470. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  112471. };
  112472. /**
  112473. * Dispose all the elements created by the Helper.
  112474. */
  112475. EnvironmentHelper.prototype.dispose = function () {
  112476. if (this._groundMaterial) {
  112477. this._groundMaterial.dispose(true, true);
  112478. }
  112479. if (this._skyboxMaterial) {
  112480. this._skyboxMaterial.dispose(true, true);
  112481. }
  112482. this._rootMesh.dispose(false);
  112483. };
  112484. /**
  112485. * Default ground texture URL.
  112486. */
  112487. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  112488. /**
  112489. * Default skybox texture URL.
  112490. */
  112491. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  112492. /**
  112493. * Default environment texture URL.
  112494. */
  112495. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  112496. return EnvironmentHelper;
  112497. }());
  112498. BABYLON.EnvironmentHelper = EnvironmentHelper;
  112499. })(BABYLON || (BABYLON = {}));
  112500. //# sourceMappingURL=babylon.environmentHelper.js.map
  112501. var BABYLON;
  112502. (function (BABYLON) {
  112503. /** Internal class used to store shapes for emitters */
  112504. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  112505. function ParticleSystemSetEmitterCreationOptions() {
  112506. }
  112507. return ParticleSystemSetEmitterCreationOptions;
  112508. }());
  112509. /**
  112510. * Represents a set of particle systems working together to create a specific effect
  112511. */
  112512. var ParticleSystemSet = /** @class */ (function () {
  112513. function ParticleSystemSet() {
  112514. /**
  112515. * Gets the particle system list
  112516. */
  112517. this.systems = new Array();
  112518. }
  112519. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  112520. /**
  112521. * Gets the emitter node used with this set
  112522. */
  112523. get: function () {
  112524. return this._emitterNode;
  112525. },
  112526. enumerable: true,
  112527. configurable: true
  112528. });
  112529. /**
  112530. * Creates a new emitter mesh as a sphere
  112531. * @param options defines the options used to create the sphere
  112532. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  112533. * @param scene defines the hosting scene
  112534. */
  112535. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  112536. if (this._emitterNode) {
  112537. this._emitterNode.dispose();
  112538. }
  112539. this._emitterCreationOptions = {
  112540. kind: "Sphere",
  112541. options: options,
  112542. renderingGroupId: renderingGroupId
  112543. };
  112544. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  112545. emitterMesh.renderingGroupId = renderingGroupId;
  112546. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  112547. material.emissiveColor = options.color;
  112548. emitterMesh.material = material;
  112549. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  112550. var system = _a[_i];
  112551. system.emitter = emitterMesh;
  112552. }
  112553. this._emitterNode = emitterMesh;
  112554. };
  112555. /**
  112556. * Starts all particle systems of the set
  112557. * @param emitter defines an optional mesh to use as emitter for the particle systems
  112558. */
  112559. ParticleSystemSet.prototype.start = function (emitter) {
  112560. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  112561. var system = _a[_i];
  112562. if (emitter) {
  112563. system.emitter = emitter;
  112564. }
  112565. system.start();
  112566. }
  112567. };
  112568. /**
  112569. * Release all associated resources
  112570. */
  112571. ParticleSystemSet.prototype.dispose = function () {
  112572. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  112573. var system = _a[_i];
  112574. system.dispose();
  112575. }
  112576. this.systems = [];
  112577. if (this._emitterNode) {
  112578. this._emitterNode.dispose();
  112579. this._emitterNode = null;
  112580. }
  112581. };
  112582. /**
  112583. * Serialize the set into a JSON compatible object
  112584. * @returns a JSON compatible representation of the set
  112585. */
  112586. ParticleSystemSet.prototype.serialize = function () {
  112587. var result = {};
  112588. result.systems = [];
  112589. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  112590. var system = _a[_i];
  112591. result.systems.push(system.serialize());
  112592. }
  112593. if (this._emitterNode) {
  112594. result.emitter = this._emitterCreationOptions;
  112595. }
  112596. return result;
  112597. };
  112598. /**
  112599. * Parse a new ParticleSystemSet from a serialized source
  112600. * @param data defines a JSON compatible representation of the set
  112601. * @param scene defines the hosting scene
  112602. * @param gpu defines if we want GPU particles or CPU particles
  112603. * @returns a new ParticleSystemSet
  112604. */
  112605. ParticleSystemSet.Parse = function (data, scene, gpu) {
  112606. if (gpu === void 0) { gpu = false; }
  112607. var result = new ParticleSystemSet();
  112608. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  112609. scene = scene || BABYLON.Engine.LastCreatedScene;
  112610. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  112611. var system = _a[_i];
  112612. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  112613. }
  112614. if (data.emitter) {
  112615. var options = data.emitter.options;
  112616. switch (data.emitter.kind) {
  112617. case "Sphere":
  112618. result.setEmitterAsSphere({
  112619. diameter: options.diameter,
  112620. segments: options.segments,
  112621. color: BABYLON.Color3.FromArray(options.color)
  112622. }, data.emitter.renderingGroupId, scene);
  112623. break;
  112624. }
  112625. }
  112626. return result;
  112627. };
  112628. return ParticleSystemSet;
  112629. }());
  112630. BABYLON.ParticleSystemSet = ParticleSystemSet;
  112631. })(BABYLON || (BABYLON = {}));
  112632. //# sourceMappingURL=babylon.particleSystemSet.js.map
  112633. var BABYLON;
  112634. (function (BABYLON) {
  112635. /**
  112636. * This class is made for on one-liner static method to help creating particle system set.
  112637. */
  112638. var ParticleHelper = /** @class */ (function () {
  112639. function ParticleHelper() {
  112640. }
  112641. /**
  112642. * Create a default particle system that you can tweak
  112643. * @param emitter defines the emitter to use
  112644. * @param capacity defines the system capacity (default is 500 particles)
  112645. * @param scene defines the hosting scene
  112646. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  112647. * @returns the new Particle system
  112648. */
  112649. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  112650. if (capacity === void 0) { capacity = 500; }
  112651. if (useGPU === void 0) { useGPU = false; }
  112652. var system;
  112653. if (useGPU) {
  112654. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  112655. }
  112656. else {
  112657. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  112658. }
  112659. system.emitter = emitter;
  112660. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  112661. system.createConeEmitter(0.1, Math.PI / 4);
  112662. // Particle color
  112663. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  112664. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  112665. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  112666. // Particle Size
  112667. system.minSize = 0.1;
  112668. system.maxSize = 0.1;
  112669. // Emission speed
  112670. system.minEmitPower = 2;
  112671. system.maxEmitPower = 2;
  112672. // Update speed
  112673. system.updateSpeed = 1 / 60;
  112674. system.emitRate = 30;
  112675. return system;
  112676. };
  112677. /**
  112678. * This is the main static method (one-liner) of this helper to create different particle systems
  112679. * @param type This string represents the type to the particle system to create
  112680. * @param scene The scene where the particle system should live
  112681. * @param gpu If the system will use gpu
  112682. * @returns the ParticleSystemSet created
  112683. */
  112684. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  112685. if (gpu === void 0) { gpu = false; }
  112686. if (!scene) {
  112687. scene = BABYLON.Engine.LastCreatedScene;
  112688. ;
  112689. }
  112690. var token = {};
  112691. scene._addPendingData(token);
  112692. return new Promise(function (resolve, reject) {
  112693. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  112694. scene._removePendingData(token);
  112695. return reject("Particle system with GPU is not supported.");
  112696. }
  112697. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  112698. scene._removePendingData(token);
  112699. var newData = JSON.parse(data.toString());
  112700. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  112701. }, undefined, undefined, undefined, function (req, exception) {
  112702. scene._removePendingData(token);
  112703. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  112704. });
  112705. });
  112706. };
  112707. /**
  112708. * Static function used to export a particle system to a ParticleSystemSet variable.
  112709. * Please note that the emitter shape is not exported
  112710. * @param system defines the particle systems to export
  112711. */
  112712. ParticleHelper.ExportSet = function (systems) {
  112713. var set = new BABYLON.ParticleSystemSet();
  112714. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  112715. var system = systems_1[_i];
  112716. set.systems.push(system);
  112717. }
  112718. return set;
  112719. };
  112720. /**
  112721. * Gets or sets base Assets URL
  112722. */
  112723. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  112724. return ParticleHelper;
  112725. }());
  112726. BABYLON.ParticleHelper = ParticleHelper;
  112727. })(BABYLON || (BABYLON = {}));
  112728. //# sourceMappingURL=babylon.particleHelper.js.map
  112729. var BABYLON;
  112730. (function (BABYLON) {
  112731. /**
  112732. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  112733. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  112734. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  112735. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  112736. */
  112737. var VideoDome = /** @class */ (function (_super) {
  112738. __extends(VideoDome, _super);
  112739. /**
  112740. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  112741. * @param name Element's name, child elements will append suffixes for their own names.
  112742. * @param urlsOrVideo defines the url(s) or the video element to use
  112743. * @param options An object containing optional or exposed sub element properties
  112744. */
  112745. function VideoDome(name, urlsOrVideo, options, scene) {
  112746. var _this = _super.call(this, name, scene) || this;
  112747. _this._useDirectMapping = false;
  112748. // set defaults and manage values
  112749. name = name || "videoDome";
  112750. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  112751. options.clickToPlay = Boolean(options.clickToPlay);
  112752. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  112753. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  112754. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  112755. if (options.useDirectMapping === undefined) {
  112756. _this._useDirectMapping = true;
  112757. }
  112758. else {
  112759. _this._useDirectMapping = options.useDirectMapping;
  112760. }
  112761. _this._setReady(false);
  112762. // create
  112763. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  112764. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  112765. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  112766. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  112767. texture.onLoadObservable.addOnce(function () {
  112768. _this._setReady(true);
  112769. });
  112770. // configure material
  112771. material.useEquirectangularFOV = true;
  112772. material.fovMultiplier = 1.0;
  112773. material.opacityFresnel = false;
  112774. if (_this._useDirectMapping) {
  112775. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112776. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112777. material.diffuseTexture = texture;
  112778. }
  112779. else {
  112780. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  112781. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112782. material.reflectionTexture = texture;
  112783. }
  112784. // configure mesh
  112785. _this._mesh.material = material;
  112786. _this._mesh.parent = _this;
  112787. // optional configuration
  112788. if (options.clickToPlay) {
  112789. scene.onPointerUp = function () {
  112790. _this._videoTexture.video.play();
  112791. };
  112792. }
  112793. return _this;
  112794. }
  112795. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  112796. /**
  112797. * Gets the video texture being displayed on the sphere
  112798. */
  112799. get: function () {
  112800. return this._videoTexture;
  112801. },
  112802. enumerable: true,
  112803. configurable: true
  112804. });
  112805. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  112806. /**
  112807. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  112808. * Also see the options.resolution property.
  112809. */
  112810. get: function () {
  112811. return this._material.fovMultiplier;
  112812. },
  112813. set: function (value) {
  112814. this._material.fovMultiplier = value;
  112815. },
  112816. enumerable: true,
  112817. configurable: true
  112818. });
  112819. /**
  112820. * Releases resources associated with this node.
  112821. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  112822. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  112823. */
  112824. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  112825. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  112826. this._videoTexture.dispose();
  112827. this._mesh.dispose();
  112828. this._material.dispose();
  112829. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  112830. };
  112831. return VideoDome;
  112832. }(BABYLON.TransformNode));
  112833. BABYLON.VideoDome = VideoDome;
  112834. })(BABYLON || (BABYLON = {}));
  112835. //# sourceMappingURL=babylon.videoDome.js.map
  112836. var BABYLON;
  112837. (function (BABYLON) {
  112838. /**
  112839. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  112840. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  112841. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  112842. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  112843. */
  112844. var PhotoDome = /** @class */ (function (_super) {
  112845. __extends(PhotoDome, _super);
  112846. /**
  112847. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  112848. * @param name Element's name, child elements will append suffixes for their own names.
  112849. * @param urlsOfPhoto defines the url of the photo to display
  112850. * @param options defines an object containing optional or exposed sub element properties
  112851. * @param onError defines a callback called when an error occured while loading the texture
  112852. */
  112853. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  112854. if (onError === void 0) { onError = null; }
  112855. var _this = _super.call(this, name, scene) || this;
  112856. _this._useDirectMapping = false;
  112857. /**
  112858. * Observable raised when an error occured while loading the 360 image
  112859. */
  112860. _this.onLoadErrorObservable = new BABYLON.Observable();
  112861. // set defaults and manage values
  112862. name = name || "photoDome";
  112863. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  112864. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  112865. if (options.useDirectMapping === undefined) {
  112866. _this._useDirectMapping = true;
  112867. }
  112868. else {
  112869. _this._useDirectMapping = options.useDirectMapping;
  112870. }
  112871. _this._setReady(false);
  112872. // create
  112873. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  112874. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  112875. // configure material
  112876. material.opacityFresnel = false;
  112877. material.useEquirectangularFOV = true;
  112878. material.fovMultiplier = 1.0;
  112879. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  112880. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  112881. if (onError) {
  112882. onError(message, exception);
  112883. }
  112884. });
  112885. _this.photoTexture.onLoadObservable.addOnce(function () {
  112886. _this._setReady(true);
  112887. });
  112888. // configure mesh
  112889. _this._mesh.material = material;
  112890. _this._mesh.parent = _this;
  112891. return _this;
  112892. }
  112893. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  112894. /**
  112895. * Gets or sets the texture being displayed on the sphere
  112896. */
  112897. get: function () {
  112898. return this._photoTexture;
  112899. },
  112900. set: function (value) {
  112901. if (this._photoTexture === value) {
  112902. return;
  112903. }
  112904. this._photoTexture = value;
  112905. if (this._useDirectMapping) {
  112906. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112907. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112908. this._material.diffuseTexture = this._photoTexture;
  112909. }
  112910. else {
  112911. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  112912. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112913. this._material.reflectionTexture = this._photoTexture;
  112914. }
  112915. },
  112916. enumerable: true,
  112917. configurable: true
  112918. });
  112919. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  112920. /**
  112921. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  112922. * Also see the options.resolution property.
  112923. */
  112924. get: function () {
  112925. return this._material.fovMultiplier;
  112926. },
  112927. set: function (value) {
  112928. this._material.fovMultiplier = value;
  112929. },
  112930. enumerable: true,
  112931. configurable: true
  112932. });
  112933. /**
  112934. * Releases resources associated with this node.
  112935. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  112936. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  112937. */
  112938. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  112939. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  112940. this._photoTexture.dispose();
  112941. this._mesh.dispose();
  112942. this._material.dispose();
  112943. this.onLoadErrorObservable.clear();
  112944. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  112945. };
  112946. return PhotoDome;
  112947. }(BABYLON.TransformNode));
  112948. BABYLON.PhotoDome = PhotoDome;
  112949. })(BABYLON || (BABYLON = {}));
  112950. //# sourceMappingURL=babylon.photoDome.js.map
  112951. var BABYLON;
  112952. (function (BABYLON) {
  112953. /** @hidden */
  112954. var _OcclusionDataStorage = /** @class */ (function () {
  112955. function _OcclusionDataStorage() {
  112956. /** @hidden */
  112957. this.occlusionInternalRetryCounter = 0;
  112958. /** @hidden */
  112959. this.isOcclusionQueryInProgress = false;
  112960. /** @hidden */
  112961. this.isOccluded = false;
  112962. /** @hidden */
  112963. this.occlusionRetryCount = -1;
  112964. /** @hidden */
  112965. this.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE;
  112966. /** @hidden */
  112967. this.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  112968. }
  112969. return _OcclusionDataStorage;
  112970. }());
  112971. BABYLON.Engine.prototype.createQuery = function () {
  112972. return this._gl.createQuery();
  112973. };
  112974. BABYLON.Engine.prototype.deleteQuery = function (query) {
  112975. this._gl.deleteQuery(query);
  112976. return this;
  112977. };
  112978. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  112979. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  112980. };
  112981. BABYLON.Engine.prototype.getQueryResult = function (query) {
  112982. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  112983. };
  112984. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  112985. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  112986. this._gl.beginQuery(glAlgorithm, query);
  112987. return this;
  112988. };
  112989. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  112990. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  112991. this._gl.endQuery(glAlgorithm);
  112992. return this;
  112993. };
  112994. BABYLON.Engine.prototype._createTimeQuery = function () {
  112995. var timerQuery = this.getCaps().timerQuery;
  112996. if (timerQuery.createQueryEXT) {
  112997. return timerQuery.createQueryEXT();
  112998. }
  112999. return this.createQuery();
  113000. };
  113001. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  113002. var timerQuery = this.getCaps().timerQuery;
  113003. if (timerQuery.deleteQueryEXT) {
  113004. timerQuery.deleteQueryEXT(query);
  113005. return;
  113006. }
  113007. this.deleteQuery(query);
  113008. };
  113009. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  113010. var timerQuery = this.getCaps().timerQuery;
  113011. if (timerQuery.getQueryObjectEXT) {
  113012. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  113013. }
  113014. return this.getQueryResult(query);
  113015. };
  113016. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  113017. var timerQuery = this.getCaps().timerQuery;
  113018. if (timerQuery.getQueryObjectEXT) {
  113019. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  113020. }
  113021. return this.isQueryResultAvailable(query);
  113022. };
  113023. BABYLON.Engine.prototype.startTimeQuery = function () {
  113024. var caps = this.getCaps();
  113025. var timerQuery = caps.timerQuery;
  113026. if (!timerQuery) {
  113027. return null;
  113028. }
  113029. var token = new BABYLON._TimeToken();
  113030. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  113031. if (caps.canUseTimestampForTimerQuery) {
  113032. token._startTimeQuery = this._createTimeQuery();
  113033. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  113034. }
  113035. else {
  113036. if (this._currentNonTimestampToken) {
  113037. return this._currentNonTimestampToken;
  113038. }
  113039. token._timeElapsedQuery = this._createTimeQuery();
  113040. if (timerQuery.beginQueryEXT) {
  113041. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  113042. }
  113043. else {
  113044. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  113045. }
  113046. this._currentNonTimestampToken = token;
  113047. }
  113048. return token;
  113049. };
  113050. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  113051. var caps = this.getCaps();
  113052. var timerQuery = caps.timerQuery;
  113053. if (!timerQuery || !token) {
  113054. return -1;
  113055. }
  113056. if (caps.canUseTimestampForTimerQuery) {
  113057. if (!token._startTimeQuery) {
  113058. return -1;
  113059. }
  113060. if (!token._endTimeQuery) {
  113061. token._endTimeQuery = this._createTimeQuery();
  113062. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  113063. }
  113064. }
  113065. else if (!token._timeElapsedQueryEnded) {
  113066. if (!token._timeElapsedQuery) {
  113067. return -1;
  113068. }
  113069. if (timerQuery.endQueryEXT) {
  113070. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  113071. }
  113072. else {
  113073. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  113074. }
  113075. token._timeElapsedQueryEnded = true;
  113076. }
  113077. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  113078. var available = false;
  113079. if (token._endTimeQuery) {
  113080. available = this._getTimeQueryAvailability(token._endTimeQuery);
  113081. }
  113082. else if (token._timeElapsedQuery) {
  113083. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  113084. }
  113085. if (available && !disjoint) {
  113086. var result = 0;
  113087. if (caps.canUseTimestampForTimerQuery) {
  113088. if (!token._startTimeQuery || !token._endTimeQuery) {
  113089. return -1;
  113090. }
  113091. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  113092. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  113093. result = timeEnd - timeStart;
  113094. this._deleteTimeQuery(token._startTimeQuery);
  113095. this._deleteTimeQuery(token._endTimeQuery);
  113096. token._startTimeQuery = null;
  113097. token._endTimeQuery = null;
  113098. }
  113099. else {
  113100. if (!token._timeElapsedQuery) {
  113101. return -1;
  113102. }
  113103. result = this._getTimeQueryResult(token._timeElapsedQuery);
  113104. this._deleteTimeQuery(token._timeElapsedQuery);
  113105. token._timeElapsedQuery = null;
  113106. token._timeElapsedQueryEnded = false;
  113107. this._currentNonTimestampToken = null;
  113108. }
  113109. return result;
  113110. }
  113111. return -1;
  113112. };
  113113. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  113114. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  113115. };
  113116. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  113117. get: function () {
  113118. return this._occlusionDataStorage.isOcclusionQueryInProgress;
  113119. },
  113120. enumerable: false,
  113121. configurable: true
  113122. });
  113123. Object.defineProperty(BABYLON.AbstractMesh.prototype, "_occlusionDataStorage", {
  113124. get: function () {
  113125. if (!this.__occlusionDataStorage) {
  113126. this.__occlusionDataStorage = new _OcclusionDataStorage();
  113127. }
  113128. return this.__occlusionDataStorage;
  113129. },
  113130. enumerable: false,
  113131. configurable: true
  113132. });
  113133. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOccluded", {
  113134. get: function () {
  113135. return this._occlusionDataStorage.isOccluded;
  113136. },
  113137. set: function (value) {
  113138. this._occlusionDataStorage.isOccluded = value;
  113139. },
  113140. enumerable: true,
  113141. configurable: true
  113142. });
  113143. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
  113144. get: function () {
  113145. return this._occlusionDataStorage.occlusionQueryAlgorithmType;
  113146. },
  113147. set: function (value) {
  113148. this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
  113149. },
  113150. enumerable: true,
  113151. configurable: true
  113152. });
  113153. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionType", {
  113154. get: function () {
  113155. return this._occlusionDataStorage.occlusionType;
  113156. },
  113157. set: function (value) {
  113158. this._occlusionDataStorage.occlusionType = value;
  113159. },
  113160. enumerable: true,
  113161. configurable: true
  113162. });
  113163. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionRetryCount", {
  113164. get: function () {
  113165. return this._occlusionDataStorage.occlusionRetryCount;
  113166. },
  113167. set: function (value) {
  113168. this._occlusionDataStorage.occlusionRetryCount = value;
  113169. },
  113170. enumerable: true,
  113171. configurable: true
  113172. });
  113173. // We also need to update AbstractMesh as there is a portion of the code there
  113174. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  113175. var dataStorage = this._occlusionDataStorage;
  113176. if (dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  113177. dataStorage.isOccluded = false;
  113178. return false;
  113179. }
  113180. var engine = this.getEngine();
  113181. if (engine.webGLVersion < 2) {
  113182. dataStorage.isOccluded = false;
  113183. return false;
  113184. }
  113185. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  113186. dataStorage.isOccluded = false;
  113187. return false;
  113188. }
  113189. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  113190. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  113191. if (isOcclusionQueryAvailable) {
  113192. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  113193. dataStorage.isOcclusionQueryInProgress = false;
  113194. dataStorage.occlusionInternalRetryCounter = 0;
  113195. dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
  113196. }
  113197. else {
  113198. dataStorage.occlusionInternalRetryCounter++;
  113199. if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
  113200. dataStorage.isOcclusionQueryInProgress = false;
  113201. dataStorage.occlusionInternalRetryCounter = 0;
  113202. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  113203. // if strict continue the last state of the object.
  113204. dataStorage.isOccluded = dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
  113205. }
  113206. else {
  113207. return false;
  113208. }
  113209. }
  113210. }
  113211. var scene = this.getScene();
  113212. if (scene.getBoundingBoxRenderer) {
  113213. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  113214. if (!this._occlusionQuery) {
  113215. this._occlusionQuery = engine.createQuery();
  113216. }
  113217. engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
  113218. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  113219. engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
  113220. this._occlusionDataStorage.isOcclusionQueryInProgress = true;
  113221. }
  113222. return dataStorage.isOccluded;
  113223. };
  113224. })(BABYLON || (BABYLON = {}));
  113225. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  113226. var BABYLON;
  113227. (function (BABYLON) {
  113228. /**
  113229. * Class used to generate noise procedural textures
  113230. */
  113231. var NoiseProceduralTexture = /** @class */ (function (_super) {
  113232. __extends(NoiseProceduralTexture, _super);
  113233. /**
  113234. * Creates a new NoiseProceduralTexture
  113235. * @param name defines the name fo the texture
  113236. * @param size defines the size of the texture (default is 256)
  113237. * @param scene defines the hosting scene
  113238. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  113239. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  113240. */
  113241. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  113242. if (size === void 0) { size = 256; }
  113243. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  113244. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  113245. _this._time = 0;
  113246. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  113247. _this.brightness = 0.2;
  113248. /** Defines the number of octaves to process */
  113249. _this.octaves = 3;
  113250. /** Defines the level of persistence (0.8 by default) */
  113251. _this.persistence = 0.8;
  113252. /** Gets or sets animation speed factor (default is 1) */
  113253. _this.animationSpeedFactor = 1;
  113254. _this._updateShaderUniforms();
  113255. return _this;
  113256. }
  113257. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  113258. var scene = this.getScene();
  113259. if (!scene) {
  113260. return;
  113261. }
  113262. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  113263. this.setFloat("brightness", this.brightness);
  113264. this.setFloat("persistence", this.persistence);
  113265. this.setFloat("timeScale", this._time);
  113266. };
  113267. NoiseProceduralTexture.prototype._getDefines = function () {
  113268. return "#define OCTAVES " + (this.octaves | 0);
  113269. };
  113270. /** Generate the current state of the procedural texture */
  113271. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  113272. this._updateShaderUniforms();
  113273. _super.prototype.render.call(this, useCameraPostProcess);
  113274. };
  113275. /**
  113276. * Serializes this noise procedural texture
  113277. * @returns a serialized noise procedural texture object
  113278. */
  113279. NoiseProceduralTexture.prototype.serialize = function () {
  113280. var serializationObject = {};
  113281. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  113282. serializationObject.brightness = this.brightness;
  113283. serializationObject.octaves = this.octaves;
  113284. serializationObject.persistence = this.persistence;
  113285. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  113286. serializationObject.size = this.getSize().width;
  113287. serializationObject.generateMipMaps = this._generateMipMaps;
  113288. return serializationObject;
  113289. };
  113290. /**
  113291. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  113292. * @param parsedTexture defines parsed texture data
  113293. * @param scene defines the current scene
  113294. * @param rootUrl defines the root URL containing noise procedural texture information
  113295. * @returns a parsed NoiseProceduralTexture
  113296. */
  113297. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  113298. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  113299. texture.brightness = parsedTexture.brightness;
  113300. texture.octaves = parsedTexture.octaves;
  113301. texture.persistence = parsedTexture.persistence;
  113302. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  113303. return texture;
  113304. };
  113305. return NoiseProceduralTexture;
  113306. }(BABYLON.ProceduralTexture));
  113307. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  113308. })(BABYLON || (BABYLON = {}));
  113309. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  113310. var __assign = (this && this.__assign) || function () {
  113311. __assign = Object.assign || function(t) {
  113312. for (var s, i = 1, n = arguments.length; i < n; i++) {
  113313. s = arguments[i];
  113314. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  113315. t[p] = s[p];
  113316. }
  113317. return t;
  113318. };
  113319. return __assign.apply(this, arguments);
  113320. };
  113321. var BABYLON;
  113322. (function (BABYLON) {
  113323. /**
  113324. * This can helps recording videos from BabylonJS.
  113325. * This is based on the available WebRTC functionalities of the browser.
  113326. *
  113327. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  113328. */
  113329. var VideoRecorder = /** @class */ (function () {
  113330. /**
  113331. * Create a new VideoCapture object which can help converting what you see in Babylon to
  113332. * a video file.
  113333. * @param engine Defines the BabylonJS Engine you wish to record
  113334. * @param options Defines options that can be used to customized the capture
  113335. */
  113336. function VideoRecorder(engine, options) {
  113337. if (options === void 0) { options = null; }
  113338. if (!VideoRecorder.IsSupported(engine)) {
  113339. throw "Your browser does not support recording so far.";
  113340. }
  113341. var canvas = engine.getRenderingCanvas();
  113342. if (!canvas) {
  113343. throw "The babylon engine must have a canvas to be recorded";
  113344. }
  113345. this._canvas = canvas;
  113346. this._canvas.isRecording = false;
  113347. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  113348. var stream = this._canvas.captureStream(this._options.fps);
  113349. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  113350. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  113351. this._mediaRecorder.onerror = this._handleError.bind(this);
  113352. this._mediaRecorder.onstop = this._handleStop.bind(this);
  113353. }
  113354. /**
  113355. * Returns wehther or not the VideoRecorder is available in your browser.
  113356. * @param engine Defines the Babylon Engine to check the support for
  113357. * @returns true if supported otherwise false
  113358. */
  113359. VideoRecorder.IsSupported = function (engine) {
  113360. var canvas = engine.getRenderingCanvas();
  113361. return (!!canvas && typeof canvas.captureStream === "function");
  113362. };
  113363. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  113364. /**
  113365. * True wether a recording is already in progress.
  113366. */
  113367. get: function () {
  113368. return !!this._canvas && this._canvas.isRecording;
  113369. },
  113370. enumerable: true,
  113371. configurable: true
  113372. });
  113373. /**
  113374. * Stops the current recording before the default capture timeout passed in the startRecording
  113375. * functions.
  113376. */
  113377. VideoRecorder.prototype.stopRecording = function () {
  113378. if (!this._canvas || !this._mediaRecorder) {
  113379. return;
  113380. }
  113381. if (!this.isRecording) {
  113382. return;
  113383. }
  113384. this._canvas.isRecording = false;
  113385. this._mediaRecorder.stop();
  113386. };
  113387. /**
  113388. * Starts recording the canvas for a max duration specified in parameters.
  113389. * @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.
  113390. * @param maxDuration Defines the maximum recording time in seconds.
  113391. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  113392. * @return a promise callback at the end of the recording with the video data in Blob.
  113393. */
  113394. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  113395. var _this = this;
  113396. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  113397. if (maxDuration === void 0) { maxDuration = 7; }
  113398. if (!this._canvas || !this._mediaRecorder) {
  113399. throw "Recorder has already been disposed";
  113400. }
  113401. if (this.isRecording) {
  113402. throw "Recording already in progress";
  113403. }
  113404. if (maxDuration > 0) {
  113405. setTimeout(function () {
  113406. _this.stopRecording();
  113407. }, maxDuration * 1000);
  113408. }
  113409. this._fileName = fileName;
  113410. this._recordedChunks = [];
  113411. this._resolve = null;
  113412. this._reject = null;
  113413. this._canvas.isRecording = true;
  113414. this._mediaRecorder.start(this._options.recordChunckSize);
  113415. return new Promise(function (resolve, reject) {
  113416. _this._resolve = resolve;
  113417. _this._reject = reject;
  113418. });
  113419. };
  113420. /**
  113421. * Releases internal resources used during the recording.
  113422. */
  113423. VideoRecorder.prototype.dispose = function () {
  113424. this._canvas = null;
  113425. this._mediaRecorder = null;
  113426. this._recordedChunks = [];
  113427. this._fileName = null;
  113428. this._resolve = null;
  113429. this._reject = null;
  113430. };
  113431. VideoRecorder.prototype._handleDataAvailable = function (event) {
  113432. if (event.data.size > 0) {
  113433. this._recordedChunks.push(event.data);
  113434. }
  113435. };
  113436. VideoRecorder.prototype._handleError = function (event) {
  113437. this.stopRecording();
  113438. if (this._reject) {
  113439. this._reject(event.error);
  113440. }
  113441. else {
  113442. throw new event.error;
  113443. }
  113444. };
  113445. VideoRecorder.prototype._handleStop = function () {
  113446. this.stopRecording();
  113447. var superBuffer = new Blob(this._recordedChunks);
  113448. if (this._resolve) {
  113449. this._resolve(superBuffer);
  113450. }
  113451. window.URL.createObjectURL(superBuffer);
  113452. if (this._fileName) {
  113453. BABYLON.Tools.Download(superBuffer, this._fileName);
  113454. }
  113455. };
  113456. VideoRecorder._defaultOptions = {
  113457. mimeType: "video/webm",
  113458. fps: 25,
  113459. recordChunckSize: 3000
  113460. };
  113461. return VideoRecorder;
  113462. }());
  113463. BABYLON.VideoRecorder = VideoRecorder;
  113464. })(BABYLON || (BABYLON = {}));
  113465. //# sourceMappingURL=babylon.videoRecorder.js.map
  113466. var BABYLON;
  113467. (function (BABYLON) {
  113468. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  113469. if (replace === void 0) { replace = false; }
  113470. // Dispose existing light in replace mode.
  113471. if (replace) {
  113472. if (this.lights) {
  113473. for (var i = 0; i < this.lights.length; i++) {
  113474. this.lights[i].dispose();
  113475. }
  113476. }
  113477. }
  113478. // Light
  113479. if (this.lights.length === 0) {
  113480. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  113481. }
  113482. };
  113483. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  113484. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  113485. if (replace === void 0) { replace = false; }
  113486. if (attachCameraControls === void 0) { attachCameraControls = false; }
  113487. // Dispose existing camera in replace mode.
  113488. if (replace) {
  113489. if (this.activeCamera) {
  113490. this.activeCamera.dispose();
  113491. this.activeCamera = null;
  113492. }
  113493. }
  113494. // Camera
  113495. if (!this.activeCamera) {
  113496. var worldExtends = this.getWorldExtends();
  113497. var worldSize = worldExtends.max.subtract(worldExtends.min);
  113498. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  113499. var camera;
  113500. var radius = worldSize.length() * 1.5;
  113501. // empty scene scenario!
  113502. if (!isFinite(radius)) {
  113503. radius = 1;
  113504. worldCenter.copyFromFloats(0, 0, 0);
  113505. }
  113506. if (createArcRotateCamera) {
  113507. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  113508. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  113509. arcRotateCamera.wheelPrecision = 100 / radius;
  113510. camera = arcRotateCamera;
  113511. }
  113512. else {
  113513. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  113514. freeCamera.setTarget(worldCenter);
  113515. camera = freeCamera;
  113516. }
  113517. camera.minZ = radius * 0.01;
  113518. camera.maxZ = radius * 1000;
  113519. camera.speed = radius * 0.2;
  113520. this.activeCamera = camera;
  113521. var canvas = this.getEngine().getRenderingCanvas();
  113522. if (attachCameraControls && canvas) {
  113523. camera.attachControl(canvas);
  113524. }
  113525. }
  113526. };
  113527. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  113528. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  113529. if (replace === void 0) { replace = false; }
  113530. if (attachCameraControls === void 0) { attachCameraControls = false; }
  113531. this.createDefaultLight(replace);
  113532. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  113533. };
  113534. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  113535. if (pbr === void 0) { pbr = false; }
  113536. if (scale === void 0) { scale = 1000; }
  113537. if (blur === void 0) { blur = 0; }
  113538. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  113539. if (!environmentTexture) {
  113540. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  113541. return null;
  113542. }
  113543. if (setGlobalEnvTexture) {
  113544. if (environmentTexture) {
  113545. this.environmentTexture = environmentTexture;
  113546. }
  113547. }
  113548. // Skybox
  113549. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  113550. if (pbr) {
  113551. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  113552. hdrSkyboxMaterial.backFaceCulling = false;
  113553. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  113554. if (hdrSkyboxMaterial.reflectionTexture) {
  113555. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  113556. }
  113557. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  113558. hdrSkyboxMaterial.disableLighting = true;
  113559. hdrSkyboxMaterial.twoSidedLighting = true;
  113560. hdrSkybox.infiniteDistance = true;
  113561. hdrSkybox.material = hdrSkyboxMaterial;
  113562. }
  113563. else {
  113564. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  113565. skyboxMaterial.backFaceCulling = false;
  113566. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  113567. if (skyboxMaterial.reflectionTexture) {
  113568. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  113569. }
  113570. skyboxMaterial.disableLighting = true;
  113571. hdrSkybox.infiniteDistance = true;
  113572. hdrSkybox.material = skyboxMaterial;
  113573. }
  113574. return hdrSkybox;
  113575. };
  113576. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  113577. if (BABYLON.EnvironmentHelper) {
  113578. return new BABYLON.EnvironmentHelper(options, this);
  113579. }
  113580. return null;
  113581. };
  113582. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  113583. if (webVROptions === void 0) { webVROptions = {}; }
  113584. return new BABYLON.VRExperienceHelper(this, webVROptions);
  113585. };
  113586. })(BABYLON || (BABYLON = {}));
  113587. //# sourceMappingURL=babylon.sceneHelpers.js.map
  113588. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction; \n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nin vec3 direction;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta; \n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  113589. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nvarying float fClipDistance4;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef REFLECTION\nuniform mat4 reflectionMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\n#ifdef TONEMAPPING_ACES\n\n\n\n\n\nconst mat3 ACESInputMat=mat3(\nvec3(0.59719,0.07600,0.02840),\nvec3(0.35458,0.90834,0.13383),\nvec3(0.04823,0.01566,0.83777)\n);\n\nconst mat3 ACESOutputMat=mat3(\nvec3( 1.60475,-0.10208,-0.00327),\nvec3(-0.53108,1.10813,-0.07276),\nvec3(-0.07367,-0.00605,1.07602)\n);\nvec3 RRTAndODTFit(vec3 v)\n{\nvec3 a=v*(v+0.0245786)-0.000090537;\nvec3 b=v*(0.983729*v+0.4329510)+0.238081;\nreturn a/b;\n}\nvec3 ACESFitted(vec3 color)\n{\ncolor=ACESInputMat*color;\n\ncolor=RRTAndODTFit(color);\ncolor=ACESOutputMat*color;\n\ncolor=clamp(color,0.0,1.0);\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\n#ifdef TONEMAPPING_ACES\nresult.rgb=ACESFitted(result.rgb);\n#else\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE2\nif (fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nif (fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nif (fClipDistance4>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\nspotInfo=computeSpotLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\nspotInfo.attenuation=computeDistanceLightFalloff_GLTF(spotInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Physical(spotInfo.lightDistanceSquared);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Standard(spotInfo.lightOffset,light{X}.vLightFalloff.x);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\nspotInfo.attenuation=computeDistanceLightFalloff(spotInfo.lightOffset,spotInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\ninfo=computeSpotLighting(spotInfo,viewDirectionW,normalW,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(POINTLIGHT{X})\npointInfo=computePointLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\npointInfo.attenuation=computeDistanceLightFalloff_GLTF(pointInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npointInfo.attenuation=computeDistanceLightFalloff_Physical(pointInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npointInfo.attenuation=computeDistanceLightFalloff_Standard(pointInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npointInfo.attenuation=computeDistanceLightFalloff(pointInfo.lightOffset,pointInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\ninfo=computePointLighting(pointInfo,viewDirectionW,normalW,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(DIRLIGHT{X})\ninfo=computeDirectionalLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec4 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nstruct pointLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat attenuation;\n};\nstruct spotLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nvec3 directionToLightCenterW;\nfloat attenuation;\n};\nfloat computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/((lightDistanceSquared+0.001));\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nconst float minDistanceSquared=0.01*0.01;\nfloat lightDistanceFalloff=1.0/(max(lightDistanceSquared,minDistanceSquared));\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=clamp(1.0-factor*factor,0.,1.);\nattenuation*=attenuation;\n\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\n\n\n\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=clamp(cd*lightAngleScale+lightAngleOffset,0.,1.);\n\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}\npointLightingInfo computePointLightingInfo(vec4 lightData) {\npointLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nspotLightingInfo computeSpotLightingInfo(vec4 lightData) {\nspotLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.directionToLightCenterW=normalize(result.lightOffset);\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nlightingInfo computePointLighting(pointLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nvec3 lightDirection=normalize(info.lightOffset);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*info.attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(spotLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec4 lightDirection,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+info.directionToLightCenterW);\nNdotL=clamp(dot(vNormal,info.directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*info.attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeDirectionalLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=length(-lightData.xyz);\nvec3 lightDirection=normalize(-lightData.xyz);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","clipPlaneVertexDeclaration2":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nout float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nout float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nout float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nout float fClipDistance4;\n#endif","clipPlaneFragmentDeclaration2":"#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};